사용자 정의 Wordpress 필드를 mapbox-gl js로 전달하여지도에 마커를 만드는 방법은 무엇입니까?
Mapbox와 Wordpress를 사용하여 다른 지점을 표시하는지도를 만들려고합니다. Wordpress에서 사용자 지정 메타 필드에 저장된 좌표를 사용하여 사용자 지정 게시물 유형을 만들었습니다. 필드가 모두 설정되었지만 내 PHP 템플릿의 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를 통해 그렇게 할 수 있습니다 (아래 코드는 예제이며 귀하의 경우에 작동하도록 변경해야 함)
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 );
그런 다음 스크립트 호출에서 현지화 된 객체에 https://code.tutsplus.com/tutorials/how-to-pass-php-data-and-strings-to-javascript-in-wordpress--wp-34699
기본적으로 여기에는 세 가지 솔루션이 있습니다. 어느 것이 당신과 매우 관련이 있는지는 당신의 사용 사례에 달려 있습니다!
스크립트를 대기열에 추가하고 쿼리의 데이터로 wp_localize_script의 변수를 지역화하는 데 사용하는 함수에서 사용자 지정 게시물 쿼리를 실행합니다 (Jasper B 위의 솔루션 :))
스크립트로 PHP를 인라인하십시오. PHP 코드는 인라인 스크립트와 같은 페이지에 있습니다 (해 키지 만 테스트에는 빠릅니다). 다음과 같은 것 (닫는 PHP 수정) :
var data = <? php $ data? "> // TODO이 pls를 수정하세요! 여기에 쓸 수 없습니다. 인코딩 된 한 데이터 배열을 제공해야합니다. console.log를 사용하여 맞습니다.
Ajax 또는 Wordpress REST를 사용하여 엔드 포인트를 생성하고 JS 파일에서 데이터를 쿼리하고 표시 할 수 있습니다. 다음은 Ajax Get 요청을 설정하는 방법에 대한 추가 정보입니다.