【发布时间】:2021-03-07 09:49:02
【问题描述】:
我正在尝试使用 Mapbox 和 Wordpress 创建一个绘制不同点的地图。在 Wordpress 中,我创建了一个自定义帖子类型,其坐标存储在自定义元字段中。这些字段都已设置,但我无法将它们传递到我的 php 模板中的 javascript。
我尝试使用循环,但不能使用它,因为坐标需要存储在 javascript 中。似乎将自定义元字段存储在 geoJSON 中是唯一的解决方案。
这是 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"
},
"geometry": {
"type": "Point",
"coordinates": [-76.609844, 39.286894]
}
},
{
"type": "Feature",
"properties": {
"title": "Starbucks"
},
"geometry": {
"type": "Point",
"coordinates": [-76.619071, 39.286649]
}
}
]
};
我的 PHP 看起来像这样来获取自定义字段并将其转换为 JSON:
<?php $args = array(
'post_type' => 'places',
'post_status' => 'publish',
'nopaging' => true
);
$query = new WP_Query( $args ); // $query is the WP_Query Object
$posts = $query->get_posts(); // $posts contains the post objects
$output = array();
foreach( $posts as $post ) { // Pluck the id and title attributes
$output[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'address' => get_post_meta($post->ID,'ci_cpt_adresse', true),
'longitude' => get_post_meta($post->ID, 'ci_cpt_adressex', true),
'altitude' => get_post_meta($post->ID, 'ci_cpt_adressey', true)
);
}
$data = json_encode(['placelist' => $output]);
?>
然后我尝试通过此脚本处理数据。但是,它不返回任何内容:
<script>
var placeJson = data;
var stores = {
"type:" "FeatureCollection",
"features:" [],
};
for (i = 0; i < placeJson.placelist.length; i++) {
geojson.features.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [placeJson.placelist.[i].altitude, placeJson.placeList[i].longitude]
},
"properties": {
"title": placeJson.placelist.[i].title
}
},);
}
</script>
<script>
stores.features.forEach(function(store, i){
store.properties.id = i;
});
</script>
我已经在这里找到了一个可能的解决方案,但不明白如何将其放入 geoJSON:How to pass custom fields into mapbox-gl js to create points on map?
【问题讨论】:
标签: javascript php json wordpress mapbox