我目前正在从事一个涉及 Mapbox GL 的项目。我从服务器获取一个 json 文件,其中包含很多位置点。该文件具有以下结构:
{"location": {"lat": 50.62914, "lon": 5.61972}}
Run Code Online (Sandbox Code Playgroud)
现在我想将它们放置在地图盒中的图层上。问题是mapbox仅支持GeoJSON。因此,我尝试通过以下解决方法来解决此问题。
function updateMap(data) {
console.log("Updating map with " + data.length + " users");
// Converting my json file into a Geojson format by returning type:point, coordinates for every json entry
data.forEach(function(d) {
return {
"type": "Point",
"coordinates": [d.location.lon, d.location.lat]
};
});
};
Run Code Online (Sandbox Code Playgroud)
我不确定这是否可能,所以如果我错了,请纠正我。我想我必须在 forEach 循环之外返回它,否则我只会得到第一个结果。
接下来是添加此 geojson 文件作为图层的源。看起来像这样的东西:
map.on('load', function () {
map.addSource('point', {
"type": "geojson",
"data": //need to add the points that I returned above here.
});
map.addLayer({
"id": "point",
"source": "point",
"type": "circle",
"paint": {
"circle-radius": 8,
"circle-color": "#000"
}
});
});
Run Code Online (Sandbox Code Playgroud)
唯一的问题是我不知道如何从 updateMap 函数的返回中检索所有数据。
提前感谢您的帮助!我希望这是可能的。
亲切的问候,
沃特
GeoJSON 在格式化要素时极其敏感。将每个值推送到数组中,而不是使用“返回”,可能是值得的。
function updateMap(data) {
var test = [];
data.forEach(function(d) {
test.push(JSON.parse('{"type": "Feature", "geometry": {"type": "Point", "coordinates": ['+d.location.lon+','+ d.location.lat+']}}'));
});
}
Run Code Online (Sandbox Code Playgroud)
然后将map.addSource更改为如下所示:
map.on('load', function() {
map.addSource("point", {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": test
}
});
map.addLayer({
"id": "point",
"type": "circle",
"source": "point",
"paint": {
"circle-radius": 8,
"circle-color": "#000"
}
});
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。