How to draw a polygon in google map using many coordinates

前端 未结 2 964
执笔经年
执笔经年 2021-01-07 03:04

I have an array containing latitude and longitude of different location which is displayed in the google map. Now I need to make a polygon passing through all these points.

相关标签:
2条回答
  • 2021-01-07 03:37

    You can use the Graham scan method to find the convex hull of your coordinate points and pass those to your polygon.

    There is a javascript implementation of the algorithm:
    https://github.com/brian3kb/graham_scan_js

    The above repo also has an example of how to implement this with Google Maps:
    https://github.com/brian3kb/graham_scan_js/blob/master/example/app1.js


    Here's a basic implementation of the above:

    function getConvexHullCoords(coords) {
        const convexHull = new ConvexHullGrahamScan();
    
        coords.forEach(item => {
            convexHull.addPoint(item.lng, item.lat);
        });
    
        return convexHull.getHull().map((item) => {
            return {
                lat: item.y,
                lng: item.x
            };
        });
    }
    
    const coords = [
        {lat: 37.772, lng: -122.214},
        {lat: 21.291, lng: -157.821},
        {lat: -18.142, lng: 178.431},
        {lat: -27.467, lng: 153.027}
    ];
    
    new google.maps.Polygon({
        paths: [getConvexHullCoords(coords)],
        fillColor: '#000',
        fillOpacity: 0.5
    });
    
    0 讨论(0)
  • 2021-01-07 03:41

    Just take the example you took and add more points.

    However, with more than three points, you'll have intersection trouble if you don't sort the coordinates properly.

    To fix it you'll need an algorithm:

    Here is the answer: Sorting points to avoid intersections.

    You can stop at the second point of the answer, you just calculate the center of your polygon and then the angles to sort the points.

    However, you can't use latitude and longitude with this algorithm.

    For this scale you can just project your coordinates to a 2d plane.

    Go for this: merkator projection

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