传单:如何从 geoJson 数据中设置多边形的样式?

Leaflet: how to style polygons from geoJson data?

我正在尝试解决为什么我的地图没有显示我在 Switch 语句中为两个多边形设置的颜色样式。

(JSfiddle here):

Here's my test data:

L.mapbox.accessToken = 'pk.eyJ1IjoiZG9zcyIsImEiOiI1NFItUWs4In0.-9qpbOfE3jC68WDUQA1Akg';
var map = L.mapbox.map('map', 'mapbox.light')
.setView([40, -74.50], 9);

var myData = [{
  "type": "FeatureCollection",
  "features": [
{
  "type": "Feature",
  "properties": {
    "stroke": "#555555",
    "stroke-width": 2,
    "stroke-opacity": 1,
    "fill": "#555555",
    "fill-opacity": 0.5,
    "Name": "Area One"
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [
          -75.289306640625,
          40.13899044275822
        ],
        [
          -75.5255126953125,
          40.000267972646796
        ],
        [
          -75.29754638671875,
          39.86969567045658
        ],
        [
          -74.97894287109375,
          39.905522539728544
        ],
        [
          -74.9871826171875,
          40.04654018618778
        ],
        [
          -75.289306640625,
          40.13899044275822
        ]
      ]
    ]
  }
},
{
  "type": "Feature",
  "properties": {
    "stroke": "#555555",
    "stroke-width": 2,
    "stroke-opacity": 1,
    "fill": "#555555",
    "fill-opacity": 0.5,
    "Name": "Area Two"
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [
          -75.223388671875,
          40.20195268954057
        ],
        [
          -75.22064208984375,
          40.029717557833266
        ],
        [
          -75.08056640625,
          40.02551125229785
        ],
        [
          -74.9322509765625,
          40.11799004890473
        ],
        [
          -75.02288818359375,
          40.197757023665446
        ],
        [
          -75.223388671875,
          40.20195268954057
           ]
         ]
       ]
     }
   }
  ]
}];

Here are my functions:

function getAreaColor(){
    switch (feature.properties.Name){
     case 'Area One' : return { fillColor: 'blue' };
     case 'Area Two' : return { fillColor: 'yellow' };
      break;
 }
};

function areaStyle(){
  return {
    fillColor: getAreaColor,
    weight: 2,
    opacity: 1,
    color: 'white',
    dashArray: '3',
    fillOpacity: 0.5
 }
};

L.geoJson(myData, {style: areaStyle}).addTo(map);

为什么这两个多边形没有得到我指定的颜色?

好的,所以你在这里遇到了几个问题,我在此 fiddle 中为你解决了这些问题。 http://jsfiddle.net/hx5pxdt8/

1.Your areaStyle 函数不接受 Leaflet 给你的特征参数。

2.Your getAreaColor 函数也没有传递该参数。

3.Your switch 语句是 returning javascript 对象,当你已经在里面时 fillColor 属性...这意味着你只需要return 颜色字符串,而不是对象。