![](/img/trans.png)
[英]How to pass custom Wordpress fields into mapbox-gl js to create markers on map?
[英]How to pass custom fields into mapbox-gl js to create points on map?
我使用 mapbox 創建了一張地圖,並繪制了多個可以與之交互的自定義點。 我也在使用 Wordpress 並希望使用高級自定義字段來創建每個點,以便非技術人員可以輕松管理它們。 這些字段都已設置,但我無法將它們傳遞到我的 php 模板中的 javascript 中。
我試過使用循環,但我不能在 javascript 中使用循環。 這是我用來繪制點並希望使用高級自定義字段的 Mapbox 代碼:
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/coptmarketing/cjvi7hc4602dk1cpgqul6mz0b',
center: [-76.615573, 39.285685],
zoom: 16 // starting zoom
});
var geojson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"title": "Shake Shack",
"id": "shake-shack"
},
"geometry": {
"type": "Point",
"coordinates": [-76.609844, 39.286894]
}
},
{
"type": "Feature",
"properties": {
"title": "Starbucks",
"id": "starbucks"
},
"geometry": {
"type": "Point",
"coordinates": [-76.619071, 39.286649]
}
}
]
};
我已經將數據存儲在一個 JSON 數組中:
[{"title":"Shake Shack","slug":"shake-shack","latitude":"-76.609844","longitude":"39.286894"},{"title":"Starbucks","slug":"starbucks","latitude":"-76.619071","longitude":"39.286649"}]
如何將其插入到 geoJSON 中?
弄清楚了:
首先,我創建了一個插件,將自定義帖子數據存儲在 JSON 數組中並將其存儲在服務器上。 每次我更新、保存或刪除帖子時,這也會更新。 這是示例 JSON:
data = {"placeList": [{"title":"Shake Shack","slug":"shake-shack","latitude":"-76.609844","longitude":"39.286894"},{"title":"Starbucks","slug":"starbucks","latitude":"-76.619071","longitude":"39.286649"}]}
然后在 php 文件中,我調用了 .json 文件,並在我的 javascript 中,將數組插入到 GeoJSON 中:
var placeJson = data;
var geojson = {
type: "FeatureCollection",
features: [],
};
for (i = 0; i < placeJson.placeList.length; i++) {
geojson.features.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [placeJson.placeList[i].latitude, placeJson.placeList[i].longitude]
},
"properties": {
"id": placeJson.placeList[i].slug,
"title": placeJson.placeList[i].title
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.