A polygon search has a more complex algorithm. The basic algorithm consists of using a line that goes through a data point. Once this line is calculated, the number of points of intersection with the polygon sides is counted on both the left and right side. If there is an odd number of intersecting points on the right side and odd number of intersecting points on the left side then the data point is inside the polygon.
.png)
Figure 4. Data point inside polygon
If there is an even number of points of intersection on either side of the data point then data point is outside of the polygon.
.png)
Figure 5. Data point outside of polygon
Note that it really doesn’t matter where you draw the line as any line will eventually intersect the polygon.
The polygonSearch function will iterate each shape in the data layer and pass it to a second function called to pointInPolygon to determine if the given data point is within the polygon. If it is, then the data point will be displayed.
function polygonSearch()
{
//hide previous results
hideEachShape();
//clear the search shape layer
searchShapeLayer.DeleteAllShapes();
//polygon coordinates
var points = new Array(new VELatLong(43.64486433588385, -79.3791389465332),
new VELatLong(43.64508171979899, -79.3930435180664),
new VELatLong(43.63682057801007, -79.38437461853027),
new VELatLong(43.63946054004705, -79.36819553375244),
new VELatLong(43.652720712083266, -79.37201499938965),
new VELatLong(43.65793702655821, -79.39111232757568),
new VELatLong(43.64927396999741, -79.37222957611084),
new VELatLong(43.64486433588385, -79.3791389465332));
for(var i=0; i < dataLayer.GetShapeCount(); i++)
{
var shape = dataLayer.GetShapeByIndex(i);
var latlong = shape.GetPoints()[0];
var lat = latlong.Latitude;
var lon = latlong.Longitude;
if(pointInPolygon(points,lat,lon))
{
shape.Show();
}
}
drawPolygon(points);
}The next function determines whether the point is actually inside the polygon.
function pointInPolygon(points,lat,lon)
{
var i;
var j=points.length-1;
var inPoly=false;
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;
}As with the bounding box and radius searches, you will also draw a polygon to represent the search area. To draw the polygon using the polylines is just a matter of passing in the array of points that make up the polygon to the VEShape Constructor.
function drawPolygon(points)
{
var polygon = new VEShape(VEShapeType.Polyline, points);
polygon.HideIcon();
searchShapeLayer.AddShape(polygon);
map.SetMapView(points);
}Calling the Polygon Search function will result in the following map.
.png)
Figure 6. Polygon search