How to draw a polygon in google map using many coordinates

前端 未结 2 994
执笔经年
执笔经年 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
    });
    

提交回复
热议问题