Javascript 如何将自定义Wordpress字段传递到mapbox gl js以在地图上创建标记?
我正在尝试使用Mapbox和Wordpress创建一个绘制不同点的地图。在Wordpress中,我创建了一个自定义post类型,坐标存储在自定义元字段中。这些字段都是设置好的,但是我在将它们传递到php模板中的javascript时遇到了问题 我尝试使用循环,但无法使用它,因为坐标需要存储在javascript中。似乎在geoJSON中存储自定义元字段是唯一的解决方案 以下是Mapbox代码的外观,坐标和标题应来自帖子和自定义字段:Javascript 如何将自定义Wordpress字段传递到mapbox gl js以在地图上创建标记?,javascript,php,json,wordpress,mapbox,Javascript,Php,Json,Wordpress,Mapbox,我正在尝试使用Mapbox和Wordpress创建一个绘制不同点的地图。在Wordpress中,我创建了一个自定义post类型,坐标存储在自定义元字段中。这些字段都是设置好的,但是我在将它们传递到php模板中的javascript时遇到了问题 我尝试使用循环,但无法使用它,因为坐标需要存储在javascript中。似乎在geoJSON中存储自定义元字段是唯一的解决方案 以下是Mapbox代码的外观,坐标和标题应来自帖子和自定义字段: var map = new mapboxgl.Map({
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>
var placeJson=数据;
变量存储={
类型:“FeatureCollection”,
“功能:”[],
};
for(i=0;i
我已经在这里找到了一个可能的解决方案,但不知道如何将其导入geoJSON:您可以通过wp\u localize\u脚本来实现(请注意,下面的代码是一个示例,需要修改才能在您的情况下工作) 然后在脚本中调用本地化对象
基本上,这里有三种解决方案。当然,哪一个和您相关很大程度上取决于您的用例
wp_enqueue_script( 'my_mapbox', get_template_directory_uri() . '/js/mabox.js' );
$dataToBePassed = array(
'home' => get_stylesheet_directory_uri(),
'pleaseWaitLabel' => __( 'Please wait...', 'default' )
);
wp_localize_script( 'my_mapbox', 'php_vars', $datatoBePassed );