CyberJunkie
CyberJunkie

Reputation: 22674

Google Maps API check if marker exists in multiple bounds

I'm trying to check if markers already exist in my boundaries before adding them to the map. I found that the best way to this is by using

map.getBounds().contains(marker.getPosition()) which returns true if the marker exists on the map and false if it doesn't. So on false, I add the marker to the map.

This works fine however I have multiple boundaries and map.getBounds()seems to get 1 boundary.

The code below sets markers in each boundary in a loop but checks if markers exists in just 1 boundary. How can I check if markers exist in all my boundaries?

I'm checking markers in the last function.

function findPlaces() {      

    var boundsArray = new Array(); //my array of multiple boundaries  

    for (var i = 0; i < boundsArray.length; i++) {
      var boundary = boundsArray[i];                  

      // Perform search over this boundary
      var request = {
        bounds: boundary,
        keyword: document.getElementById("keyword").value
      };

      service.nearbySearch(request, callback); 
    }
  });
}


//Returns places and create markers
function callback(results, status) { 
    if (status == google.maps.places.PlacesServiceStatus.OK) {
       for (var i = 0; i < results.length; i++) {
       createMarker(results[i]);    
    }     
}   

//create markers
function createMarker(place) {                          
    var marker = new google.maps.Marker({
       position: place.geometry.location
    });

    var onMap = map.getBounds().contains(marker.getPosition());

    //if marker is not on the map, add it               
    if (onMap === false) {          
        marker.setMap(map);
    }
}

Upvotes: 2

Views: 3164

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117314

You may create 1 polygon of all these LatLngBounds.

Polygons support multiple Paths, so all you have to to is create an array which contains for every LatLngBounds an array with the LatLngs defined by the 4 vertices of the LatLngBounds and apply this array to the paths-property of the Polygon.

This Polygon now may used with google.maps.geometry.poly.containsLocation to determine if a location is located within any of the LatLngBounds.

Upvotes: 1

Related Questions