2010-03-11 135 views
3

我正在使用谷歌地圖。根據要求,我需要設置不同的縮放級別,這取決於我的搜索查詢。如果在國家地圖上有多個位置,那麼地圖應該將焦點放在國家。其他情況是,如果城市中有不同的位置標記,那麼地圖應該集中在城市層面。如何動態設置Google地圖自定義縮放級別?

回答

4
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); 
0

我發現下面的文章非常有幫助。使用代碼示例代碼我能夠實現這個enter link description here

我試過在drupal中的代碼,它工作。

0

你執行搜索後,一旦你的位置,你可以使用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

相關問題