如何在leaflet.js中正确添加多边形

时间:2018-11-11 08:52:57

标签: leaflet

使用leaflet.js渲染多边形时。 以下示例具有不同的结果。

示例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


示例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

为什么?

如果我必须像示例2一样设置latlngs数据,该怎么办?

1 个答案:

答案 0 :(得分:3)

原因是Leaflet默认使用纬度和经度,并使用Web Mercator投影将其投影在平面上。在第二个多边形上,坐标为out of bounds for latitude

如果只需要在“像素”坐标中绘制三角形,则可以使用CRS.Simple

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

请参见JSFiddle:http://jsfiddle.net/ekqvwo76/