我正在使用L.divIcon在Leaflet / Mapbox.js地图上设置标记样式。我已经设法为地图上的所有要素设置了单个className,但是我想根据与每个要素关联的属性来设置不同的类。看来,我尝试过的每种配置都会返回“未定义功能”错误,或者只会返回默认的l.divIcon平方。
http://pennybeames.net/maps/MekongHydroTimeline2.html正在进行的工作
GeoJSON的摘录:
"features": [
{ "type": "Feature", "properties": { "Dam_name": "A Luoi", "Main": "false"}, "geometry": { "type": "Point", "coordinates": [ 107.18, 16.21 ] } },
{ "type": "Feature", "properties": { "Dam_name": "Banda", "Main": "true"}, "geometry": { "type": "Point", "coordinates": [ 97.93, 30.2 ] } },
我创建一个switch函数来查找“ true”和“ false”,并返回我在样式表中定义的css类:
function getClassName(x) {
switch(x) {
case "true":
return 'circle' ;
//'circle set in stylesheet'
break;
case "false":
//'leaflet-div-icon' set by leaflet stylesheet
return 'leaflet-div-icon';
break;
default:
//set default to 'triangle' from my own stylesheet to test if the code
//was recognizing this function and would set everything to 'triangle',
//but it doesn't
return 'triangle';
break;
}};
然后创建一个函数,以根据geoJSON中feature.properties.Main中的结果返回className:
var setDivIcon = function(feature) {
return {
className: getClassName(feature.properties.Main)
};
}
然后创建我的L.divIcon:
var damIcon = L.divIcon(setDivIcon);
稍后,我稍后使用pointToLayer将geoJSON添加到地图中:
pointToLayer: function (feature, latlng) {
return L.marker(latlng, {icon: damIcon});
}
但是无论如何,我得到的只是默认的leaflet-div-icon,并且控制台中的错误为零。我错过了什么?
最佳答案
L.divIcon
takes an object as input
var damIcon = L.divIcon(setDivIcon);
setDivIcon是一个返回对象而不是对象的函数。
一个正确的电话是
var damIcon = L.divIcon(setDivIcon(feature));
一起:
pointToLayer: function (feature, latlng) {
return L.marker(latlng, { icon: L.divIcon(setDivIcon(feature)) });
}
关于javascript - 根据geoJSON属性设置不同的L.divIcon样式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32449111/