Riccardo Raffini
Riccardo Raffini

Reputation: 396

Leaflet polygon draw a weird shape

So I am using Leaflet map in my page and I have to show a polygon. I get the vertices of the shape from my Node controller and then add them to the map using the following way:

    function fetchAreas(){
        const url='http://localhost:1337/api/areas';
        fetch(url)
        .then((res) => {
            return res.json();
        })
        .then((data) => {
            console.log(data);

            for(d in data){
                var polvertices = [];
                for(c in data[d].Coords)
                    polvertices.push([data[d].Coords[c].Latitude, data[d].Coords[c].Longitude]);

                L.polygon(polvertices, {
                    color: 'red',
                    fillColor: '#f03',
                    fillOpacity: 0.5
                }).addTo(map);
            }
        });
    }

As a result I get the following weird shape: enter image description here

I discovered it is caused by vertices' longitude order, so ordering them by lon. in the controller query result in an other weird shape: enter image description here

So now I am wondering how can I show it correctly or if I am missing something in my code because leaflet example does not show too much.

Thanks for your help.

Upvotes: 1

Views: 676

Answers (1)

Riccardo Raffini
Riccardo Raffini

Reputation: 396

So apparently the solution to this problem is the order of vertices in the coords array, passed to the polygon: they must follow the order of the perimeter of the shape.

I mean if you have to draw a rectangle like this

A +--------------+ B
  |              |
  |              |
D +--------------+ C

using the function

L.polygon(verticesArray).addTo(map);

you must add the vertices ([lat, lon]) in the correct order, coming back to the rectangle, the correct order must be [A, B, C, D].

Not respecting the order may cause errors like in my original question.

Upvotes: 4

Related Questions