Create a Google Maps Shortcode in WordPress

Google Maps is one of the most widely used services on the internet. In the first decade of the 21st century, it and its counterparts like Mapquest and Bing maps have completely revolutionized how people find destinations. Before these came on the scene, people used to call each other up and ask for directions and write things like “2nd right after the gas station” on *paper*. How did we live like this? 😀

While there are definitely a lot of great and easy-to-use WordPress plugins out there (maybe, too many in a saturated WordPress plugin market), I’m a fan of not installing a plugin for every little thing if it is something that could be accomplished by adding a relatively small amount of code to a page. In what follows, we’re going to create a Google Maps shortcode to quickly integrate Google Maps into your website without the need for a plugin. That way you can just drop it into your editor and be on your merry way.

First, in order to get Google Maps to work in your WordPress site you’re going to want to include the JavaScript for Google Maps. If you wanted to, you could place the following in the <head> section of your header.php file…

<script src="" type="text/javascript"></script>

However, if you are using the “proper way” that you’re supposed to load scripts in WordPress using the wp_enqueue_script function you could add the following to your functions.php file or a class if you are wrapping your WordPress functionality up in classes

function enqueue_custom_scripts() {
    wp_register_script('googlemaps', ('http://maps.google.com/maps/api/js?sensor=false'), false, null, true);
    wp_enqueue_script('googlemaps');
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');

Here we hook our script registration to the wp_enqueue_scripts action hook.

For our shortcode we’re going to want a bunch of different options that we can set in the attributes of our shortcode. As can be found in the Google Maps Developer Documentation, there are a bunch of different elements of a Google map that we can customize.

First, we’re going to want to have an “id” attribute to support multiple maps on the same page. This can be a simple string value that we’ll use for our element that we create (which will be a <div>). Obviously, we’re going to want to be able to center the map around a locale that we specify. Unfortunately with Google Maps we can’t just pass in an address in code. Rather than dealing with parsing all of the different formats of addresses all the world over, Google Maps instead uses a latitude/longitude system. Fortunately, there are good services out there like this one from iTouchMap where you can enter an address and you’ll get the correct latitude/longitude coordinates back.

We’re going to want to control the zoom (how far away or how close we’re zoomed in to our locale) and we’re also going to want to be able to customize the “type” of map to initialize: satellite, terrain, roadmap, or hybrid. Finally, we’ll also want to add a click handler so that when we click on the marker, we get a message box that pops-up with a message. Width and height are also good things to specify so we can set how large we want our map to be.

So with all of those options taken into account the finished shortcode is below…

/*** Google Map ***/
function googleMapShortcode($atts, $content = null) 
{
    extract(shortcode_atts(array("id" => 'myMap', "type" => 'road', "latitude" => '36.394757', "longitude" => '-105.600586', "zoom" => '9', "message" => 'This is the message...', "width" => '300', "height" => '300'), $atts));
    $mapType = '';
    if($type == "satellite") 
        $mapType = "SATELLITE";
    else if($type == "terrain")
        $mapType = "TERRAIN";  
    else if($type == "hybrid")
        $mapType = "HYBRID";
    else 
        $mapType = "ROADMAP";  
    echo '<!-- Google Map -->
        <script type="text/javascript">  
        $(document).ready(function() {
          function initializeGoogleMap() {
              var myLatlng = new google.maps.LatLng('.$latitude.','.$longitude.');
              var myOptions = {
                center: myLatlng,  
                zoom: '.$zoom.',
                mapTypeId: google.maps.MapTypeId.'.$mapType.'
              };
              var map = new google.maps.Map(document.getElementById("'.$id.'"), myOptions);
              var contentString = "'.$message.'";
              var infowindow = new google.maps.InfoWindow({
                  content: contentString
              });
              var marker = new google.maps.Marker({
                  position: myLatlng
              });
              google.maps.event.addListener(marker, "click", function() {
                  infowindow.open(map,marker);
              });
              marker.setMap(map);
          }
          initializeGoogleMap();
        });
        </script>';
        return '<div id="'.$id.'" style="width:'.$width.'px; height:'.$height.'px;" class="googleMap"></div>';
} 

We also have to make sure that we register the shortcode. Add the following immediately after the googleMapShortcode function…

add_shortcode('googlemap','googleMapShortcode');

Then to use the shortcode you just have to do the following…

[googlemap id="myMap" zoom="9" latitude="21.306944" longitude="-157.858333" message="We are here"]

If you wanted to use this code outside of the WordPress Loop, such as your sidebar.php or footer.php files, you could use the following….

echo do_shortcode(‘[googlemap id="anotherMap" zoom="9" latitude="21.306944" longitude="-157.858333" message="We are here"]‘);

Now we have an easy way of adding Google Maps to our WordPress website!

9bit Studios E-Books

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

9 Responses to Create a Google Maps Shortcode in WordPress

  1. Johnnydev

    September 24, 2013 at 4:43 am  
    Nice tutorial! I have one question. Is it possible to add a plugin shortcode inside google infowindow?

    • September 26, 2013 at 7:37 am  
      Hi there Johnny - I'm not sure if I know entirely what you mean. The "message" attribute in the shortcode handles what the InfoWindow shows in the documentation for Google Maps Could you perhaps clarify a bit further?
  2. Vincenzo

    February 5, 2014 at 3:56 pm  
    Hi and thank you for your tutorial. I think I'm missing somethingg here, because this is not working for me. Here are the steps I took to implement this: - I put this part of your example in my functions.php file
    function enqueue_custom_scripts() {
        wp_register_script('googlemaps', ('http://maps.google.com/maps/api/js?sensor=false'), false, null, true);
        wp_enqueue_script('googlemaps');
    }
    add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
    - then I also inserted the other part of the code snippet inside functions.php right after the previous one as follows:
    /*** Google Map ***/
    function googleMapShortcode($atts, $content = null)
    {
        extract(shortcode_atts(array("id" => 'myMap', "type" => 'road', "latitude" => '36.394757', "longitude" => '-105.600586', "zoom" => '9', "message" => 'This is the message...', "width" => '300', "height" => '300'), $atts));
        $mapType = '';
        if($type == "satellite")
            $mapType = "SATELLITE";
        else if($type == "terrain")
            $mapType = "TERRAIN"; 
        else if($type == "hybrid")
            $mapType = "HYBRID";
        else
            $mapType = "ROADMAP"; 
        echo '
            $(document).ready(function() {
              function initializeGoogleMap() {
                  var myLatlng = new google.maps.LatLng('.$latitude.','.$longitude.');
                  var myOptions = {
                    center: myLatlng, 
                    zoom: '.$zoom.',
                    mapTypeId: google.maps.MapTypeId.'.$mapType.'
                  };
                  var map = new google.maps.Map(document.getElementById("'.$id.'"), myOptions);
                  var contentString = "'.$message.'";
                  var infowindow = new google.maps.InfoWindow({
                      content: contentString
                  });
                  var marker = new google.maps.Marker({
                      position: myLatlng
                  });
                  google.maps.event.addListener(marker, "click", function() {
                      infowindow.open(map,marker);
                  });
                  marker.setMap(map);
              }
              initializeGoogleMap();
            });
            ';
            return '';
    }
    - The last thing I did is to use the shortcode inside a wordpress page, like this:
    [googlemap id="myMap" zoom="9" latitude="21.306944" longitude="-157.858333" message="We are here"]
    As you can guess, this didn't work for me. Can you point me in the right direction? Thank you again. Vincenzo

    • February 8, 2014 at 6:17 am  
      Hi there Vicenzo. You know what step is probably missing? You actually have to register the shortcode. so after the googleMapShortcode function add the following...
      add_shortcode('googlemap','googleMapShortcode'); 
      I unfortunately forgot to include it in the tutorial. I have added it in now.
  3. Vincenzo

    February 10, 2014 at 4:33 pm  
    I solved this problem the same night by reading Wordpress' official documentation about shortcodes, but thanks a lot for the answer. I'm curious about a thing: I'm displaying two maps in a single page and despite this my wordpress page is still loading faster compared to my previous solution (maps included as s); why is this solution faster than the one with s? Thanks again for the big help! ;)

    • February 11, 2014 at 7:52 am  
      Hey there Vincenzo -- Glad you figured it out. :) I can't say for sure why this would be loading faster as opposed to something else without really seeing the code of both. I mostly just try to follow some decent practices for efficiency and optimization.

  4. May 22, 2014 at 5:56 pm  
    Thanks for this. I also don't like using plugins for every little bit of functionality on my site, in fact I'm quite bored of searching for answers to WordPress problems and all the results say "plugin, plugin, plugin". How could we set up a map that has multiple markers for a network of users. Say you had a business site where you wanted to be able to show the locations of all your registered users. How could we do it so that when they sign up, a marker is added to the map to show their location? The map would be on one centrally located page. I'm guessing this tutorial here could be modified. Perhaps it would be possible to create custom profile fields that accept latitude and longitude coordinates then somehow this custom field is hooked into the map so that it knows to place a new marker at that location.

    • May 24, 2014 at 8:47 am  
      Hey there Ryan -- Yeah I think that's definitely possible, but like you said there would have to modifications made to both the PHP and the JavaScript. On the server side you'd probably want to loop through your registered users (and yeah they'd need custom user meta fields added to each user for latitude and longitude). You could put that functionality somewhere else in your code, separate from this maps piece. As you're looping through users, you'd read this meta info and you'd be creating an array of latitude and longitudes that you would then echo to the browser as a variable/string. Of course, you'd also have to modify the client-side script to handle an array of markers instead of a single one. You could still use the shortcode's latitude and longitude attributes to set the center of the map, but the actual markers would come from the array of markers instead of the shortcode's attributes. Here is an example showing multiple markers on one map. You'd have to modify the JavaScript that's being echoed out to sort of look like that.
  5. Rohan

    July 26, 2014 at 1:34 pm  
    Thanks bro... u saved my day and helped me to learn a lot.. CHEERS!!!

Leave a Reply