首页 > 解决方案 > 如何以编程方式放置自定义 Leaflet.draw 形状?

问题描述

我想从数据库中恢复一个自定义的 L.Draw.Marker (L.Draw.Waypoint),但是当我尝试初始化它时,结果不是一个合适的层,而只是处理程序。如果不使用鼠标单击按钮来激活处理程序,然后在地图上的某个位置放置航点,我怎么能做到这一点?

我能够用 L.geoJson() 做一些接近的事情,但这只是一个没有我的航点对象功能的普通标记......或者有没有办法从 GeoJSON 层创建一个航点?

像这样的东西:

function load_shape() {
    let test_wp = {
        "type": "Feature",
        "properties": {
            "layer_type": "waypoint",
            "map_id": 0,
            "rotation": -44
        },
        "geometry": {
            "type": "Point",
            "coordinates": [27.712348, 5.000000]
        }
    };
    
    let geojson = L.geoJson(test_wp); <- works
    let wp = waypoint(map, geojson._layers[geojson._leaflet_id-1]); <- works too, but this is 
                                                                       just the handler

    drawnItems.addLayer(wp.layer); <- doesn't work of course, just to get the idea...
    - or -
    wp.layer.addTo(map)
}

标签: javascriptjsonleafletgeojsonleaflet.draw

解决方案


我找到了一个解决方案:

L.geoJson(test_wp, {
            // style: function (feature) {
            //     return {color: feature.properties.color};
            // },
            pointToLayer: function (feature, latlng) {
                return L.marker(latlng, {
                    draggable: true,
                    icon: L.icon({
                        iconUrl: 'static/images/icons/arrow-alt-circle-up-regular.svg',
                        iconSize: [18, 18],
                        iconAnchor: [9, 9],
                    }),
                    rotationOrigin: 'center center',
                })
            },
            onEachFeature: function (feature, layer) {

                layer.on('click', function (e) {
                    //open a popup or whatever
                });

                layer.on('drag', function (e) {
                    //when dragging do...
                });

                layer.bindPopup(feature.properties.description).addTo(drawnItems);
            }
        });

这不会创建我的自定义标记,但我可以为它提供我需要的所有功能。


推荐阅读