jim*_*age 5 javascript jquery leaflet topojson
我正在尝试创建一个可视化某些数据的交互式地图.
我使用了传单贴图和topojson图层.接下来,我尝试使用leaflet标签插件在每个topojson多边形上添加静态标签,即标签应始终在那里,不应对mouseover事件做出反应.
我尝试使用实现bindLabel()方法noHide:true,但它似乎没有工作.因此,我在传单(geojson)多边形上实现了提供给这个问题的简单标签的解决方案.我成功地添加了静态标签.
然后,我有一个函数删除click事件上的topojson多边形.我本来应该删除这个特殊多边形上的标签,但它似乎无法实现.
这是我添加topojson图层和标签的方法:
function addRegions(map) {
var regionLayer = new L.TopoJSON();
$.getJSON('region.topo.json').done(addRegionData);
function addRegionData(topoData) {
regionLayer.addData(topoData);
regionLayer.addTo(map);
regionLayer.eachLayer(addLabel);
regionLayer.eachLayer(handleLayer);
}
function handleLayer(layer) {
layer.on({
click: clickAction
});
}
// Here's the code for adding label
function addLabel(layer) {
var label = new L.Label();
label.setContent(layer.feature.properties.REGION);
label.setLatLng(layer.getBounds().getCenter());
map.showLabel(label);
}
// Here's the code that removes a polygon when it is clicked and retains the previously removed polygon
function clickAction(e) {
regionLayer.eachLayer(function(layer){
map.addLayer(layer);
});
var layer = e.target;
map.removeLayer(layer);
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,此代码在单击时删除了topojson多边形,但标签仍然存在.
我必须删除已移除的特定多边形上的标签,但将标签保留在其他多边形上.
此外,当单击另一个多边形时,应该将其删除,但应保留先前删除的标签,因为还保留了先前删除的多边形.
我不能,因为我的生活想到如何实现这一点.请帮我.
释
首先,您需要维护labels_array标签的存放位置,以便在需要时将其删除.
其次,维护另一个unique_property_array需要存储topojson文件中的唯一属性的位置.
第三,当用户点击任何特征时,我们将获得点击的特征属性并与我们匹配unique_property_array,获取匹配值的索引并从中删除该索引labels_array.此外,先添加标签删除.
代码块
首先,您需要有三个全局变量
var labels_array=[];
var unique_property_array=[];
var labelIndexToRemove='';
Run Code Online (Sandbox Code Playgroud)
其次,通过addLabel()这种方式修改你的功能
function addLabel(layer) {
var label = new L.Label();
label.setContent(layer.feature.properties.REGION);
label.setLatLng(layer.getBounds().getCenter());
map.showLabel(label);
//below two lines are new
labels_array.push(label);
unique_property_array.push(layer.feature.properties.region);
}
Run Code Online (Sandbox Code Playgroud)
最后,以clickAction()这种方式修改您的功能
function clickAction(e) {
regionLayer.eachLayer(function(layer){
map.addLayer(layer);
});
var layer = e.target;
map.removeLayer(layer);
//below lines are new
if(labelIndexToRemove!=''){
map.addLayer(labels_array[labelIndexToRemove]);
}
labelIndexToRemove= unique_property_array.indexOf(e.target.feature.properties.region);
map.removeLayer(labels_array[labelIndexToRemove]);
}
Run Code Online (Sandbox Code Playgroud)
试试这个并告诉我它是否有效.祝好运
| 归档时间: |
|
| 查看次数: |
1646 次 |
| 最近记录: |