Google Maps API check if marker exists in multiple bounds

浪尽此生 提交于 2019-12-10 23:48:39

问题


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);
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/17253929/google-maps-api-check-if-marker-exists-in-multiple-bounds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!