user3009319
user3009319

Reputation: 77

Check if a point is inside a Polygon with the Google Maps API

I am developing an application using the Google Maps API v3, and I'm struggling to know how to find out if an X coordinate is inside a polygon.

Upvotes: 3

Views: 15705

Answers (2)

Eric Yuan
Eric Yuan

Reputation: 1492

In iOS it can be done by using GMSGeometryContainsLocation

Just create a GMSMutablePath, then fill with vertexes of your polygon and test the point.

Example(Swift 4.0):

func isWithin(_ point: CLLocationCoordinate2D) -> Bool {
    let p = GMSMutablePath()
    p.add(CLLocationCoordinate2D(latitude:30.02356126, longitude: -90.07047824))
    p.add(CLLocationCoordinate2D(latitude:30.02501037, longitude: -90.0614231))
    p.add(CLLocationCoordinate2D(latitude:30.03321034, longitude: -90.0617981))
    p.add(CLLocationCoordinate2D(latitude:30.03192855, longitude: -90.07342815))
    return GMSGeometryContainsLocation(point, p, true)
}

Note: If the last param of GMSGeometryContainsLocation is set to true, the GMSMutablePath is composed of great circle segments, otherwise it's of rhumb (loxodromic) segments.

Upvotes: 4

Taylan Aydinli
Taylan Aydinli

Reputation: 4363

You can use the Geometry Library of the Google Maps JS API. There's a function called containsLocation which tells you if a given LatLng is inside a Polygon. Note that it's a Polygon, not a Polyline. A Polyline is (as it says in the name) a line. So there is no such thing as a point being inside a polyline. You can check if a point is inside a Polygon with the containsLocation function.

google.maps.geometry.poly.containsLocation(somePoint, somePolygon)

Upvotes: 11

Related Questions