【问题标题】:Ionic2 Leaflet marker onClick event with geoJson带有geoJson的Ionic2 Leaflet标记onClick事件
【发布时间】:2018-02-27 12:13:03
【问题描述】:

将 onClick 事件添加到由 GeoJSON 生成的标记时出现错误。我尝试过使用以下内容:

layer.on(‘click’, (e)=> {this.onMapClick(e)});

点击时我收到的错误是

ERROR TypeError: _this.onMapClick 不是函数

onMapClick(e) {
    console.log(e.latlng.lng, e.latlng.lat)
}
initMap() {
    this.MapData.getPoints().subscribe((res) => {

        this.markers = res;

        function oneachFeature(feature, layer) {
            layer.bindPopup(feature.properties.description);
            layer.on('click', (e) => {
                this.onMapClick(e)
            });

        }
        var myLayer = L.geoJSON(this.markers, {
            pointToLayer: function(feature, latlng) {
                if (feature.properties.route === "red") {
                    var smallIcon = new L.Icon({
                        iconSize: [27, 27],
                        iconAnchor: [13, 27],
                        popupAnchor: [1, -24],
                        iconUrl: 'assets/images/redx2.png'
                    });
                    return L.marker(latlng, {
                        icon: smallIcon
                    });
                } else if (feature.properties.route === "blue") {
                    var smallIcon = new L.Icon({
                        iconSize: [27, 27],
                        iconAnchor: [13, 27],
                        popupAnchor: [1, -24],
                        iconUrl: 'assets/images/bluex2.png'
                    });

                    return L.marker(latlng, {
                        icon: smallIcon
                    });
                }
            },
            onEachFeature: oneachFeature
        })

        myLayer.addTo(this.map);
    });
}

【问题讨论】:

    标签: angular ionic2 leaflet


    【解决方案1】:

    问题:您正在通过onEachFeature: oneachFeature 丢失范围(this),您可以通过以下方法之一维护范围。


    您只需发送邮件至bind(this)

    onEachFeature: oneachFeature.bind(this)
    

    或使用 ES6(粗箭头运算符)

    onEachFeature: (feature, layer) => oneachFeature(feature, layer)
    

    onEachFeature : (feature, layer) => {
        layer.bindPopup(feature.properties.description);
        layer.on('click', (e) => {
            this.onMapClick(e)
        });
    }
    

    【讨论】:

    • @VivekDoshi 很高兴添加了解释和几种可能的解决方案!
    猜你喜欢
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 2019-03-11
    • 2015-02-11
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多