カスタムWordpressフィールドをmapbox-gljsに渡して、マップ上にマーカーを作成するにはどうすればよいですか?

Nov 24 2020

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に渡して、マップ上にポイントを作成する方法は?

回答

JasperB Nov 24 2020 at 22:52

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

HendrikVlaanderen Nov 25 2020 at 06:14

基本的に、ここには3つの解決策があります。どちらがあなたに関連するかは、もちろんあなたのユースケースに大きく依存します!

  1. スクリプトをキューに入れるために使用する関数でカスタム投稿クエリを実行し、クエリからのデータを使用してwp_localize_scriptの変数をローカライズします(上記のJasper Bのソリューション:))

  2. スクリプトでphpをインライン化します。PHPコードは、インラインスクリプトと同じページにあります(ハッキーですが、テストは簡単です)。このようなもの(終了phpを修正):

    var data = <?php $ data? "> // TODOこのplsを修正してください!ここに書き込むことはできません。これがエンコードされている限り、データの配列が提供されます。console.logを実行して、あたりです。

  3. AjaxまたはWordpressRESTを使用してエンドポイントを作成し、JSファイルでデータをクエリして表示できます。AjaxGetリクエストを設定する方法の詳細は次のとおりです