【发布时间】:2018-06-10 01:20:24
【问题描述】:
我正在开发一个使用 Leaflet.js 和 geoJson 数据的项目。我正在制作一个等值线图,并试图将一个函数的结果传递给另一个函数。我不认为这种情况是 Leaflet 独有的,我认为在将一个函数的结果作为另一个函数的参数传递时我只是磕磕绊绊。
我有一个函数可以根据从 API 中提取的 GDP 值来设置地图中国家/地区的样式:
function getColor(d) {
return d > 1000000 ? '#005824' :
d > 500000 ? '#238b45' :
d > 200000 ? '#41ae76' :
d > 100000 ? '#66c2a4' :
d > 50000 ? '#99d8c9' :
d > 20000 ? '#ccece6' :
d > 15000 ? '#edf8fb':
'#fff'
}
这个函数被第二个函数调用:
function style(feature) {
return {
fillColor: getColor(100000),
weight: 2,
opacity: 1,
color: 'white',
//dashArray: '3',
fillOpacity: 0.7,
stroke: true,
weight: .5,
fill: true,
clickable: true
};
}
如您所见,我目前将 100000 硬编码为 getColor 函数的参数。我想对此进行更改,以便将 API 中的数据传递给 getColor 而不是这个硬编码值。
我从 API 中提取了 GDP 数据,并且可以使用以下功能对其进行控制台记录:
function getGDP(gdp) {
for(var i = 0; i < countriesData.features.length; i++) {
console.log(countriesData.features[i].properties.name + ' ' + countriesData.features[i].properties.gdp_md_est);
return countriesData.features[i].properties.gdp_md_est;
}
}
如何将 getGDP() 函数的结果传递给 style() 函数内部的 getColor() 函数?
这是否必须涉及闭包?如果是这样,我该如何使用闭包呢?我不相信这个问题是 Leaflet 或这个项目所独有的,我想我只是在思考如何将一个函数的返回值传递给嵌套在第三个函数中的另一个函数时遇到了麻烦。
getColor 函数必须遍历 countriesData.features[i].properties.gdp_md_est 元素。
这样的工作是否可行:
function style(feature) {
return {
//fillColor: getColor(100000),
fillColor: getColor(function(d) {
for(var i = 0; i < countriesData.features.length; i++) {
var data = countriesData.features[i].properties.gdp_md_est;
return data;
}
}),
weight: 2,
opacity: 1,
color: 'white',
//dashArray: '3',
fillOpacity: 0.7,
stroke: true,
weight: .5,
fill: true,
clickable: true
};
}
【问题讨论】:
-
getColor(getGDP(???))- 因为你还没有展示你如何调用 getGDP,所以不确定???应该是什么......你说iterate over可能是错误的......并且没有展示.gdp_md_est与100000的关系如何 -
在样式函数中传递一个回调函数到 getColor 有什么更好的方法?
-
我想摆脱硬编码的 100000 值,并从 API/getGDP 传递 getColor 迭代数据
-
首先,您没有在 getGDP 中进行迭代 - 返回确保您始终返回
countriesData.features[0].properties.gdp_md_est- 请注意0而不是i。另外,我认为fillColor和任何你想要的getGDP之间有一个重要的“链接”来返回你没有展示的东西。你知道你想要什么,但你根本没有解释过 -
fillColor 需要是单值,不能迭代,是样式属性
标签: javascript function parameters leaflet closures