Google Maps API Tutorial

© 2006, 2007, 2008, 2009 Mike Williams

Translate this page:


Testing if a polygon contains a point

Version 2.88 introduces the polygon and polyline "click" events which make all the following redundant.

They also make it not work, since the the click event passed through the polygon to the map contains the polygon object reference ratgher than the point clicked.

Versions prior to v2.88

I've adapted some code that I found at into a Javascript method that tests whether a point lies inside a polygon or polyline.

The code is implemented as GPolygon.Contains(glatlng) and GPolyline.Contains(glatlng), which return true if the point is inside and false is the point is outside.

Here's an example

[The XML file that it uses is here]

The method works for closed or open polygons and polylines. If the shape is open, it considers there to be an additional virtual line from the last point to the first.

If the point happens to lie exactly on the boundary of the polygon, then it may return either true or false.

The method gets pretty slow if you've got lots of complex polygons. But then again, plotting lots of complex polygons in the first place is pretty slow.

This example draws 50 polygons representing the states of the USA, using data loosely based on the SQL data posted by "Wabler"
there are 50 polygons with 3372 nodes between them occupying 139kb of XML data.

I reckon that that example is acceptable under Firefox on a fast computer, and that the speed under MSIE isn't acceptable. You might think otherwise, depending on what you consider acceptable.

The initial loading time is affected by the size of the XML file and the speed at which the API draws polygons.

The zoom time is affected by the speed at which the API draws polygons.

The click response time is affected by the speed of my GPolygon.Contains() method, which I believe to be proportional to the total number of nodes being scanned. (I deliberately didn't optimise the code by jumping out of the loop when a match is found, so that you can get a true feel for the natural speed of the algorithm.)

It would be possible to make further optimisations to the click response (e.g. by checking states whose centres are close to the click point first and jumping out of the loop when a match is found) but I don't think that there's anything that can be done about the slow zoom redraw when using lots of complex GPolygons.

Back to Mike's Homepage
Up to the start of this tutorial