gpt4 book ai didi

javascript - 如何使用 for each 语句在 mapbox 上绘制多个点?

转载 作者:行者123 更新时间:2023-11-30 11:26:51 25 4
gpt4 key购买 nike

我有一个经度和纬度的二维数组,我希望能够在 MapBox 上映射每个点。

我的问题是给出的示例是针对两个点的,因此我尝试应用一个 for-each 循环来遍历我的二维数组并绘制这些点。问题是你需要一个唯一的 ID 来添加一个图层。我一直在关注位于此处的本教程: https://www.mapbox.com/help/getting-started-directions-api/

这是我目前的代码,如有任何帮助,我们将不胜感激!

<body>
//create the map
<div id='map'></div>
<div id='instructions'></div>
<script>
mapboxgl.accessToken = 'ACCESS TOKEN KEY';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v9', //stylesheet location
center: [-6.266155,53.350140], // starting position
zoom: 12 // starting zoom
});


//load the route function
map.on('load', function(){
getRoute();
});

//get route takes start and end (lat,long)
function getRoute() {
//create an array
var arr = [
[-6.3053, 53.3562],
[-6.802586, 53.176861],
[-6.5991, 53.0918],
[-6.3053, 53.3562]];

arr.forEach(function(el, index)
{


var nodeOnes = [];
nodeOnes = arr[0];


console.log("here" + n);
map.addLayer({
id: nodeOnes,
type: 'circle',
source: {
type: 'geojson',
data: {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: nodeOnes
}
}
}
});
});
}
</script>

注意我没有包含我的访问 token

最佳答案

您可以添加一个包含所有点的 FeatureCollection,而不是添加具有自己图层的独立点:

const allPoints = arr.map(point => ({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: point
}
}));

map.addLayer({
id: 'path',
type: 'circle',
source: {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: allPoints
}
}
});

关于javascript - 如何使用 for each 语句在 mapbox 上绘制多个点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47702517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com