Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps v3: check if point exists in polygon

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

like image 362
Bob-ob Avatar asked Jun 29 '11 14:06

Bob-ob


People also ask

How do you check if a given point lies inside or outside a polygon JavaScript?

Pick a point outside the polygon check and see if a line from that point to your point intersects an odd number of lines that define the perimeter of the polygon. poly[i]. y should be poly[i][1] at the end of line 3. Also that function checks if the point is inside the polygon not if the point belongs to the polygon.

How do I extract a polygon from Google Maps?

Assuming you have a Google account, creating a map is explained here and by using draw a line tool, you can create polygons. Even though it says line, the sub menu says Add line or shape and closing your line will create a polygon. Once you finish your map, in the map options, you will find Export to KML.


1 Answers

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.

like image 155
mhyfritz Avatar answered Sep 29 '22 22:09

mhyfritz