我使用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 ] } },
我创建了一个切换功能来查找" true"和"假"并返回我在样式表中定义的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;
}};
然后创建一个函数来返回className,具体取决于geoJSON中feature.properties.Main中的结果:
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,我在控制台中得到零错误。我错过了什么?
答案 0 :(得分:1)
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)) });
}