Demo: How to find if a point is inside a KMLPolygon.

46 views
Skip to first unread message

dinther

unread,
Apr 16, 2009, 1:22:58 AM4/16/09
to KML Developer Support - Google Earth Plug-in
You can create a polygon in code (See API examples) or load one using
a KMZ file.
You can find in another post how to get your hands on the KMLPolygon
object.

I found code that was originally written by Darel Rex Finley (
http://alienryderflex.com/polygon/) then adapted by Mike Williams
( http://econym.googlepages.com/epoly.htm )

I changed it a bit more so it can use native KMLPolygon object where
it deals correctly with outer and inner rings. I only looked at the
point in polygon routine.

The following function will return true if the given latitude and
longitude is inside the polygon. I hope it will be useful to someone.


function locationInPolygon(poly, latitude, longitude){
var locationInBoundary = function(boundary, latitude, longitude){
var j=0;
var inside = false;
var x = longitude;
var y = latitude;
var lat1 = 0;
var lat2 = 0;
var lon1 = 0;
var lon2 = 0;
var coordinates = boundary.getCoordinates();
var pointCount = coordinates.getLength();

for (var i=0; i < pointCount; i++) {
j++;
if (j == pointCount) {j = 0;}
lat1 = coordinates.get(i).getLatitude();
lat2 =coordinates.get(j).getLatitude();
lon1 = coordinates.get(i).getLongitude();
lon2 = coordinates.get(j).getLongitude();
if (((lat1 < y) && (lat2 >= y))
|| ((lat2 < y) && (lat1 >= y))) {
if ( lon1 + (y - lat1)
/ (lat2-lat1)
* (lon2 - lon1)<x ) {
inside = !inside
}
}
}
return inside;
}
var inside = false;
var outer = poly.getOuterBoundary();
inside = locationInBoundary(outer, latitude, longitude);
if (inside){
//check all inner boundaries if any.
var inners = poly.getInnerBoundaries().getChildNodes();
for (var i=0; i < inners.getLength(); i++) {
inside = locationInBoundary(inners.item(i), location);
//inners are like holes in a polygon
if (inside){ inside = !inside; break;}
}
}
return inside;
}
Reply all
Reply to author
Forward
0 new messages