geojson Leaflet弹出窗口不会出现或打破标记

时间:2016-11-11 12:58:46

标签: maps leaflet geojson

我有使用Leaflet显示的geoJson数据。标记出现在地图上,但我无法将弹出窗口绑定到它上面。如果我直接将它附加到标记,则不会出现任何内容。如果我将它附加到图层,它就不会出现,但标记会出现。请查看并告知问题所在!

function playgroundMarker(feature, layer){
    var popupOptions = {width: 200};
    var popupContent = "This is some content";


    var marker = new L.icon({iconUrl: "lib/leaflet/images/play_icon.png"});
    //L.marker.bindPopup(popupContent, popupOptions); - This breaks it
    //layer.bindPopup(popupContent, popupOptions); - This just doesn't appear
    layer.setIcon(marker);

};  
var playground = L.geoJson(playgrounds, {
    onEachFeature: playgroundMarker
}).addTo(map);

2 个答案:

答案 0 :(得分:2)

如果您just .bindPopup(),则不会显示任何内容。这是预期的。

如果您.bindPopup() and then .openPopup(),则会显示弹出窗口。

您遇到的主要问题是致电setIconsetIcon expects its only argument to be an instance of L.Icon L.Marker的实例。该标记已经是layer回调收到的onEachFeature

您不需要(也不应该)在onEachFeature中创建标记。标记是在pointToLayer callback option of L.GeoJSON中创建的。如果您需要创建标记,请覆盖默认的pointToLayer回调并在那里执行。

当您使用GeoJSON时,pointToLayerstyle选项可以将其转换为L.Marker s(pointToLayer),并将LineStrings / Polygons转换为{{1 }} S / L.Polyline秒。将所有GeoJSON要素转换为 标记或折线/多边形后,然后 L.Polygon遍历所有要素。将它们混合起来很容易。

答案 1 :(得分:0)

我不确定我是否理解你,但如果你有geojson对象,你可以使用pointToLayer函数添加标记。 eachFeature函数适用于绑定弹出窗口。

var playground = L.geoJson(playgrounds, {
     pointToLayer: function (feature, latlng) {
         return L.marker(latlng, {icon: new L.icon({iconUrl: "lib/leaflet/images/play_icon.png"})});
     },
    onEachFeature: playgroundMarker
}).addTo(map);



function playgroundMarker(feature, layer) {
            var popup = new L.Popup({
                autoPan: false,
                keepInView: true,
                closeButton: false,
                offset: new L.point(0, -5)
            }).setContent("This is some content");


        layer.bindPopup(popup);
        //you can also choose the click event oder simply no event and add layer.openPopup();
        layer.on({
            mouseover: function () {
                layer.openPopup();
            },
            mouseout: function () {
                layer.closePopup()
            },
            mousemove: function (e) {
                popup.setLatLng(e.latlng);
            }
        });
    }