【问题标题】:Geocodezip code is not working with WordPress loopGeocodezip 代码不适用于 WordPress 循环
【发布时间】:2013-09-07 09:20:41
【问题描述】:

我想在每个 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 file 中使用时运行良好,由于我知识贫乏,我无法弄清楚为什么当 div 处于循环状态时它不工作

【问题讨论】:

    标签: php wordpress geocoding


    【解决方案1】:

    您应该使用wp_enqueue_scripts,但问题在于传递值&lt;?php echo $address;?&gt;。可以通过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 位于插件文件夹中。脚本的第一部分来自this 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() 本地化脚本。

    【讨论】:

    • 嘿!感谢您的帮助,但它生成的结果与我的代码生成的结果相同。并且与我之前的代码生成相同的问题/错误。我的意思是位置标记丢失并且缩放功能不起作用。
    • 您有实时链接吗?我测试了上面的代码并且工作正常。
    • 顺便说一句!我将“geocodezip.com/GMapsExampleV3b.html”这个 HTML 格式转换为 PHP 格式,我发现标记丢失并且缩放选项不再起作用。所以我想这是因为我使用的是 PHP 格式......请指导我。谢谢:)
    • 当我测试代码并放置一个 SO 地址时,这是what shows up。您的浏览器控制台是否会转储任何错误?
    • 您正在手动添加地址,而我正在从数据库中获取它。每个帖子都不同。这是一篇文章的链接“apotheekvinder.nl/?p=2828”请尝试缩放地图
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 2021-03-23
      • 1970-01-01
      相关资源
      最近更新 更多