How to draw a polygon in google map using many coordinates

Viewed 6035

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. I have found the good tutorial in google apis but that example works well only for 3 points.

Can anybody please help or refer me any tutorial where I can create a polygon without intersecting between lines.

Thank You.

2 Answers

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

Graham scan

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
});
Related