Find centerpoint of polygon in JavaScript

后端 未结 5 1184
余生分开走
余生分开走 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条回答
  •  -上瘾入骨i
    2020-12-15 09:36

    I realize this is not exactly what you are looking for, but in case no one else answers it may be of some help. This is a PHP function which I use to to find the center point of polygons for my map application. It should be fairly easily converted to javascript for your use.

    function getCenter($coord_array){
        $i = 0;
        $center = $coord_array[0];
        unset($coord_array[0]);
        foreach($coord_array as $key => $coord){    
            $plat = $coord[0];
            $plng = $coord[1];
            $clat = $center[0];
            $clng = $center[1];
            $mlat = ($plat + ($clat * $i)) / ($i + 1);
            $mlng = ($plng + ($clng * $i)) / ($i + 1);
            $center = array($mlat, $mlng);
            $i++;
        }
        return array($mlat, $mlng);
    }
    

    Note that the polygon has to be closed, meaning the first point in the array and the last point in the array are the same.

    The function that converts the coordinate string to the necessary array:

    function coordStringToArray($coord_string)
    {
        $coord_array = explode("\n",$coord_string);
        foreach($coord_array as $key => $coord){
            $coord_array[$key] = explode(', ',$coord);
        }
        return $coord_array;
    }
    

    A sample of the raw coordinate string:

    42.390576, -71.074258
    42.385822, -71.077091
    42.382461, -71.079408
    42.382018, -71.081468
    42.380496, -71.080953
    42.380433, -71.076576
    42.373902, -71.073915
    42.373078, -71.069967
    42.369273, -71.064216
    42.368892, -71.062328
    42.369527, -71.056491
    42.370288, -71.050741
    42.371619, -71.047908
    42.376185, -71.046278
    42.383476, -71.045763
    42.386139, -71.050483
    42.386202, -71.057693
    42.387597, -71.066534
    42.390259, -71.072284
    42.391210, -71.073658
    

提交回复
热议问题