如何在谷歌地图V3上居中和缩放多个标记

How to center and zoom multiple markers on Google Maps V3

本文关键字:缩放 谷歌地图 V3      更新时间:2024-05-07

我使用以下代码:

 var geocoder;
    var map;
    var markers = [];
    function initialize() {
        geocoder = new google.maps.Geocoder();
        // var latlng = new google.maps.LatLng(51.733833,0.351563);
        var latlng = new google.maps.LatLng(53.590875,-2.279663);
        // var latlng = new Array (new google.maps.LatLng (52.537,-2.061), new google.maps.LatLng (52.564,-2.017));
        var myOptions = {
            zoom: 7,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        addPostCode('EX4 5SP');
        addPostCode('EX16 6LH');
        addPostCode('M1 2AP');
}

我在下面的代码中找到了一些如何实现这一点的示例:Google MAP API v3:Center&缩放显示的标记以实现此目的,使用以下代码。

// map: an instance of GMap3
// latlng: an array of instances of GLatLng
var latlngbounds = new google.maps.LatLngBounds();
latlng.each(function(n){
   latlngbounds.extend(n);
});
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds); 

问题是我需要使用邮政编码来显示地图上的位置。是否可以从邮政编码创建GLatLng的实例数组,然后使用上面的代码缩放地图上的多个标记并将其居中?

GClientGeocoder可以获取邮政编码并返回GLatLng:请参阅https://groups.google.com/forum/#!主题/谷歌地图api/JN8OW5Yaws。

关于多个标记的居中,请参阅在谷歌地图中查找多个位置的中心

是的,这是V2——GLatLng抛出了我。V3中也存在相同的功能:https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

//locationsColl包含坐标列表

var latlng = [];
_.forEach(locationsColl, function (address) {
    latlng.push(address);
});
var latlngbounds = new google.maps.LatLngBounds();
_.forEach(latlng,function (n) {
    latlngbounds.extend(n);
});
// center map to central point between markers
map.setCenter(latlngbounds.getCenter());
// set zoom to fit all coord
map.fitBounds(latlngbounds);