Find centerpoint of polygon in JavaScript

后端 未结 5 1188
余生分开走
余生分开走 2020-12-15 08:39

I have a \"place\" object from Google Maps which has a set of coordinates that represent a bounding box for a given location, say London. Each set of coordinates has a latit

5条回答
  •  暖寄归人
    2020-12-15 09:42

    Here is my es6 solution to average an array of latitudes and longitudes. Average is not the exact center point but it gets the job done in my case.

    getLatLonCenterFromGeom = (coords) => {
        const arrAvg = arr => arr.reduce((a,b) => a + b, 0) / arr.length;
    
        const centerLat = arrAvg(coords.map(c=>c.latitude));
        const centerLon = arrAvg(coords.map(c=>c.longitude));
    
        if (isNaN(centerLat)|| isNaN(centerLon))
            return null;
        else return {latitude: centerLat, longitude:centerLon};
    }
    

提交回复
热议问题