-1

我想在每个 WordPress 帖子中显示地图。位置会有所不同,地址将从数据库中获取。此代码正在生成结果,但无法正常工作。

  1. 地图制作工具不见了。
  2. 缩放选项不起作用或我无法直观地看到它。

这个函数需要在body标签中提到initialize(),所以我将我的body标签定制为:

<body onload="initialize()">

这是我正在使用的脚本:

    var geocoder;
    var map;
    var address ="<?php echo $address;?>";
    function initialize() {
    geocoder = new google.maps.Geocoder();
    var myOptions = {
    zoom: 16,
    center: new google.maps.LatLng(-33, 151),
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    if (geocoder) {
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
      map.setCenter(results[0].geometry.location);

        var infowindow = new google.maps.InfoWindow(
            { content: '<b>'+address+'</b>',
              size: new google.maps.Size(150,50)
            });

        var marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map, 
            title:address
        }); 
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
        });

      } else {
        alert("No results found");
       }
     } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
     });
     }
     }

我正在使用在 WordPress 发布循环中显示结果的 Div:

<div id="map_canvas" style="width:470px; height:358px"></div>

此代码在HTML 文件中使用时运行良好,由于我知识贫乏,我无法弄清楚为什么当 div 处于循环中时它不工作

4

2 回答 2

0

您应该使用wp_enqueue_scripts,但问题是传递值<?php echo $address;?>。可以用 解决wp_localize_script

以下是简码的工作示例,用于[gmaps address="city, state, country"]您的内容。

<?php
/* Plugin Name: My Gmaps */

add_shortcode( 'gmaps', 'gmaps_so_18671818' );

function gmaps_so_18671818( $atts ) 
{
    $address = isset( $atts['address'] ) ? $atts['address'] : '275-291 Bedford Ave, Brooklyn, NY 11211, USA';
    wp_register_script( 
        'gmaps',
        'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false',
        array(),
        null,
        true
    );
    wp_enqueue_script( 
        'call-gmaps',
        plugin_dir_url( __FILE__ ) . '/call-gmaps.js',
        array( 'gmaps' ),
        null,
        true 
    );
    wp_localize_script( 
        'call-gmaps', 
        'my_vars',
        array( 'address' => $address ) 
    );
    return '<div id="map_canvas" style="width:470px; height:358px"></div>';
}

该文件call-gmaps.js位于插件文件夹中。脚本的第一部分来自这个 Answer,负责处理onload事件。地址正在内部传递my_vars.address

// https://stackoverflow.com/a/1236040/1287812
// Dean Edwards/Matthias Miller/John Resig
function init() {
    if (arguments.callee.done) return;
    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;
    // kill the timer
    if (_timer) clearInterval(_timer);
    // do stuff
    initialize();
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            init(); // call the onload handler
        }
    };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            init(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = init;



var geocoder;
var map;
var address = my_vars.address; // <---- PASSED BY wp_localize_script
function initialize() {
    geocoder = new google.maps.Geocoder();
    var myOptions = {
        zoom: 16,
        center: new google.maps.LatLng(-33, 151),
        mapTypeControl: true,
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
        navigationControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    if (geocoder) {
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                    map.setCenter(results[0].geometry.location);

                    var infowindow = new google.maps.InfoWindow(
                    { content: '<b>'+address+'</b>',
                        size: new google.maps.Size(150,50)
                    });

                    var marker = new google.maps.Marker({
                        position: results[0].geometry.location,
                        map: map, 
                        title:address
                    }); 
                    google.maps.event.addListener(marker, 'click', function() {
                        infowindow.open(map,marker);
                    });

                } else {
                    console.log("No results found");
                }
            } else {
                console.log("Geocode was not successful for the following reason: " + status);
            }
        });
    }
}

可以调整所有这些以使用自定义字段来存储地址并用于get_post_meta()本地化脚本。

于 2013-09-07T13:50:58.087 回答
0

你知道......这是我的浏览器缓存导致问题。我清除了缓存,它正在工作。

感谢您的帮助,我非常感谢您的努力,并为浪费您宝贵的时间而道歉。

于 2013-09-14T14:32:39.543 回答