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

问题描述:

我正在使用谷歌地图。根据要求,我需要设置不同的缩放级别,这取决于我的搜索查询。如果在国家地图上有多个位置,那么地图应该将焦点放在国家。其他情况是,如果城市中有不同的位置标记,那么地图应该集中在城市层面。如何动态设置Google地图自定义缩放级别?

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); 
    } 
}); 

我认为这对你的关键部分是

//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); 

我发现下面的文章非常有帮助。使用代码示例代码我能够实现这个enter link description here

我试过在drupal中的代码,它工作。

你执行搜索后,一旦你的位置,你可以使用bounds.extendmap.fitBounds使地图自动放大显示搜索返回的所有引脚,像这样:

//places is an array that contains the search result 
    var bounds = new google.maps.LatLngBounds(); 
    for (var i = 0, place; place = places[i]; i++) { 
     //pass the location of each place to bounds.extend 
     bounds.extend(place.geometry.location); 
    } 
    //tell your map to sets the viewport to contain all the places. 
    map.fitBounds(bounds); 

另如果您使用地理编码器搜索区域如邮政编码,城市或国家,还可以使用map.fitBounds来设置视口以显示地理编码器返回的整个特定区域,如下所示:

//response is the geocoder's response 
map.fitBounds(response[0].geometry.viewport); 

以下是地理编码器示例的代码本https://codepen.io/jaireina/pen/gLjEqY