Determine the lat lngs of markers within a polygon

后端 未结 4 1124
-上瘾入骨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: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;
    };
    

提交回复
热议问题