我得到了关于如何使折线位于中心的问题的答案,但这就是问题所在。 当我想看 map 的时候。 map 仅在我的 div 的左上角初始化。当我调用这个函数时:
setTimeout(function() {
google.maps.event.trigger(map,'resize');
}, 200);
我可以在整个 div 中看到 map ,但折线未缩放并且位于左上角内。
我该怎么办?
我的代码:
全局定义:
var flightPlanCoordinates=[];
var flightPath;
var map;
var myLatLng = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
后来使用的代码...
$.ajax({
type: 'POST',
url: 'history.php',
data: {
'd_year1':$('#select-choice-year1').val(),
'd_month1': $('#select-choice-month1').val(),
'd_day1':$('#select-choice-day1').val(),
'd_year2':$('#select-choice-year2').val(),
'd_month2': $('#select-choice-month2').val(),
'd_day2':$('#select-choice-day2').val()
},
success: function(data)//callback to be executed when the response has been received
{
if(data=="[]")
{
alert("None");
}else
{
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);
zoomToObject(flightPath);
}
}
});
以及缩放和居中折线的功能:
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);
setTimeout(function() {
google.maps.event.trigger(map,'resize');
}, 200);
}
那么如何真正初始化 map 以适合整个 div 以及如何缩放和居中折线以适合 map ?
最佳答案
将缩放和中心功能更改为:
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);
setTimeout(function() {
google.maps.event.trigger(map,'resize');
map.fitBounds(bounds);
}, 200);
}
或者在调用 map 调整大小事件之前触发它(在 AJAX 回调内)。
关于javascript - 谷歌地图API3,折线不在中心且未缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13032245/