leaflet 列表查询popup与地图popup

项目中地图布局如下。要实现点击右侧列表中某一项时,在地图中出现popup。


image.png

列表查询实现地图popup

在leaflet中以geojosn加载的图层,其实第个几何体就是一个图层,一个geojson文件创建的其实是包含各个几何体图层的FeatureGroup。因此,当点击右侧列表时,获取所点击的项的id,然后在地图中获取map._layers,在layers中查询满足条件的layer,然后在layer中可以:

  • 获取图层当前的popup对象:layer.getPopup()
  • 获取图层当前的popup内容:layer.getPopup().getContent()
  • 设置图层的popup内容:layer.setPopupContent(response.popupContent);
  • 打开popup:layer.openPopup(layer._latlng);
    在这里定义了函数showStationPopup,用于在地图中打开popup:
function showSationPopup(stationId, layer) {
    if (!layer.getPopup().getContent()) {
        initStationPopupContent(stationId, layer).then(function (response) {
            layer.setPopupContent(response.popupContent);
            layer.openPopup(layer._latlng);
        });
    } else {
        layer.openPopup(layer._latlng);
    }
}

由于在geojson创建图层时,里面的onEachFeature会全部调用一次,所以为提高首次数据加载速度,把对每个popup内容的获取放到了打开popup时。当要打开popup时,首先判断内容是否为空,若为空则进行异步数据请求。
异步数据请求采用了axios。创建请求,并对请求的响应体response进行数据处理,如添加属性等,在这里是添加了response.popupContent。然后返回promise。

image.png

这样当请求完成后,就会在then中获取response中的popup的内容,赋给popup,layer.setPopupContent(response.popupContent);

地图点击出现popup

这里可能存在问题,后面再改进。

layer.on('popupopen', function (e) {
            //console.log("事件信息");
            //console.log(e);
            _map.flyTo([feature.geometry.coordinates[1], feature.geometry.coordinates[0]], 17, {
                animate: true,
                duration: 0.5,
                easeLinearity: 1.0,
                maxZoom: 17
            });
            showSationPopup(Id, layer);
        });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。