check if map markers are within selected bounds

后端 未结 2 1200
青春惊慌失措
青春惊慌失措 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.

    0 讨论(0)
  • 2020-12-09 00:55

    Box/Rectangle Draw Selection in Google Maps

    This was my solution..

         google.maps.event.addListener(dz, 'dragend', function(e) { //important listener          
          for(var i = 0; i < markers.length; i++){ // looping through my Markers Collection       
            if(e.contains(markers[i].position))
                console.log("Marker"+ i +" - matched");
            }         
         });
    
    0 讨论(0)
提交回复
热议问题