如何与地图外部的传单标记图层进行交互?

roy*_*roy 28 javascript jquery geojson leaflet

我有一个传单地图,显示从GeoJSON渲染的公共艺术作品的点.在地图旁边,我创建了一个来自相同GeoJSON数据的片段列表,并且希望能够从地图外部的列表中单击某个项目,并在地图上显示相关标记的弹出窗口.

如何通过点击事件将项目列表链接到各自的标记?

我的map.js文件如下所示:

var map;
var pointsLayer;

$(document).ready(function () {
    map = new L.Map('mapContainer');
    var url = 'http://{s}.tiles.mapbox.com/v3/mapbox.mapbox-streets/{z}/{x}/{y}.png';
    var copyright = 'Map data © 2011 OpenStreetMap contributors, Imagery © 2011 CloudMade';
    var tileLayer = new L.TileLayer(url, {
        attribution: copyright
    });
    var startPosition = new L.LatLng(41.883333, - 87.633333);
    map.on('load', function (e) {
        requestUpdatedPoints(e.target.getBounds())
    });
    map.setView(startPosition, 13).addLayer(tileLayer);
    map.on('moveend', function (e) {
        requestUpdatedPoints(e.target.getBounds())
    })
});

function requestUpdatedPoints(bounds) {
    $.ajax({
        type: 'GET',
        url: '/SeeAll',
        dataType: 'json',
        data: JSON.stringify(bounds),
        contentType: 'application/json; charset=utf-8',
        success: function (result) {
            parseNewPoints(result);
            addToList(result)
        },
        error: function (req, status, error) {
            alert('what happen? did you lose conn. to server ?')
        }
    })
}

function addToList(data) {
    for (var i = 0; i < data.features.length; i++) {
        var art = data.features[i];
        $('div#infoContainer').append('<a href="#" class="list-link" title="' + art.properties.descfin + '"><div class="info-list-item">' + '<div class="info-list-txt">' + '<div class="title">' + art.properties.wrknm + '</div>' + '<br />' + art.properties.location + '</div>' + '<div class="info-list-img">' + art.properties.img_src + '</div>' + '<br />' + '</div></a>')
    }
    $('a.list-link').click(function (e) {
        alert('now you see what happens when you click a list item!');
        e.preventDefault()
    })
}

function parseNewPoints(data) {
    if (pointsLayer != undefined) {
        map.removeLayer(pointsLayer)
    }
    pointsLayer = new L.GeoJSON();
    var geojsonMarkerOptions = {
        radius: 8,
        fillColor: "#FF6788",
        color: "YELLOW",
        weight: 1,
        opacity: 1,
        fillOpacity: 0.5
    };
    L.geoJson(data, {
        pointToLayer: function (feature, latlng) {
            return L.circleMarker(latlng, geojsonMarkerOptions)
        },
        onEachFeature: function (feature, pointsLayer) {
            pointsLayer.bindPopup(feature.properties.img_src + "<br />" + feature.properties.wrknm + "<br />" + feature.properties.artist + "<br />" + feature.properties.location + '<div class="description">' + feature.properties.descfin + '</div>')
        }
    }).addTo(map)
}
Run Code Online (Sandbox Code Playgroud)

InP*_*uit 35

Felix Kling是对的,但我会稍微扩展他的评论......

由于L.LayerGroup和L.FeatureGroup(L.GeoJSON从中扩展)没有方法来检索单个图层,您需要从L.GeoJSON扩展并添加这样的方法或保持您自己的独立ID从唯一ID到来自GeoJSON的CircleMarker.

GeoJSON不需要唯一的ID,但我会假设您的Feed中的标记具有名为"id"的唯一ID属性.您需要将此唯一ID添加到用户可以单击的链接,以便链接可以在地图上选择正确的标记.然后,您需要将标记的地图存储到标记,以便检索标记以在地图上选择标记.

markerMap = {}; // a global variable unless you extend L.GeoJSON

// Add the marker id as a data item (called "data-artId") to the "a" element
function addToList(data) {
    for (var i = 0; i < data.features.length; i++) {
        var art = data.features[i];
        $('div#infoContainer').append('<a href="#" class="list-link" data-artId=\"'+art.id+'\" title="' + art.properties.descfin + '"><div class="info-list-item">' + '<div class="info-list-txt">' + '<div class="title">' + art.properties.wrknm + '</div>' + '<br />' + art.properties.location + '</div>' + '<div class="info-list-img">' + art.properties.img_src + '</div>' + '<br />' + '</div></a>')
    }
    $('a.list-link').click(function (e) {
        alert('now you see what happens when you click a list item!');

        //Get the id of the element clicked
        var artId = $(this).data( 'artId' );
        var marker = markerMap[artId];

        //since you're using CircleMarkers the OpenPopup method requires
        //a latlng so I'll just use the center of the circle
        marker.openPopup(marker.getLatLng());
        e.preventDefault()
    })
}
Run Code Online (Sandbox Code Playgroud)

从服务器获取数据时,需要构建markerMap.您的pointToLayer方法可以修改为:

L.geoJson(data, {
    pointToLayer: function (feature, latlng) {
      var marker = new L.CircleMarker( latlng, geojsonMarkerOptions );
      markerMap[feature.id] = marker;
      return marker;
    },...
Run Code Online (Sandbox Code Playgroud)

  • 我想知道使用当前最新版本的LeafletJS是否有更简单的方法. (3认同)

Ski*_*ack 5

我知道这是一个老问题,但传单是它的方式,以提供一个内置的解决方案,有一个(有点)内置的方式来实现,现在它...

该方法将使用layerGroup接口。它提供了一种方法,getLayer听起来像使用ID来获得我们的标记是完美的。然而,在这个时候,小叶没有提供任何方法来指定自定义ID或名称

Github上的这个问题讨论了应该如何做。这样,您就可以获取并保存任何标记的自动生成的ID(或iLayer就此而言),如下所示:

let people = [...],
    group = L.layerGroup()

people.forEach(person => {
    let marker = // ... create marker

    group.addLayer( marker );
    person.marker_id = group.getLayerId(marker)
})
Run Code Online (Sandbox Code Playgroud)

现在我们已将每个标记的ID与每个后备对象一起保存在数据数组中,我们以后可以轻松地获得标记,如下所示:

group.getLayer(person.marker_id)
Run Code Online (Sandbox Code Playgroud)

有关完整示例,请参见此笔;有关更多选项,请参见此问题