5

I know how to do this using Apple MapKit following this link, but don't have any idea about how to check if location or annotation (GMSMarker) is inside the GMSPolygon in Google Map SDK.

Nitesh Borad
  • 4,583
  • 36
  • 51
  • I found how to do that in Google Maps in JavaScript... from this link, http://stackoverflow.com/questions/20074747/check-if-a-point-is-inside-a-polygon-with-the-google-maps-api But did not find any solution for iOS – Nitesh Borad Jul 18 '14 at 14:01
  • See http://stackoverflow.com/questions/19587792/how-to-detect-that-a-point-is-inside-a-polygon-using-google-maps-sdk-for-ios. Use GMSGeometryContainsLocation. Even without that built-in Google method, you can use the CGPathContainsPoint approach shown [here](http://stackoverflow.com/questions/19014926/detecting-a-point-in-a-mkpolygon-broke-with-ios7-cgpathcontainspoint) to build your own CGPathRef using the coordinates of the polygon. –  Jul 18 '14 at 14:02

2 Answers2

16

I got the answer.

There is an inline function defined in GMSGeometryUtils.h file in Google SDK:

//Returns whether |point|,CLLocationCoordinate2D lies inside of path, GMSPath
    BOOL GMSGeometryContainsLocation(CLLocationCoordinate2D point, GMSPath *path,
                                 BOOL geodesic);

It contains a function called GMSGeometryContainsLocation, which determines whether location point lies inside of polygon path.

if (GMSGeometryContainsLocation(locationPoint, polygonPath, YES)) {
    NSLog(@"locationPoint is in polygonPath.");
} else {
    NSLog(@"locationPoint is NOT in polygonPath.");
}

Source: GMSGeometryContainsLocation

Nitesh Borad
  • 4,583
  • 36
  • 51
4

For Swift 4 you can use this extension:

extension GMSPolygon {

    func contains(coordinate: CLLocationCoordinate2D) -> Bool {

        if self.path != nil {
            if GMSGeometryContainsLocation(coordinate, self.path!, true) {
                return true
            }
            else {
                return false
            }
        }
        else {
            return false
        }
    }
}

You can call it directly from your polygon object like this:

if gms_polygon.contains(coordinate: point) {
    //do stuff here
}
Mario Jaramillo
  • 567
  • 6
  • 9