如何动态设置谷歌地图自定义缩放级别?

Ran*_*iaz 3 google-maps

我正在使用谷歌地图.根据要求,我需要设置不同的缩放级别,这取决于我的搜索查询.如果国家/地区的地图上有多个位置,那么地图应该关注国家/地区.其他情况是,如果城市中标记了不同的位置,那么地图应该集中在城市级别.

dou*_*uwe 5

var geoCoder = new GClientGeocoder();
geoCoder.setViewport(map.getBounds());
geoCoder.getLocations('searchquery', function(latlng) {
  if( latlng.Placemark.length > 0 ) {
    var box = latlng.Placemark[0].ExtendedData.LatLonBox;
    var bounds = new GLatLngBounds(new GLatLng(box.south, box.west), new GLatLng(box.north, box.east));
    var center = new GLatLng(box.Placemark[0].Point.coordinates[1], latlng.Placemark[0].Point.coordinates[0]);
    var zoom = oMap.getBoundsZoomLevel(bounds);
    map.setCenter(center, zoom);
  }
});
Run Code Online (Sandbox Code Playgroud)

我认为这对你来说至关重要

//box is a LatLonBox with the size of your resultquery. You can create this yourself as well
var box = latlng.Placemark[0].ExtendedData.LatLonBox;

//bounds are the bounds of the box
var bounds = new GLatLngBounds(new GLatLng(box.south, box.west), new GLatLng(box.north, box.east));

//center is the center of the box, you want this as the center of your screen
var center = new GLatLng(box.Placemark[0].Point.coordinates[1], latlng.Placemark[0].Point.coordinates[0]);

//zoom is the zoomlevel you need for all this
var zoom = oMap.getBoundsZoomLevel(bounds);

//the actual action
map.setCenter(center, zoom);
Run Code Online (Sandbox Code Playgroud)