-1

I want to show map in each WordPress post. Location will be vary, address will get fetched from database. This code is generating the result, but not working properly.

  1. Map Maker is missing.
  2. Zoom option is not working or I can't see it visually.

This function need initialize() mentioned in body tag so I have customized my body tag as:

<body onload="initialize()">

Here is the script I am using:

    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);
    }
     });
     }
     }

I am using Div which show result in WordPress post loop:

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

This code is working perfect while used in HTML file, because of my poor knowledge I am unable to figure out why it is not working when div is in loop

j0k
  • 22,600
  • 28
  • 79
  • 90
Nizam Kazi
  • 1,900
  • 1
  • 20
  • 26

2 Answers2

0

You should use wp_enqueue_scripts, but the problem is passing the value <?php echo $address;?>. It can be solved with wp_localize_script.

The following is a working example of shortcode, used as [gmaps address="city, state, country"] inside your content.

<?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>';
}

The file call-gmaps.js is located in the plugin folder. The first part of the script is from this Answer, and takes care of the onload event. The address is being passed inside 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);
            }
        });
    }
}

It is possible to adapt all this to work with a Custom Field to store the address and use get_post_meta() to localize the script.

Community
  • 1
  • 1
brasofilo
  • 25,496
  • 15
  • 91
  • 179
  • Hey! Thanks for the help, but it is generating same result as my code is generating. And same issue/error as my previous code is generating. I mean location marker is missing and Zoom functionality is not working. – Nizam Kazi Sep 13 '13 at 13:57
  • Do you have a live link? I tested the code above and worked ok. – brasofilo Sep 13 '13 at 13:59
  • BTW! I converted "http://www.geocodezip.com/GMapsExampleV3b.html" this HTML format into PHP format and I found that Marker is missing and Zoom option is no more working. So I guess it is because of PHP format I am using... please guide me on that. Thanks :) – Nizam Kazi Sep 13 '13 at 14:04
  • When I test the code and put a SO address this is [what shows up](http://cl.ly/image/2K3A1X0a0Y1W). Does your browser console dumps any error? – brasofilo Sep 13 '13 at 14:07
  • You are adding address manually, while I am fetching it from database. Which is different for each post. here is a link of one post "http://apotheekvinder.nl/?p=2828" try zooming map please – Nizam Kazi Sep 13 '13 at 14:18
  • I am sorry Brasofilo, but I have to switch site to maintenance mode right now! any help will be surely appreciated. Thanks for what so ever you did! – Nizam Kazi Sep 13 '13 at 14:38
0

You know... it was my browser cache which was causing problem. I cleared cache and it is working.

Thanks for the help I really appreciate your efforts and apologize for wasting your valuable time.

Nizam Kazi
  • 1,900
  • 1
  • 20
  • 26