【问题标题】:fitBounds does not center correctlyfitBounds 未正确居中
【发布时间】:2014-04-08 22:34:00
【问题描述】:

当我初始化地图时,我会在地图上添加 1 个标记。当我缩小地图时,我可以在地图“副本”上多次看到添加的标记。

当我在地图上搜索位置时,它会添加一个新标记。 之后,我使用 fitBounds 来适应地图上的两个标记。

通常这会导致以下结果:

有时它会这样做:

我感觉 fitBounds 方法有时会使用'另一个世界'上的标记。 两个标记的纬度和经度都是正确的,正如您所见,现在左侧有 2 个标记。

有人可以向我解释为什么会发生这种情况以及如何避免/解决它吗?

这是我计算边界的搜索提交函数的一部分:

var searchResultLocation = mapSearchPlaces[0].geometry.location;

//Create search marker
marker = new google.maps.Marker({
    position: searchResultLocation,
    animation: google.maps.Animation.BOUNCE,
    map: map
});
searchMarkers.push(marker);

//Find map bounds
var closestMarker = null;
var closest = Number.MAX_VALUE;
for (var i=0; i < markerLocations.length; i++) {
    var distance = google.maps.geometry.spherical.computeDistanceBetween(searchResultLocation, markerLocations[i]);
    if (distance < closest) {
        closest = distance;
        closestMarker = markerLocations[i];
    }
}
var bounds = new google.maps.LatLngBounds(searchResultLocation, closestMarker);
map.fitBounds(bounds);

【问题讨论】:

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


    【解决方案1】:

    google.maps.LatLngBounds 构造函数采用两个非常具体的参数,按特定顺序:

      LatLngBounds(sw?:LatLng, ne?:LatLng) | Constructs a rectangle from the points at its south-west and north-east corners.
    

    您应该创建一个空的 LatLngBounds 对象并用两个点扩展它:

    var bounds = new google.maps.LatLngBounds();
    bounds.extend(searchResultLocation);
    bounds.extend(closestMarker);
    map.fitBounds(bounds);
    

    【讨论】:

    • 先生,您是英雄。我见过extend 方法,但不认为它会有所作为......
    猜你喜欢
    • 2013-10-22
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 2019-05-18
    • 2020-10-31
    • 2016-05-25
    相关资源
    最近更新 更多