根据 geoJSON 属性设置不同的 L.divIcon 样式

Set different L.divIcon style depending on geoJSON properties

我正在使用 L.divIcon 在 Leaflet/Mapbox.js 地图上设置标记样式。我已设法为地图上的所有要素设置一个 className,但我想根据与每个要素关联的属性设置不同的 classes。似乎我尝试过的每个配置要么返回 "feature is not defined" 错误,要么只会 return 默认 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" 和 "false" 以及 return 和我在样式表中定义的 css class:

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;
        }};

然后创建函数return class根据在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});
    }   

但无论如何,我得到的只是默认的传单-div-图标,并且我在控制台中得到零错误。我错过了什么?

L.divIcon takes an object as input

var damIcon = L.divIcon(setDivIcon);

setDivIcon 是一个函数,它returns一个对象,而不是一个对象。

正确的调用应该是

var damIcon = L.divIcon(setDivIcon(feature));

一起:

pointToLayer: function (feature, latlng) {
    return L.marker(latlng, { icon: L.divIcon(setDivIcon(feature)) });
}