设置地图缩放以覆盖所有标记;确保中心位于特定标记

时间:2016-01-20 09:15:10

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

我们可以缩放地图并将其居中以通过此代码显示所有标记:

var markers = //some array (all of them should be visible);
var Themarker = //a marker that should be the center
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
 bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);

但如何确保:

  1. 所有标记都可见(上面代码执行此操作)
  2. 地图的中心是 Themarker (上面代码不这样做)
  3. 地图可以通过map.panTo(Themarker.getPosition());以Themarker为中心,但最后使用它可以将标记滑出视图。

1 个答案:

答案 0 :(得分:1)

您可以考虑使用以下解决方案调整视口,以便在地图中心更改后显示所有标记:

&#13;
&#13;
function initialize() {

    var center = new google.maps.LatLng(-31.953159, 115.849915); //Perth

    var options = {
        center,
        zoom: 20,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map-div"), options);


    var locations = [
           { id: 1, name: "Brisbane", coords: [-33.867396, 151.206854]},
            { id: 2, name: "Sydney", coords: [-27.46758, 153.027892] },
            { id: 3, name: "Perth", coords: [-31.953159, 115.849915] },
            { id: 4, name: 'Canberra', coords: [-35.279014, 149.124449] }
    ];

    var markers = [];
    var bounds = new google.maps.LatLngBounds();
    locations.forEach(function (loc) {
        var pos = new google.maps.LatLng(loc.coords[0], loc.coords[1]);
        var marker = createMarker(map, pos);
        markers.push(marker);
        bounds.extend(pos);
    });
    map.fitBounds(bounds);
 
    map.panTo(center);  //change map center

    google.maps.event.addListenerOnce(map, 'idle', function () {
        resizeMapView(map, markers); //adjust viewport
    });


   
}



function resizeMapView(map, markers) {
    var mapBounds = map.getBounds(); // get bounds of the map object's viewport
   
    var result = markers.filter(function(marker) {  //determine wether map contains all the markers
        if (!mapBounds.contains(marker.getPosition())) {
            return true;
        }
    });
    if (result.length > 0) {
        var zoom = map.getZoom();
        map.setZoom(zoom - 1);
        resizeMapView(map, markers);
    }
}


function createMarker(map,position) {
    return new google.maps.Marker({
        position: position,
        map: map
    });
}


google.maps.event.addDomListener(window, 'load', initialize);
&#13;
html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

#map-div {
    height: 100%;
}
&#13;
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map-div"></div>
&#13;
&#13;
&#13;

JSFiddle