编辑:这是一个jsfiddle模型:https://jsfiddle.net/6t8gnegf/
我有一张地图外的位置表,我希望在相应的表格元素被鼠标悬停时,每个区域都会突出显示。所以我首先列出一个geojson图层列表,由name属性键入:
var layarr = {}
for (i=0;i<listOfNames.length;i++) {
for (var prop in geojson['_layers']) {
if (!geojson['_layers'].hasOwnProperty(prop)) {
continue;
}
if (geojson['_layers'][prop]["feature"]["properties"]["name"]==listOfNames[i]) {
layarr[listOfNames[i]] = geojson['_layers'][prop]
}
}
}
然后我调用这个函数:
function highlight(name) {
var laytouse = layarr[name]
laytouse.setStyle(highlightStyle)
}
没有任何事情发生,甚至没有错误。
我已经有一个高亮显示功能,可以在地图上的实际区域被覆盖时起作用:
function highlightFeature(e) {
var layer = e.target;
layer.setStyle(highlightStyle);
}
以下列方式调用:
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
});
}
geojson=L.geoJson(neighbData, {style: style,
onEachFeature: onEachFeature
}).addTo(mymap);
即使我直接在控制台上做这样的事情:
layarr[name].setStyle({fillOpacity: 1});
我仍然一无所获。看起来我以某种方式得到了错误的图层,但该图层具有预期的setStyle()方法,而且我没有收到任何控制台错误。
编辑:jsfiddle模型:https://jsfiddle.net/6t8gnegf/
答案 0 :(得分:3)
你的问题非常接近这个问题:Accessing Leaflet.js GeoJson features from outside。诀窍在于geoJSON层实际上是一个图层组,因此您可以使用图层组方法,例如getLayer()。
您的想法是,您希望根据其ID访问您的功能。首先需要将多边形ID附加到表中的位置(在我的gist示例的列表中):
function onEachFeature(feature, layer) {
nhood = parseInt(feature.id);
name = feature.properties.name;
$('#neighborhood').append('<li value="' + nhood + '">'+name+'</li>');
layer._leaflet_id = nhood;
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
});
}
然后,当您将鼠标指向某个位置时,突出显示与该位置ID匹配的功能,如下所示:
var hovered_id, layer;
$('#neighborhood li').on('mouseenter', function(e){
hovered_id = e.target.value;
layer = geojson.getLayer(hovered_id); //your feature id here
layer.setStyle(highlightStyle);
}).on('mouseout', function(e){
geojson.resetStyle(layer);
});
请查看the gist I created,您会看到代码实际上比您最初分享的代码简单得多。
编辑:传单ID必须是唯一的,并且邻域名称应分配给要素ID。以下是更新后的代码:
function onEachFeature(feature, layer) {
name = feature.properties.name;
$('#neighborhood').append('<li data-value="' + name + '">'+name+'</li>');
layer._leaflet_id = name;
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
});
}
var hovered_id, layer;
$('#neighborhood li').on('mouseenter', function(e){
hovered_id = $(e.target).data('value');
console.log(hovered_id);
layer = geojson.getLayer(hovered_id); //your feature id here
layer.setStyle(highlightStyle);
}).on('mouseout', function(e){
geojson.resetStyle(layer);
});