我正在使用具有硬编码值的函数为传单地图上的多边形分配颜色。样式函数是从内部调用的$.getJSON
。我想重写我的代码,以便直接从数据中提取值而不是硬编码 - 从理论上讲,这样我将来可以更轻松地重用代码
调用的(截断的)geojson数据$.getJSON
是:
{"type": "FeatureCollection","crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [{"type": "Feature", "properties": {"MAJORCOLOR": "ZONE A"}, "geometry": { "type": "Polygon", "coordinates": [ [ [ -77.946264290220981, 42.574112051418197 ], [ -77.954525714402251, 42.569801987122105 ], [ -77.964847297117899, 42.562124252064194 ]]]}},
"features": [{"type": "Feature", "properties": {"MAJORCOLOR": "ZONE B"}, "geometry": { "type": "Polygon", "coordinates": [ [ [ -77.946264290220981, 42.574112051418197 ], [ -77.954525714402251, 42.569801987122105 ], [ -77.964847297117899, 42.562124252064194 ]]]}},
"features": [{"type": "Feature", "properties": {"MAJORCOLOR": "ZONE A"}, "geometry": { "type": "Polygon", "coordinates": [ [ [ -77.946264290220981, 42.574112051418197 ], [ -77.954525714402251, 42.569801987122105 ], [ -77.964847297117899, 42.562124252064194 ]]]]}}]}
是$.getJSON
:
$.getJSON('data/ecozone_wgs84_multipart.geojson', function(data){
var geojsonLayer = L.geoJson(data.features, {
onEachFeature: makeMarkers,
//this provides thematic styling to the layers
style: style
})
.addTo(map);
//call the function to create keys
getArray(data);
});
这是根据数据值分配颜色的函数
//get color depending on the Zone value
function getColor(z) {
return z == 'ZONE A' ? '#a6cee3':
z == 'ZONE B' ? '#1f78b4':
z == 'ZONE C' ? '#b2df8a':
'#000000';}
依次由style
函数从内部调用$.getJSON
function style(feature) {
return {
fillColor: getColor(feature.properties.MAJORCOLOR),
color: getColor(feature.properties.MAJORCOLOR),
weight: 1.25,
opacity: 0.95,
fillOpacity: 0.5
};}
我想重写该getColor
函数,以便不再使用硬编码值来确定颜色,而是从我从 geojson 创建的数组中提取值,我编写如下:
//this is a function that pulls the values from MAJORCOLOR to create the array
function getArray(data) {
for (var i=0; i< data.features.length; i++) {
keys.push(data.features[i].properties.MAJORCOLOR);
}}
//this is a function to collapse to unique values
function unique(keys) {
return keys.reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);};
但是,当我重写颜色函数以使用数组中的值时它不起作用 - 多边形都被分配了“其他”颜色 #000000 而不是我想要的颜色。
function getColor(z) {
return z == unique(keys)[0] ? '#a6cee3':
z == unique(keys)[1] ? '#1f78b4':
z == unique(keys)[2] ? '#b2df8a':
'#000000';}
为什么这不起作用?
unique(keys)
从控制台看,我["ZONE A", "ZONE B", "ZONE C"]
知道我正在keys
正确地创建......我很困惑。
提前感谢您解决我的问题!