Leaflet结合wms和wfs实现点击选中要素
Openlayers结合wfs服务要素选中的方法较为简单, 参考官方文档搜索select案例即可。但是leaflet并没有封装相关选中要素的函数,所有需要自己写方法请求wfs服务来实现选中要素功能。
具体思路如下:
1、读取wms服务(3857坐标),添加图层至map对象
this.planLayer = L.tileLayer.wms("http://*.*.*.*:8090/geoserver/cite/wms", {
layers: 'cite:land',
format: 'image/png',
transparent: true
}).addTo(this.map);;
2、对map对象添加点击事件,并将点击事件的经纬度坐标转成3857坐标
this.map.on('click', (res) => {
if (document.getElementById("popup")) { document.getElementById("popup").parentNode.removeChild(document.getElementById("popup"))
}
if (this.clickResLayer) this.clickResLayer.clearLayers();
var pt = L.CRS.EPSG3857.project(res.latlng)
this.getClickFeatrue(pt)
})
3、获取点击事件坐标后,用该坐标拼接CQL_FILTER参数,请求wfs服务。
!!注意srsName参数要选4326坐标系,可以返回4326坐标的geojson,再将返回的geojson作为图层添加至map对象中;此外,案例中的wms和wfs服务均为geoserver发的服务,geoserver发的wms和wfs才能使用CQL_FILTER。
getClickFeatrue(pt) {
var urlString = "http://*.*.*.*:8090/geoserver/cite/wfs";
var param = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'cite:land',
outputFormat: 'application/json',
maxFeatures: 3200,
srsName: 'EPSG:4326',
CQL_FILTER: 'INTERSECTS(geom,POINT(' + pt.x + ' ' + pt.y + '))'
};
uni.request({
url: urlString + L.Util.getParamString(param, urlString),
success: (res) => {
console.log(res.data.features["0"].properties.objectid)
var content = '<a id="popup" style="text-decoration: underline;cursor: pointer;">' +
res.data.features[0].properties.objectid + '</a>'
var jsonObj = L.geoJSON(res.data)
this.clickResLayer = jsonObj.addTo(this.map);
jsonObj.bindPopup(content).openPopup()
this.popup = document.getElementById("popup")
this.popup.onclick = () => {
this.handlePopClick()
}
}
})
},