开发者

Determine the lat lngs of markers within a polygon

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 woul开发者_Go百科d 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?


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.


// 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;
};


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

  • Check if a polygon contains a coordinate in Google Maps


This has been updated in v3. You can do this calculation via the google.maps.geometry.poly namespace API Documentation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜