我有一个(相当大的)JSON数组对象,每个对象都包含一个纬度和经度值。当我的Google地图加载时,我会遍历这个数组并创建一个新的标记,并将其添加到地图中。Google Maps Api v3,使用场所时的动态缩放级别库
加入的是,我使用谷歌地图API V3的地方(从这个例子相当多的开箱: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);
});
}
非常感谢提前!
一旦地图完成缩放,获取地图界限,如果边界中包含的地图上的标记数小于所需的阈值,则缩小地图边界,直至缩小为止。您应该能够计算给定地图中心和缩放级别的边界,并执行相同操作,而不需要地图完成对中和缩放到第一个位置。 – geocodezip