tags:

views:

133

answers:

3

I have a google maps app which plots markers as it loads. One of the new requirment is to to add a Polygon overlay encompassing a selection of markers by the user. I was able to achieve that using the Geometry Controls of the GMaps Utility Library

Now, the next step is to form a group of the selected markers for which I would need to determine if the lat lngs of the markers falls within the lat lngs of the polygon? Is there a way to determine the lat lngs of a polygon and compute if the marker's lat lng is within its boundaries?

+1  A: 

I have never directly messed around with Google Maps, but you can store the points that make up the polygon and then use the Point-In-polygon Algorithm to check if a given longitude and latitude point is within a polygon or not.

npinti
A: 

Following npinti's suggestion, you may want to check out the following point-in-polygon implementation for Google Maps:

Daniel Vassallo
A: 
// Create polygon method for collision detection
GPolygon.prototype.containsLatLng = function(latLng) {
    // Do simple calculation so we don't do more CPU-intensive calcs for obvious misses
    var bounds = this.getBounds();

    if(!bounds.containsLatLng(latLng)) {
        return false;
    }

    // Point in polygon algorithm found at http://msdn.microsoft.com/en-us/library/cc451895.aspx
    var numPoints = this.getVertexCount();
    var inPoly = false;
    var i;
    var j = numPoints-1;

    for(var i=0; i < numPoints; i++) { 
        var vertex1 = this.getVertex(i);
        var vertex2 = this.getVertex(j);

        if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng())  {
            if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) {
                inPoly = !inPoly;
            }
        }

        j = i;
    }

    return inPoly;
};
klay