当前位置: 代码迷 >> JavaScript >> 根据标记居中放置Google地图
  详细解决方案

根据标记居中放置Google地图

热度:91   发布时间:2023-06-13 12:13:33.0

我想基于动态加载的标记将Google Map居中。 我已经看到了'bounds'的用法,并尝试实现“适合边界”,但是我无法将其正确地应用于地图。 这是代码:

var MapStart = new google.maps.LatLng(41.664723,-91.534548);

var markers;
var map;
var infowindow = new google.maps.InfoWindow({maxWidth: 650});

function initialize() {
    markers = new Array();
    var mapOptions = {
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: MapStart
    };

    map = new google.maps.Map(document.getElementById("map"), mapOptions);

    $("#map_list ul li").each(function(index) {
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng($(this).children(".marker_long").text(), $(this).children(".marker_lat").text()),
            map: map,
            animation: google.maps.Animation.DROP,
            title : $(this).children(".marker_title").text(),
            brief: $("div.infoWindow", this).html()
        });

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(marker.brief);  
            infowindow.open(map, marker);
        });

        markers.push(marker);
    });
}

这很容易,在您的initialize方法中创建一个bounds对象,然后使用每个标记的位置扩展bounds对象。 最后,在地图对象上调用map.fitBounds()以居中并使地图适合标记:

function initialize() {
    ...
    var bounds = new google.maps.LatLngBounds();
    ...
    $("#map_list ul li").each(function(index) {
        ...
        //extend the bounds to include each marker's position
        bounds.extend(marker.position);
        ...
    });
    ...
    //now fit the map to the newly inclusive bounds
    map.fitBounds(bounds);
    ...
}

//(optional) restore the zoom level after the map is done scaling
var listener = google.maps.event.addListener(map, "idle", function () {
    map.setZoom(15);
    google.maps.event.removeListener(listener);
});
  相关解决方案