我有一个(相当大的)JSON对象数组,每个对象都包含一个纬度和经度值。当我的Google地图加载时,我循环遍历这个数组并创建一个新标记,将其添加到地图上。
除此之外,我正在使用Google Maps Api v3 Places插件(基本上是从这个示例中直接使用:https://developers.google.com/maps/documentation/javascript/examples/places-searchbox)
当我搜索特定地址时,我需要确保至少N个标记在地图上可见。现在,我将缩放级别设置为始终为10。然而,当我搜索例如法罗群岛(只有大约5个标记)时,缩放级别太近了,用户看不到任何5个标记。
有没有办法动态设置缩放级别,以便用户可以看到至少4或5个标记? :-)
我的代码如下:
除此之外,我正在使用Google Maps Api v3 Places插件(基本上是从这个示例中直接使用:https://developers.google.com/maps/documentation/javascript/examples/places-searchbox)
当我搜索特定地址时,我需要确保至少N个标记在地图上可见。现在,我将缩放级别设置为始终为10。然而,当我搜索例如法罗群岛(只有大约5个标记)时,缩放级别太近了,用户看不到任何5个标记。
有没有办法动态设置缩放级别,以便用户可以看到至少4或5个标记? :-)
我的代码如下:
$(document).ready(function () {
var map = null;
var markers = [];
var overlays = [];
var infowindow = new google.maps.InfoWindow();
// Init google map (API v. 3)
var mapOptions = {
center: new google.maps.LatLng(56.161, 10.77),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker, i;
for (i = 0; i < data.length; i++) {
// Create a new marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].Latitude, data[i].Longitude),
map: map,
title: data[i].Name
});
// Add the marker to a global array for filtering
markers.push(marker);
}
// Create the search box and link it to the UI element.
var input = /** @type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** @type {HTMLInputElement} */(input));
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function () {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
if (markers[i].type == "userMarker") {
marker.setMap(null);
}
}
// For each place, get the icon, place name, and location.
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
marker.type = "userMarker";
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(11);
});
// [END region_getplaces]
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function () {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
非常感谢您的提前帮助!