Jesse Luo
Jesse Luo

Reputation: 137

How to add polygon properly in leaflet.js

When using leaflet.js to render polygon. The following examples have different results.

Example 1

const map = L.map('map', {
    preferCanvas: true,
    zoomControl: false,
    attributionControl: false
});
const latlngs = [
    [
        6,
        5
    ],
    [
        7,
        1
    ],
    [
        9,
        2
    ]
];
const polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
map.fitBounds(polygon.getBounds());

enter image description here


Example 2

    ...
    const latlngs = [
        [
            116,
            115
        ],
        [
            117,
            111
        ],
        [
            119,
            112
        ]
    ];
    const polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
    map.fitBounds(polygon.getBounds());

enter image description here

Why is that?

And what can I do if I have to set latlngs data like Example 2.

Upvotes: 1

Views: 2348

Answers (2)

Phan Huỳnh Long
Phan Huỳnh Long

Reputation: 1

If you want to create a polygon based on 4 dots on latitude and longitude, here is the code

    var polygons = [];
    var currentPolygonCoords = [];
    function onMapClick(e) {
        currentPolygonCoords.push(e.latlng);
        L.marker(e.latlng).addTo(map);
        if (currentPolygonCoords.length === 4) { 
            var polygon = L.polygon(currentPolygonCoords, { color: 'purple' }).addTo(map); 
            polygons.push(polygon); 
            currentPolygonCoords = []; 
        }
    }
    map.on('click', onMapClick);

Upvotes: 0

thibautg
thibautg

Reputation: 2042

The reason is that Leaflet uses latitude and longitude by default and projects it on a plane using a Web Mercator projection. On your second polygon, the coordinates are out of bounds for latitude.

If you just need to draw a triangle in "pixel" coordinates, you can use CRS.Simple.

const map = L.map('map', {
    preferCanvas: true,
    zoomControl: false,
    attributionControl: false,
    // Add this line:
    crs: L.CRS.Simple
});

See JSFiddle: http://jsfiddle.net/ekqvwo76/

Upvotes: 3

Related Questions