【问题标题】:Automatically Finding Appropriate Zoom for Geocoding Result为地理编码结果自动寻找合适的缩放比例
【发布时间】:2012-02-05 19:28:31
【问题描述】:

我正在为我的位置服务应用程序使用 Google 地图和 Google 地理编码服务。我使用 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

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

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

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

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 的任何东西?)

谢谢!

【问题讨论】:

    标签: google-maps-api-3 google-geocoder


    【解决方案1】:

    使用 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

    【讨论】:

    • 我不熟悉 v2 API。你能用 API v3 来描述它吗?谢谢。
    • 在 v3 中你可以使用 LatLngBounds 类 code.google.com/apis/maps/documentation/javascript/…
    • 很好,我刚刚从您的示例 URL 中发现了 fitBounds 方法。我只是制作map.fitBounds(results[0].geometry.bounds);,它就像一个魅力。谢谢!
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-06-08
      • 2023-03-26
      • 2016-09-26
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多