【问题标题】:Google maps draggable marker zoom to fit all markers谷歌地图可拖动标记缩放以适合所有标记
【发布时间】:2012-12-13 22:14:16
【问题描述】:

我有一个带有可拖动标记的工作版地图。放大以包括所有标记作品

bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);

results[0].geometry.location 是新的可拖动位置。

如果新位置正在形成更大的区域,则此方法有效。但是,当我将标记拖到离其余标记更近的位置时,我认为这 不会扩展 边界,因此不会放大。

有什么想法吗?

【问题讨论】:

  • 使用边界中已包含的标记扩展边界不会更改边界。它应该缩放以显示所有标记。如果您希望它放大新添加的标记,则需要执行其他操作。如果这不是问题,您需要在问题中包含更多上下文。

标签: google-maps google-maps-api-3 zooming fitbounds


【解决方案1】:

当您放置标记时,将标记位置添加到包含原始边界的临时 LatLngBounds 对象,并将地图边界与每次拖放时的边界相匹配。

var mapOptions = {
  center: new google.maps.LatLng(38.68551, -96.341308),
  zoom: 8,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
    mapOptions);

var bounds = new google.maps.LatLngBounds(),
    markers = [];

markers.push(new google.maps.Marker({position: new google.maps.LatLng(38.69, -96.14),map: map}));
markers.push(new google.maps.Marker({position: new google.maps.LatLng(38.65, -96.44),map: map}));
markers.push(new google.maps.Marker({position: new google.maps.LatLng(38.56, -96.56),map: map}));
markers.push(new google.maps.Marker({position: new google.maps.LatLng(38.42, -96.98),map: map}));
markers.push(new google.maps.Marker({position: new google.maps.LatLng(38.31, -96.45),map: map}));

for (var m in markers) {
    bounds.extend(markers[m].getPosition());
}

map.fitBounds(bounds);

var dropMarker = function(latlng) {
    var marker = new google.maps.Marker({position: latlng, map: map}),
        tempBounds = new google.maps.LatLngBounds();

     // notice we use the union method here to add the original bounds object
    tempBounds.union(bounds).extend(marker.getPosition());
    map.fitBounds(tempBounds);
}

// imitate dropping marker far away from others
setTimeout(function() {
    dropMarker(new google.maps.LatLng(31, -96));
}, 2000);

// imitate dropping marker close to others
setTimeout(function() {
    dropMarker(new google.maps.LatLng(38.5, -96.5));
}, 5000);

您可以尝试使用地图 panToBounds 方法来获得良好的平滑过渡,而不仅仅是拟合临时边界。

【讨论】:

  • 这基本上是每次拖动结束事件重新做绑定。我会想象有一个更聪明的方法来解决这个问题。
  • 您不会重新计算每一滴的界限。您计算一次初始边界,只需将标记位置添加到每个标记放置的初始边界。这适用于缩小和缩小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
  • 1970-01-01
  • 2011-08-07
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多