Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if map markers are within selected bounds

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 found some great info here: How to get markers inside an area selected by mouse drag?

I have implemented the keymapzoom plugin ok. like so

    $('#dispatcher').gmap3({action:'get'}).enableKeyDragZoom({
        boxStyle: {
          border: "dashed black",
          //backgroundColor: "red",
          opacity: 0.5
        },
        paneStyle: {
          backgroundColor: "gray",
          opacity: 0.2
        }
  });
var dz = $('#dispatcher').gmap3({action:'get'}).getDragZoomObject();
google.maps.event.addListener(dz, 'dragend', function (bnds) {
  alert(bnds);
});

This gives me the following ((lat,long),(lat,long)) format from the alert(bnds);

I need to know how i can now check if any markers are within this?

I already have an object that is storing the markers for another reason. like:

    markers[name] = {};
    markers[name].lat = lati;
    markers[name].lng = longi;

which might be useful?

I don't understand how to use the GLatLngBounds and containsLatLng(latlng:GLatLng) as suggested.

like image 524
Vince Lowe Avatar asked Jun 27 '12 15:06

Vince Lowe


2 Answers

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.

like image 66
Peter Kruithof Avatar answered Sep 22 '22 12:09

Peter Kruithof


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");
        }         
     });
like image 30
Vince Lowe Avatar answered Sep 22 '22 12:09

Vince Lowe