我做了類似的事情here。我的方法是使用WordPress wp_localize_script函數來生成參數,我認爲這將是您的最佳選擇。
我沒有時間現在拉出代碼,但如果您需要更多,我可以稍後再看。
編輯
好了,在這裏你去。這些都是基於上面的鏈接,所以它可能會有比你需要的更多的代碼,但它應該可以做到。
首先,我創建了一個名爲property
的自定義帖子類型來匹配您的代碼,並創建了幾個屬性,給出每個屬性的緯度和經度。
接下來,我創建了一個名爲so.maps.js
文件,有如下內容(bounds
代碼只是爲了確保在地圖上顯示我的所有標記;你可能不會需要它):
(function($) {
function initialise_map() {
var locations_str = php_args.locations.replace(/"/g, '"');
var locations = $.parseJSON(locations_str);
var latlng = new google.maps.LatLng(48.856667, 2.350833);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
addMarker(locations[i], map, bounds);
}
if (locations.length > 1) {
map.fitBounds(bounds);
}
}
function addMarker(location, map, bounds) {
var locationLatLng = new google.maps.LatLng(location.latitude,location.longitude);
bounds.extend(locationLatLng);
var marker = new google.maps.Marker({
position: locationLatLng,
map: map,
title:location.title
});
}
$(function() {
initialise_map();
});
})(jQuery);
的重要組成部分,是php_args
變量 - 這就是我前面提到的wp_localize_script
調用的內容。
然後,我創建了一個頁面,顯示地圖,填充我想傳遞給JavaScript中的數組,並與wp_localize_script
傳遞:
<?php
/*
Template Name: Test Page
*/
define('GOOGLE_MAPS_V3_API_KEY', 'xxxxx');
add_action('wp_enqueue_scripts', 'so_exhibitions_map_scripts');
function so_exhibitions_map_scripts() {
wp_register_script('googlemaps', 'http://maps.googleapis.com/maps/api/js?hl=en&key=' . GOOGLE_MAPS_V3_API_KEY . '&sensor=false', false, '3');
wp_enqueue_script('googlemaps');
wp_register_script('so.maps', get_bloginfo('stylesheet_directory') . "/js/so.maps.js", array('jquery', 'googlemaps'), false, false);
wp_enqueue_script('so.maps');
$locations = array();
$location_query = new WP_Query(array(
'post_type' => 'property',
'posts_per_page' => -1
));
while ($location_query->have_posts()) {
$location_query->the_post();
$locations[] = array(
'title' => get_the_title(),
'latitude' => get_post_meta(get_the_ID(), 'latitude', true),
'longitude' => get_post_meta(get_the_ID(), 'longitude', true),
'id' => get_the_ID()
);
}
wp_reset_postdata();
wp_localize_script('so.maps', 'php_args', array(
'locations' => json_encode($locations)
));
}
get_header();
?>
<div id="container">
<div id="content">
<div id="map_canvas"></div>
</div><!-- #content -->
</div><!-- #container -->
<?php
get_footer();
?>
最後,我確信地圖上是可見通過設置其大小在CSS:
#map_canvas {
width: 100%;
height: 452px;
}
希望有所幫助。我不是Google Maps API的專家,但是這對我來說確實有竅門。
這是太棒了,非常乾淨的顯示。不過,我不是Google Maps API的專家,如果可能的話,一定會欣賞更多的代碼。謝謝! – littlebizzy
我已經更新了我的答案;讓我知道如果有什麼不清楚。 – Hobo
非常感謝。一直試圖做這個工作,但沒有運氣。這是偶然的舊版Google Maps API嗎? 'var locations_str'似乎會使地圖崩潰! – littlebizzy