0
votes

Is there a way to loop through a multipolygon feature using google maps v3 to extract each sub polygon and then use containsLocation() to find out if a location within the sub polygons matches my stored Lat and Long coordinates?

I'm expecting to be able to use a loop like so:

//check if multipolygon
if(e.feature.getGeometry().getType()==='MultiPolygon'){

 //loop over sub polygons
  var polygons = e.feature.getGeometry().getArray();

  polygons.foreach(function(item, index){

    //item is our polygon?

    var coords = item.getAt(index).getArray();
    var poly = new google.maps.Polygon({

      paths: coords,

    });

    //check if the subpolygon contains my latlong

    if(google.maps.geometry.poly.containsLocation(myLatLong, poly)){

     // do something

    }

  });

}

However, it doesn't work as I don't think 'item' is actually a polygon?

Any help would be great on how I can achieve this.

1
developers.google.com/maps/documentation/javascript/3.exp/… should the var polygons be in an array? I think getArray() returns an array. polygons.forEach(); instead of [polygons].forEach();arodjabel
Yes, it is possible. You need to make google.maps.Polygons from the coordinates, then do the check, so the posted code should in principle work. Please provide a minimal reproducible example that demonstrates your issue.geocodezip
it appears that it loops over the polygons fine, but it's the contains location which never equals true...HKG

1 Answers

2
votes

I figured out the issue was around the .getAt(i) and it needed to be .getAt(0)

if (e.feature.getGeometry().getType() === 'MultiPolygon' ) {
          var array = e.feature.getGeometry().getArray();
          array.forEach(function(item,i){

            var coords= item.getAt(0).getArray();
            var poly = new google.maps.Polygon({
              paths: coords
            });
            if (google.maps.geometry.poly.containsLocation(location, poly)) {
              //do something

            }

          });
        }