如何在 Leaflet 中子类化多边形?

How to subclass Polygon in Leaflet?

我正在尝试为 Leaflet 创建一个十六进制 class,其中中心和边长应该以屏幕单位(像素)而不是 lat/lng 来获得这样的效果 在地图上。

代码在这里:

L.Hex = L.Polygon.extend({
    initialize: function (args) {
        console.log('arguments', JSON.stringify(arguments));
        console.log('arguments[0]', JSON.stringify(arguments[0]));

        // options = options || {};

        this.center  = args[0];
        this.size    = args[1];
        this.options = args[2] || {};

        L.Polygon.prototype.initialize.call(this, [], this.options);
    },

    points: function(center, size, map){
        var latlngs = [0, 1, 2, 3, 4, 5, 6]
            .map(p => this.hexCorner(center, size, p))
            .map(p => map.layerPointToLatLng(p));
        return latlngs;
    },

    hexCorner: function(center, size, i){
        var angle_deg = 60 * i - 30;
        var angle_rad = Math.PI / 180 * angle_deg;

        return [center[0] + size * Math.cos(angle_rad),
                center[1] + size * Math.sin(angle_rad)]
    },
})

L.hex = function(){ return new L.Hex(arguments) }

由于坐标在用户 space 中,我认为只能在添加到地图后才能计算它们 - 但那是失败的原因。如果像这样添加点:

var h = L.hex([100, 100], 30);
var points = h.points([100, 100], 30, e.map);
h.setLatLngs(points);
h.addTo(map);

一切正常,但我在 onAdd 上的最佳尝试是:

onAdd: function (map) {
    var points = this.points(this.center, this.size, map);
    this.setLatLngs(points);
    map.addLayer(this);
},

有消息TypeError: t._path is undefined

那么问题来了:问题出在哪里,否则我该怎么办?

this.setLatLngs(points) 更改为 this._setLatLngs(points);

使用 setLatLngs() 函数 this.redraw(); 被调用,这需要映射变量,它应用 map.addLayer(this)