37

这里有几点:

  1. 我在地图上有一些标记,并且在地图旁边的右侧面板上有与之关联的记录。它们通过数字 id 连接,数字 id 存储为标记的属性。
  2. 所有标记都存储在一个数组中。
  3. 当用户放大地图时,仅与可见标记相关联的记录应显示在右侧面板上。

那么,如何获取当前缩放级别上所有可见标记的列表呢?我在互联网上搜索并没有找到有用的东西。可以在这里找到我想要实现的某种目标

4

6 回答 6

58

在 Google Maps JavaScript API V3 中,我们可以使用如下内容:

let markers
let map
let bounds = map.getBounds()
markers.filter(m => m.isAdded).forEach(m => {
  if (bounds.contains(m.getPosition())) {
    // code for showing your object, associated with current marker
  }
})
于 2011-10-13T22:46:02.073 回答
26

用于GMap2.getBounds()查找边界框。用于GLatLngBounds.containsLatLng()检查每个标记以查看它是否可见。

于 2010-05-25T23:10:54.847 回答
23

我知道你想要 API V2,但我必须更正我在@bruha 对 V3 的回复中看到的一些内容,以防有人来找它:

var markers; // your markers
var map; // your map

for(var i = markers.length, bounds = map.getBounds(); i--;) {
    if( bounds.contains(markers[i].getPosition()) ){
        // code for showing your object
    }
}

以这种方式向后遍历数组会更快地遍历标记数组,而且我们在进入循环之前将边界设置为变量,因此我们不会在每次通过循环时都请求它,唯一的请求是我们必须make 是特定标记是否位于边界内。

编辑:搞砸了我的减量器

编辑: map.getBounds() 应该是 map.getBounds

于 2012-02-01T00:29:34.393 回答
3

如果有人仍然需要这个问题的答案,我在 Codepen.io 上有一个完整的工作模型

随意下载它并根据您的需要进行调整。只需将 API 密钥更改为您自己的即可。(他们是免费的)

https://codepen.io/pailwriter/pen/bGEpeRv

这是在视口中获取标记的函数。

function showVisibleMarkers() {
    var bounds = map.getBounds(),
        count = 0;
                                   
    for (var i = 0; i < markers.length; i++) {
        var marker = markers[i],
            infoPanel = $('.info-' + (i+1) ); // array indexes start at zero, but not our class names :)
                                           
        if(bounds.contains(marker.getPosition())===true) {
            infoPanel.show();
            count++;
        }
        else {
            infoPanel.hide();
        }
    }
    
    $('#infos h2 span').html(count);
}
于 2020-07-31T19:19:58.127 回答
2

这是简单的代码。试试这个代码。

private boolean CheckVisibility(Marker marker)
{
    if(googleMap != null)
    {
        //This is the current user-viewable region of the map
        LatLngBounds latLongBounds = googleMap.getProjection().getVisibleRegion().latLngBounds;

            if(latLongBounds.contains(marker.getPosition()))
                   //If the item is within the the bounds of the screen
                  return true;
            else
                  //If the marker is off screen
                  return false;
    }
    return false;
}
于 2016-08-29T10:18:42.277 回答
0

我的代码片段

private boolean isAnyMarkerVisible(LatLng ll) {
    if(gMap != null && markersData != null) {
        final LatLngBounds latLongBounds = LatLngBounds.builder().include(ll).build();
        for (Store store : markersData) {
            if (latLongBounds.contains(store.getLatLng())) {
                return true;
            }
        }
    }
    return false;
}
于 2017-02-16T14:04:50.257 回答