WordPress php 数组到 js 数组以在谷歌地图中使用


Wordpress php array to js array to use in google map

嗨,我想使用存储在php数组中的一些数据在谷歌地图API中使用它,以填充地图中的多个位置。

我使用循环来创建我的 php 数组。

<?php 
while ( $the_query->have_posts() ) : $the_query->the_post();?>
    $locations_data = array(get_the_title(), rwmb_meta( 'lat' ), rwmb_meta( 'lng' ), get_the_ID (), get_permalink());
    array_push($locations_array, $locations_data);
endwhile; 

如果我print_r($locations_array)我得到这个。

print_r($locations_array); // to see the contents

结果:

Array ( [0] => Array ( [0] => title 1 [1] => -54.8949292 [2] => -56.1682769 [3] => 3175 [4] => http://localhost/wordpress/custom_post/title1/ ) [1] => Array ( [0] => title 2 [1] => -54.8617426 [2] => -56.1998983 [3] => 3174 [4] => http://localhost/wordpress/custom_post/title2/ ) [2] => Array ( [0] => title 3 [1] => -54.8617426 [2] => -56.1998983 [3] => 3169 [4] => http://localhost/wordpress/custom_post/title3/ ) )

我想在谷歌地图 API 中使用这些数据。我创建此地图.js文件

jQuery('document').ready(function($){
        'use strict';
        // Google Maps
        function init() {
            // ***HERE I NEED TO PUT MY DATA***
            var locations = [
            ['title 1', -54.89942324, -56.13500564, "the_ID_of_title1","the permalink of title1"],
            ['title 2', -54.90618086, -56.17895096, "the_ID_of _title2","the permalink of title2"],
            ['title 3', -54.89379148, -56.1645314, "the_ID_of title3","the permalink of title3"],  
            ];
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 12,
                center: new google.maps.LatLng(-54.85492175, -56.16659134),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            var infowindow = new google.maps.InfoWindow();
            var marker, i;
            for (i = 0; i < locations.length; i++) {
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                    map: map,
                    clickable: true,
                    url:locations[i][4]
                });
                google.maps.event.addListener(marker, 'click', (function (marker, i) {
                    return function () {
                        infowindow.setContent(locations[i][0]);
                        infowindow.open(map, marker);
                        window.location.href = marker.url;
                    }
                })(marker, i));
            }
        }
        google.maps.event.addDomListener(window, 'load', init);
});

提前致谢

您可以使用序列化为 json。

var data  = JSON.parse('<?php echo(json_encode($locations_array));?>');