谷歌地图:API 3,如何将折线设置在中心位置

15

大家好,我需要将折线置于地图中心。

以下是核心代码...

success: function(data) {//callback to be executed when the response has been received

    data = JSON.parse(data);
    for (var i=0;i<data.length;i++) {
        flightPlanCoordinates[i] = new google.maps.LatLng(data[i].x,data[i].y);
    }
    map = new google.maps.Map(document.getElementById("map_find"),
    mapOptions);
    flightPath = new google.maps.Polyline({
            path: flightPlanCoordinates,
            strokeColor: "#8a2be2",
            strokeOpacity: 1.0,
            strokeWeight: 3
    });

    flightPath.setMap(map);
    map.setZoom(5);
    map.setCenter(flightPlanCoordinates);
}

这不是我所需要的...我的地图没有居中并且没有缩放,如何实现?

1个回答

38
你可以使用这个函数,将折线作为参数调用它:
function zoomToObject(obj){
    var bounds = new google.maps.LatLngBounds();
    var points = obj.getPath().getArray();
    for (var n = 0; n < points.length ; n++){
        bounds.extend(points[n]);
    }
    map.fitBounds(bounds);
}

调用它:

flightPath.setMap(map);
zoomToObject(flightPath);

请确保你的地图对象是一个全局变量。


我需要在这行代码 flightPath.setMap(map); 之前调用它吗? - user123_456
我认为你的代码是有效的,但是我的地图没有在整个div中初始化...当我调用这个函数时,它只出现在整个div的1/6中。有什么想法吗? - user123_456
最好您发布一个包含完整代码的新问题。您的地图<div>有尺寸吗?(宽度和高度都有吗?) - Marcelo
我发布了一个新问题,请查看:http://stackoverflow.com/questions/13032245/google-polyline-is-not-in-the-center-and-not-zoomed - user123_456

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接