根据标记建立Google地图 [英] Center a Google Map based on Markers

查看:81
本文介绍了根据标记建立Google地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据动态加载的标记来集中我的Google地图。我已经看到了边界的使用,并试图实现适合边界,但我没有能够正确地应用到我的地图。这里是代码:

I would like to center my Google Map based on dynamically loaded markers. I have seen the use of 'bounds' and tried to implement Fit to bounds, but I haven't been able to apply it correctly to my map. Here is the code:

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方法创建一个边界对象,然后用每个标记的位置扩展边界对象。最后,在地图对象上调用map.fitBounds()以居中并将您的地图放入您的标记中:

This is easy, in your initialize method create a bounds object, and then extend the bounds object with each marker's position. Finally, call map.fitBounds() on your map object to center and fit your map to your markers:

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);
});

这篇关于根据标记建立Google地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆