3

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.

S S
  • 1,443
  • 2
  • 12
  • 42
  • 1
    You're talking about [this example](https://developers.google.com/maps/documentation/javascript/examples/polygon-simple?hl=en)? Because if so just add more coordinate inside the chords array. – m.nachury Jul 12 '17 at 12:46
  • @m.nachury, yes if i add more coordinates then then there is crossing of lines. – S S Jul 12 '17 at 13:25
  • @S S Then I think you have an issue with your coordinates , It works fine for me even with 20 coordinates . Can you give me an example of your coordinates ? I feel like you should not send them all... – m.nachury Jul 12 '17 at 13:31
  • @m.nachury https://jsfiddle.net/e0L9g38a/ can you please look here. There is crossing of line. Well I want to know how to sort those coordinates so that the lines do not cross – S S Jul 12 '17 at 13:57
  • Edited you a proper Answer – m.nachury Jul 12 '17 at 14:11

2 Answers2

3

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
});
m.spyratos
  • 3,823
  • 2
  • 31
  • 40
2

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

m.nachury
  • 972
  • 8
  • 23