Determine the lat lngs of markers within a polygon

后端 未结 4 1118
-上瘾入骨i
-上瘾入骨i 2021-01-21 23:40

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

相关标签:
4条回答
  • 2021-01-22 00:16

    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
    0 讨论(0)
  • 2021-01-22 00:16

    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.

    0 讨论(0)
  • 2021-01-22 00:19
    // 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;
    };
    
    0 讨论(0)
  • 2021-01-22 00:22

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

    0 讨论(0)
提交回复
热议问题