Bing Maps: Polygon Search - Is Point Within Polygon?
Today, I found an article on MSDN that covers how to perform a polygon search to determine if a given Lat/Long point is within a given Polygon.
I copied the logic for searching within the Polygon and made it more reusable than what is posted in the MSDN article, so I thought I’d post it here.
if (GeoHelper == undefined) var GeoHelper = {}; GeoHelper.IsInPolygon=function(points,latlong) { // This code adapted from the following URL: // http://msdn.microsoft.com/en-us/library/cc451895.aspx var i; var j=points.length-1; var inPoly=false; var lat = latlong.Latitude; var lon = latlong.Longitude; for (i=0; i<points.length; i++) { if (points[i].Longitude<lon && points[j].Longitude>=lon || points[j].Longitude<lon && points[i].Longitude>=lon) { if (points[i].Latitude+(lon-points[i].Longitude)/(points[j].Longitude-points[i].Longitude)*(points[j].Latitude-points[i].Latitude)<lat) { inPoly=!inPoly; } } j=i; } return inPoly; };
The usage of the IsInPolygon method is fairly simple, the first parameter is an array of VELatLong point objects that make up the Polygon, and the second is the VELatLong point object you want to test to see if it is located within the Polygon. Then the method simply returns True if it’s within the Polygon, and False if it’s not.
Also, this code would be very easily converted to C# or VB.NET if you need to perform the search within your server-side code.
Here’s a full code sample demonstrating this. This sample allows you to click on the map, and when you click it checks to see if the point you clicked is within the polygon, and it displays an alert box telling you if it is or not.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
You can find the original MSDN article here: http://msdn.microsoft.com/en-us/library/cc451895.aspx