check if map markers are within selected bounds

后端 未结 2 1199
青春惊慌失措
青春惊慌失措 2020-12-09 00:13

I have a map with various markers and i need to be able to draw a rectangle on the map and select the markers which are within the rectangle bounds.

So far i have fo

2条回答
  •  时光说笑
    2020-12-09 00:43

    Your question is tagged with the v3 version of the Maps API, so I'll assume you are using that version (which you should as v2 is deprecated). Note that some classes and methods are named different than in your question.

    Bounds are represented with the LatLngBounds class. You can perform the contains method on an instance of that class to determine if a point lies within those bounds.

    If you have an object with all your markers, you can loop through them and check each marker, for example:

    var bounds = new google.maps.LatLngBounds(sw, ne);
    for (var a in markers) {
        if (bounds.contains(new google.maps.LatLng(markers[a].lat, markers[a].lng)) {
            // marker is within bounds
        }
    }
    

    On a side note, I would store the LatLng object in the markers object when creating them. That way you don't have to create them wherever you need.

提交回复
热议问题