首页 > 解决方案 > 如何使用谷歌 api 标记自定义在 WordPress 中将数据从 PHP 传递到 JS

问题描述

在我的 WordPress 项目中,我使用 Google API 的 infowindow 方法,它允许我通过单击地图上的象形图来显示信息

我的 JS 函数:

async function initFeatures(map_id) {
                const contentString =
                // MY DATA
                const infowindow = new google.maps.InfoWindow({
                  content: contentString,
                });
                markers[map_id]["parking"] = new google.maps.Marker({
                    position: feature.position,
                    map: map[map_id],
                    icon: {
                        url: interparking_maps_vars[map_id].markerInterparking,
                        size: new google.maps.Size(24, 33),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(24, 33)
                    }
                });
                google.maps.event.addListener(markers[map_id]["parking"],"click", () => {
                  infowindow.open(map[map_id], markers[map_id]["parking"]);
                });
                bounds.extend(feature.position);
            });
            map[map_id].fitBounds(bounds);
            map[map_id].zoom = 18;
            resolve();
        }
    });
}

当然,如果我写硬数据,它工作得很好!

在我的一个 PHP 文件中,我在 HTML 中获取数据

<h3><?php echo $park_name; ?></h3>
<p><?php echo $park_address; ?><br><?php echo $park_zip." ".$park_city; ?></p>
<p><?php echo __("Nombre de place", "interparking_aeroparker_offers")." : ".$park_capacity; ?><br><?php echo __("Hauteur maximale", "interparking_aeroparker_offers")." : ".$park_size; ?></p>
    <div class="position-relative d-flex pop-up-group">
      <?php foreach($park_services as $service): ?>
        <?php 
          $img_url = isset($service['image_url']) ? $service['image_url'] : ""; // category/term image url 
        ?>
        <div class="position-relative mr-1">
          <img src="<?php echo $img_url ?>" alt="<?php echo $service['name'] ?>" class="icon_service" />
          <div class="pop-up"><?php echo $service['name']." ".$service['description'] ?></div>
        </div>
    <?php endforeach; ?>
</div>

我知道你可以使用wp_localize_script()它允许我将 PHP 注入 JS,也许是一样的:

wp_localize_script('googlemaps_api', "interparking_maps_vars", '{"'.$map_id.'":'.json_encode($vars).'}');

这将允许我发送一个包含所有停车场的对象表。

我的问题是如何在我的contentString变量中以 JS 发送我的 PHP 数据?

谢谢你的帮助

编辑(更新)

function interparking_maps_shortcode_parks($atts = [], $content = null)
{
    $a = shortcode_atts( array(
        'positions' => "",
        'width' => "100%",
        'height' => "100%",
        'center_lat' => 48.8606419,
        'center_lng' => 2.3516968
    ), $atts );
    // do something to $content
    $positions = $a["positions"] ? json_decode("[".$a["positions"]."]", true) : "";
    // var_dump($a,$positions);die;
    
    $mapsAPIkey = esc_attr(get_option( 'interparking_maps_api_key','' ));
    wp_enqueue_style( 'interparking_maps_style', plugins_url( 'css/interparking_maps.css', __FILE__ ), array(), '2.0', 'all');
    wp_enqueue_script('interparking_maps_integration',plugins_url( 'js/init.js', __FILE__ ), array(), '2.1', 'all');
    if(wp_script_is("googleplaces_api","enqueued")){
        wp_dequeue_script("googleplaces_api");
    }
    wp_enqueue_script('googlemaps_api',"https://maps.googleapis.com/maps/api/js?key=".$mapsAPIkey."&callback=initMap&libraries=distancematrix&libraries=directions&libraries=places&language=".get_bloginfo('language'));
    $map_id = "map".random_int(0,1000000);
    $vars = [
        "positions" => $positions,
        "markerInterparking" => plugins_url( "img/Marker_interparking.png", __FILE__ ),
        "markerDefault" => plugins_url( "img/Marker.png", __FILE__ ),
        "markerEvent" => plugins_url( "img/Marker_event.png", __FILE__ ),
        "type" => "parks",
        "center_lat" => $a["center_lat"], 
        "center_lng" => $a["center_lng"]
    ];
    // wp_localize_script('googlemaps_api', "interparking_maps_vars", '{"'.$map_id.'":'.json_encode($vars).'}');

    $content .= '
    <style>
        .parks_map {
            width: '.$a["width"].' !important;
            height: '.$a["height"].' !important;
        }
    </style>
    <div id="'.$map_id.'" class="map parks_map"></div>
    <script>
        document.addEventListener("interparking_initvars", function(e) {
            interparking_maps_vars = Object.assign(interparking_maps_vars, {"'.$map_id.'":'.json_encode($vars).'});
        });
    </script>';
    return $content;
}
add_shortcode('interparking_map_positions', 'interparking_maps_shortcode_parks');

标签: javascriptphpwordpressgoogle-api

解决方案


推荐阅读