Google Maps v3: check if point exists in polygon

Bob-ob picture Bob-ob · Jun 29, 2011 · Viewed 65k times · Source

I am looking to find a way of checking if a point exists inside a polygon in Google Maps v3 (JavaScript). I've searched everywhere and the only solutions I have found so far have been to do with getting the bounds of the polygon, but the code shown seems to just create a rectangle and keeps expanding its surface area to include all relevant points.

By the way, the reason I can't just use a big square i.e. getting a polygons bounds, is that I have bordering polygons on the map and they can not expand into each other's territory.

EDIT Following on from the reply below, I have tried implementing the example code using one of my existing polygons but it is just saying that it is not defined and I can't figure out why.

Here is my declaration:

myCoordinates = [
    new google.maps.LatLng(0.457301,-0.597382),
    new google.maps.LatLng(0.475153,-0.569916),
    new google.maps.LatLng(0.494379,-0.563049),
    new google.maps.LatLng(0.506738,-0.553436),
    new google.maps.LatLng(0.520470,-0.541077),
    new google.maps.LatLng(0.531456,-0.536957),
    new google.maps.LatLng(0.556174,-0.552063),
    new google.maps.LatLng(0.536949,-0.596008),
    new google.maps.LatLng(0.503991,-0.612488),
    new google.maps.LatLng(0.473780,-0.612488) ];

polyOptions = { 
    path: myCoordinates,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#0000FF",
    fillOpacity: 0.6 };

var rightShoulderFront = new google.maps.Polygon(polyOptions);
rightShoulderFront.setMap(map);

and here is where I am checking for the point:

var coordinate = selectedmarker.getPosition();
var isWithinPolygon = rightShoulderFront.containsLatLng(coordinate);
console.log(isWithinPolygon);

But it keeps coming up with the error: Uncaught ReferenceError: rightShoulderFront is not defined

Answer

mhyfritz picture mhyfritz · Jun 29, 2011

One algorithm to solve this is ray-casting. See an explanation here.

And you can find code implementing this for the Google Maps JS API V3 here.

HTH.