javascript - 如何将自定义 Wordpress 字段传递到 mapbox-gl js 以在地图上创建标记?
问题描述
我正在尝试使用 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:如何将自定义字段传递到 mapbox-gl js 以在地图上创建点?
解决方案
基本上,这里有三种解决方案。当然,哪一个与您相关在很大程度上取决于您的用例!
在用于将脚本排入队列并使用来自查询的数据本地化 wp_localize_script 中的变量的函数中运行您的自定义发布查询(Jasper B 他的上述解决方案:))
将 php 内联到脚本中。PHP 代码与内联脚本在同一页面上(hacky 但快速测试)。像这样的东西(更正关闭的php):
var data = <?php $data ?"> // TODO 请更正这个!我这里不能写。只要是编码的,它应该为你提供一个数据数组,只需 console.log 看看是否这是正确的。
您可以使用 Ajax 或 Wordpress REST 创建端点,并在您的 JS 文件中查询数据并显示它。这是有关如何设置 Ajax Get 请求的更多信息
推荐阅读
- excel - SSIS 自动从数据库生成 Excel 文件
- adb - “adb version”输出中的版本号是什么意思
- laravel - 如果产品仅与一个“子类别”相关,如何获得“主类别”的产品?
- android - W/System.err: java.lang.Exception: FFmpeg 未加载
- python - 使用烧瓶、python、HTML 和 PostgreSQL 加载 Web 应用程序时出现问题;无法连接 python 和 html 脚本以及内部服务器错误消息
- javascript - 光滑的滑块有 12 个项目,slidesToScroll 5 和 slidesToShow 5 不滑动每张幻灯片 5 个项目
- powershell - 如何删除 Powershell 中的前导和尾随空格?
- python - os.path.abspath 从哪里执行
- routes - 如何为 Camel 组件/端点编写 Camel Quarkus 扩展?
- azure - AzureSearch edgeNGram 搜索匹配太多文档