7

我正在为我的位置服务应用程序使用谷歌地图和谷歌地理编码服务。我使用 Google 地理编码服务将地址转换为 lat/lng 位置。我的问题是如何像 maps.google.com 那样自动为某个地址找到合适的缩放比例。

例如,当我在 maps.google.com(例如Cisitu Baru, Bandung)中搜索街道时,它会以较小的缩放比例显示街道。当我搜索一个区域(例如Bandung)时,它会显示更大的缩放。以及更大的省缩放比例(例如Jawa Barat/ West Java),等等。

我都试过了

var geocoder = new google.maps.Geocoder();
geocoder.geocode( {
    'address': someAddress
}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        console.dir(results);
        //cut
        map.panToBounds(results[0].geometry.bounds); //setting bound
        //cut
    }
});

//cut
map.panToBounds(results[0].geometry.viewports); //setting bound
//cut

(老实说,我仍然不知道 code.google.com/apis/maps/documentation/javascript/geocoding.html 之间有什么区别bounds以及viewport它们的用途是什么)

但两者仍然没有以适当的缩放比例显示地图。

现在,我使用这样的小技巧

var tabZoom =  {
    street_address: 15,
    route: 15,
    sublocality: 14,
    locality: 13,
    country: 10
};
//cut
map.setCenter(results[0].geometry.location);
if (tabZoom[results[0].types[0]] != undefined){
    map.setZoom(tabZoom[results[0].types[0]]);
} else {
    map.zetZoom(10);
}
//cut

还有其他解决方案吗?(或者我还不知道的来自 Google Map API 的任何东西?)

谢谢!

4

2 回答 2

4

使用 GLatLngBounds 类

一个例子:

// map: an instance of GMap2

// latlng: an array of instances of GLatLng

var latlngbounds = new GLatLngBounds( );

for ( var i = 0; i < latlng.length; i++ )
{
    latlngbounds.extend( latlng[ i ] );
}

map.setCenter( latlngbounds.getCenter( ), map.getBoundsZoomLevel( latlngbounds ) );

^

诀窍是将需要在地图上同时可见的所有点的列表添加到 GLatLngBounds 对象中。Google Maps API 可以完成其余的数学运算。

或者在 v3 中您可以使用 LatLngBounds 类(类似于 v2 中的 GLatLngBounds),链接:http ://code.google.com/apis/maps/documentation/javascript/reference.html#LatLngBounds

举个例子,看看这个:http ://unicornless.com/code/google-maps-v3-auto-zoom-and-auto-center

于 2012-01-09T08:40:41.540 回答
3

使用结果几何体的视口。如果您的搜索结果没有特定的界限,您将收到 geometry.bounds 错误

视口为您提供结果的最佳视图。

map.fitBounds(results[0].geometry.viewport);

于 2013-03-10T17:49:53.223 回答