Finding the center of Leaflet polygon?

后端 未结 4 549
逝去的感伤
逝去的感伤 2020-12-24 13:00

I have a bunch of leaflet polygons on a map I created. Each polygon represents something different. A specific set of information is displayed in a popup depending on the pa

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 13:46

    There are a few ways to approximate the centroid of a polygon.

    The easiest (but least accurate method) is to get the center of the bounding box that contains the polygon, as yarl suggested, using polygon.getBounds().getCenter();

    I originally answered the question with the formula for finding the centroid of the points, which can be found by averaging the coordinates of its vertices.

    var getCentroid = function (arr) { 
        return arr.reduce(function (x,y) {
            return [x[0] + y[0]/arr.length, x[1] + y[1]/arr.length] 
        }, [0,0]) 
    }
    
    centerL20 = getCentroid(L20);
    

    While the centroid of the points is a close enough approximation to trick me, a commenter pointed out that it is not the centroid of the polygon.

    An implementation based on the formula for a centroid of a non-self-intersecting closed polygon gives the correct result:

    var getCentroid2 = function (arr) {
        var twoTimesSignedArea = 0;
        var cxTimes6SignedArea = 0;
        var cyTimes6SignedArea = 0;
    
        var length = arr.length
    
        var x = function (i) { return arr[i % length][0] };
        var y = function (i) { return arr[i % length][1] };
    
        for ( var i = 0; i < arr.length; i++) {
            var twoSA = x(i)*y(i+1) - x(i+1)*y(i);
            twoTimesSignedArea += twoSA;
            cxTimes6SignedArea += (x(i) + x(i+1)) * twoSA;
            cyTimes6SignedArea += (y(i) + y(i+1)) * twoSA;
        }
        var sixSignedArea = 3 * twoTimesSignedArea;
        return [ cxTimes6SignedArea / sixSignedArea, cyTimes6SignedArea / sixSignedArea];        
    }
    

提交回复
热议问题