Give Your Customers Driving Directions With the Google Maps API

=>SOURCE<=

=>DOWNLOAD<=

Instead of just showing your business location on a Google Map, why not offer your users the opportunity to get driving directions on the same page? No need for them to open up a new browser window and find it themselves, we can do better than that!

Using the Google Maps API within your WordPress website is a relatively simple process and we’ll explore exactly how to do it in this tutorial.

What We’ll Be Doing in This Tutorial…

  1. First we’ll set up some custom options so that we can enter information about our map in the WordPress Admin panel.
  2. Then we’ll use shortcodes to output a map container, input fields and directions container
  3. Finally we’ll write some JavaScript to initiate the Google Map

Note: We’ll be writing a fair bit of JavaScript here, but don’t worry! This is a WordPress tutorial so feel free to gloss over the JavaScript parts🙂


Step 1 Create the Directory and Files

  1. Create a folder inside your theme called Map
  2. Inside this folder, create map.php
  3. Finally create map.js

Step 2 Include the map.php File

In your functions.php file (located in the root directory of your theme) – include the map.php file you created at the top.

  1. /* functions.php */
  2. include(‘map/map.php’);

Step 3 Register Settings

There are 3 things that we want to be able to edit from the Admin area.

  1. The Destination. We’re going to use Longitude and Latitude values to specify the precise location of your destination (more details to follow)
  2. The infoWindow content. This is the white bubble you often see on Google Maps – we want to be able to edit the text in the bubble!
  3. Initial Zoom Level of the map – how far the map is zoomed in when the user first loads the page.

In map.php, hook into admin_init to register our settings:

  1. function map_init() {
  2.     register_setting(‘general’, ‘map_config_address’);
  3.     register_setting(‘general’, ‘map_config_infobox’);
  4.     register_setting(‘general’, ‘map_config_zoom’);
  5. }
  6. add_action(‘admin_init’, ‘map_init’);

Now we can set up the heading text for our section in the options page and all of the inputs we need.

  1. function map_config_option_text() {
  2.     echo ‘<p>Set Options for the Map here:</p>’;
  3. }
  4. // Longitude, Latitude Values for the Destination
  5. function map_config_address() {
  6.     printf((‘<input type= »text » id= »map_config_address » name= »map_config_address » value= »%s » size= »50″/>’), get_option(‘map_config_address’));
  7. }
  8. // The text content for the InfoWindow Bubble
  9. function map_config_infobox() {
  10.     printf((‘<textarea name= »map_config_infobox » id= »map_config_infobox » cols= »30″ rows= »3″>%s</textarea>’), get_option(‘map_config_infobox’));
  11. }
  12. // The initial Zoom Level of the map.
  13. function map_config_zoom() {
  14.     printf((‘<input name= »map_config_zoom » id= »map_config_zoom » value= »%s » />’), get_option(‘map_config_zoom’));
  15. }

Finally we hook into admin_menu to display our settings in the WordPress Admin:

  1. function map_config_menu() {
  2.     add_settings_section(‘map_config’, ‘Map Configuration’, ‘map_config_option_text’, ‘general’);
  3.     add_settings_field(‘map_config_address’, ‘Address – Longitude and Latitude’, ‘map_config_address’, ‘general’, ‘map_config’);
  4.     add_settings_field(‘map_config_infobox’, ‘Map InfoWindow’, ‘map_config_infobox’, ‘general’, ‘map_config’);
  5.     add_settings_field(‘map_config_zoom’, ‘Map Zoom Level’, ‘map_config_zoom’, ‘general’, ‘map_config’);
  6. }
  7. add_action(‘admin_menu’, ‘map_config_menu’);

Go into your admin area, you should now see this:


Step 4 Enter Your Destination, infoWindow Text and Zoom Level

  1. Destination AddressThe Google Maps API actually accepts regular addresses such as ‘Newgate Lane, Mansfield, Nottinghamshire, UK’ – However, you’ll find that you will want to be more precise with your destination (for example, you’ll most likely want to point directly to your business and not just the street). You can use a Google Maps API V3 Sample to search for your destination. Drag the target around until you have pin-pointed your spot. When you’re happy, copy the Lat/Lng: value into the address field in the options – for example 27.52774434830308, 42.18752500000007 (just the numbers separated by the comma, no brackets or quotes!)
  2. InfoWindow TextMake this whatever you want. Your Business Name would be a good idea🙂
  3. Zoom LevelA good starting point is 10.

Click ‘Save Changes’ and when the page refreshes you can check that the info has been stored. It should look something like this now:


Step 5 Set Up the Shortcodes

When we are finished, we’ll have 3 elements: the Map, the Form, and the Directions – so in this tutorial I’ve decided to split them up into 3 separate shortcodes. This will allow us to change the order/placement of each item without having to modify any of our PHP code. For example, you may decide to have your directions above the map instead of below, or at the side, etc.

  1. Shortcode 1 : wpmap_mapHere we register and enqueue the Google Maps API JavasScript file as well as our own maps.js file.Next we use the $output variable to store our map-container div along with some custom data attributes. ( data-map-infowindow will store the content for the infowindow and data-map-zoom will represent the initial zoom level – both of these values are returned using WordPress’s get_optionfunction).

    Finally we return the generated HTML to be output:

    1. function wpmap_map() {
    2.     wp_register_script(‘google-maps’, ‘http://maps.google.com/maps/api/js?sensor=false&rsquo;);
    3.     wp_enqueue_script(‘google-maps’);
    4.     wp_register_script(‘wptuts-custom’, get_template_directory_uri() . ‘/map/map.js’,  »,  », true);
    5.     wp_enqueue_script(‘wptuts-custom’);
    6.     $output = sprintf(
    7.         ‘<div id= »map-container » data-map-infowindow= »%s » data-map-zoom= »%s »></div>’,
    8.         get_option(‘map_config_infobox’),
    9.         get_option(‘map_config_zoom’)
    10.     );
    11.     return $output;
    12. }
    13. add_shortcode(‘wpmap_map’, ‘wpmap_map’);
  2. Shortcode 2 : wpmap_directions_containerHere we simply return an empty div with an ID of dir-container. This will act as the container for the directions.
    1. function wpmap_directions() {
    2.     $output = ‘<div id= »dir-container » ></div>’;
    3.     return $output;
    4. }
    5. add_shortcode(‘wpmap_directions_container’, ‘wpmap_directions’);
  3. Shortcode 3 : wpmap_directions_inputThis generates the Markup needed for our form.This is also where we’ll set our final custom option – the destination Address. This time, we’ll use a hidden form field to hold the Latitude/Longitude value that we entered earlier in the Admin Panel.
    1. function wpmap_directions_input() {
    2.     $address_to = get_option(‘map_config_address’);
    3.     $output = ‘<section id= »directions » class= »widget »>
    4.                 <strong>For Driving Directions, Enter your Address below :</strong><br />
    5.                 <input id= »from-input » type= »text » value= » » size= »10″/>
    6.                 <select class= »hidden » onchange= » » id= »unit-input »>
    7.                     <option value= »imperial » selected= »selected »>Imperial</option>
    8.                     <option value= »metric »>Metric</option>
    9.                 </select>
    10.                 <input id= »getDirections » type= »button » value= »Get Directions » onclick= »WPmap.getDirections(); »/>
    11.                 <input id= »map-config-address » type= »hidden » value= »‘ . $address_to . ‘ »/>
    12.             </section>’;
    13.     return $output;
    14. }
    15. add_shortcode(‘wpmap_directions_input’, ‘wpmap_directions_input’);

Now we have the shortcodes set up, you can go ahead and type them into your Contact Us page (or any page you like).

If you preview the page now, all you’ll see is the form input fields. That’s because we haven’t written our JavaScript that will initialize the Map yet and the div for the directions is currently empty.

Note: Before we dive into the JavaScript, we just need to add this to our style.css:

  1. #map-container {
  2.     width: 100%;
  3.     height: 400px;
  4. }

Step 7 Writing JavaScript to Interact With Google Maps API

Now it’s time to make the magic happen! I’ll provide a quick run-down of what we’re going to do first, then we’ll dig straight into the code.

  1. First we’re going to create an object WMmap and assign properties to it (some of which we’ll be grabbing from the markup that we created in the shortcodes)
  2. Then we’ll add a few methods to handle the functionality of the map and directions.
  3. One of these methods, init, will be responsible for loading the map and also for setting some default values such as the infoWindow text, zoom level and initial marker position (all from WordPress options)
  4. Finally we’ll set an event listener to load our map when the page is ready.

Ready?

I’ll explain each part of the code step-by-step, but don’t worry if you get lost, we’ll put it all together at the end.

Set Properties

Let’s create our object and set some properties. Here we are simply querying the DOM to retrieve the HTML elements that contain the values we need. The property names we’re using should be very clear and self-explanatory (mapContainer is obviously the Map Container, etc :))

Here we also get a couple of objects from the API that we’ll use later when we deal with Directions.

  1. var WPmap = {
  2.     // HTML Elements we’ll use later!
  3.     mapContainer    : document.getElementById(‘map-container’),
  4.     dirContainer    : document.getElementById(‘dir-container’),
  5.     toInput         : document.getElementById(‘map-config-address’),
  6.     fromInput       : document.getElementById(‘from-input’),
  7.     unitInput       : document.getElementById(‘unit-input’),
  8.     // Google Maps API Objects
  9.     dirService      : new google.maps.DirectionsService(),
  10.     dirRenderer     : new google.maps.DirectionsRenderer(),
  11.     map             : null,
  12.     /* continues below */
  13. }

The Methods

These are also part of our WPmap object, if you are unsure how everything ties together, be sure to check out the bottom of this tutorial to see all of the code together.

showDirections()

This is called from within another method that we’ll see later, it basically controls the insertion of the directions into the page.

  1. /* within WPmap object */
  2. showDirections:function (dirResult, dirStatus) {
  3.     if (dirStatus != google.maps.DirectionsStatus.OK) {
  4.         alert(‘Directions failed: ‘ + dirStatus);
  5.         return;
  6.     }
  7.     // Show directions
  8.     WPmap.dirRenderer.setMap(WPmap.map);
  9.     WPmap.dirRenderer.setPanel(WPmap.dirContainer);
  10.     WPmap.dirRenderer.setDirections(dirResult);
  11. },

getStartLatLng()

This is called once from our init method. It will set the startLatLng property equal to agoogle.maps.LatLng object that we can use later. It requires that we provide it separate Latitude and Longitude values – how can we do this?

  1. In our shortcode we inserted a hidden form field that contains the Latitude & Longitude value that we set in the WordPress Admin. Then we retrieved the hidden form field and stored it in toInput. This means we can now access the value using WPmap.toInput.value
  2. However, the value we set in the form is just a string with a comma separating the numbers. To separate the values we can split the string up using .split(","). This will return an array containing the Latitude and Longitude as separate values.
  3. Now we can access each one by using the arrays index.
  1. /* within WPmap object */
  2. getStartLatLng: function () {
  3.     var n = WPmap.toInput.value.split(« , »);
  4.     WPmap.startLatLng = new google.maps.LatLng(n[0], n[1]);
  5. },

getSelectedUnitSystem()

Because we have allowed our users to select whether they would prefer directions in Metric or Imperial, we use this method to set DirectionsUnitSystem to either METRIC or IMPERIAL.

  1. /* within WPmap object */
  2. getSelectedUnitSystem:function () {
  3.     return WPmap.unitInput.options[WPmap.unitInput.selectedIndex].value == ‘metric’ ?
  4.         google.maps.DirectionsUnitSystem.METRIC :
  5.         google.maps.DirectionsUnitSystem.IMPERIAL;
  6. },

getDirections()

This is the method that is called when the user clicks the Get Directions button.

  1. First we get the address that the user entered and store it in the fromStr variable.
  2. Next we set up an options object – dirRequest. This will contain the options needed to provide the Driving Directions.
    1. origin – The address that the user entered.
    2. destination – The google.maps.LatLng object containing the Latitude and Longitude values of your destination.
    3. travelMode – Here we ensure we are only retrieving Driving Directions.
    4. unitSystem – Specify which unit of measurement to use based on user’s choice.
  3. Finally, we call WPmap.dirService.route – and pass two parameters to it:
    1. dirRequest – this is the object containing our options.
    2. WPmap.showDirections – the callback function that handles the placement of the directions into the page.
  1. /* within WPmap object */
  2. getDirections:function () {
  3.     var fromStr = WPmap.fromInput.value;
  4.     var dirRequest = {
  5.         origin      : fromStr,
  6.         destination : WPmap.startLatLng,
  7.         travelMode  : google.maps.DirectionsTravelMode.DRIVING,
  8.         unitSystem  : WPmap.getSelectedUnitSystem()
  9.     };
  10.     WPmap.dirService.route(dirRequest, WPmap.showDirections);
  11. },

init()

This is the method that is called when the page is loaded. It is responsible for :

  1. Initiating the map, centered on your address.
  2. Retrieving values that are needed to set the infoWindow text and the initial Zoom level.
  3. Setting a marker pin showing your address.
  4. Listening for when when a user clicks ‘Get Directions’ so that it can remove the initial Marker and infoWindow
  1. init:function () {
  2.     // get the infowindow text and zoom level
  3.     var infoWindowContent = WPmap.mapContainer.getAttribute(‘data-map-infowindow’);
  4.     var initialZoom       = WPmap.mapContainer.getAttribute(‘data-map-zoom’);
  5.     // call the method that sets WPmap.startLatLng
  6.     WPmap.getStartLatLng();
  7.     // setup the map.
  8.     WPmap.map = new google.maps.Map(WPmap.mapContainer, {
  9.         zoom      : parseInt(initialZoom),
  10.         center    : WPmap.startLatLng,
  11.         mapTypeId : google.maps.MapTypeId.ROADMAP
  12.     });
  13.     // setup the red marker pin
  14.     marker = new google.maps.Marker({
  15.         map       : WPmap.map,
  16.         position  : WPmap.startLatLng,
  17.         draggable : false
  18.     });
  19.     // set the infowindow content
  20.     infoWindow = new google.maps.InfoWindow({
  21.         content : infoWindowContent
  22.     });
  23.     infoWindow.open(WPmap.map, marker);
  24.     // listen for when Directions are requested
  25.     google.maps.event.addListener(WPmap.dirRenderer, ‘directions_changed’, function () {
  26.         infoWindow.close();         //close the initial infoWindow
  27.         marker.setVisible(false);   //remove the initial marker
  28.     });
  29. }//init
  30. ;// <– this is the end of the object.

** Optional **

If you want to display a nice message (like the one seen below) to your users after they have requested directions, just copy the code under the image into the event listener inside the init method.

Optional Thank you message:

  1. // Get the distance of the journey
  2. var distanceString = WPmap.dirRenderer.directions.routes[0].legs[0].distance.text;
  3. // set the content of the infoWindow before we open it again.
  4. infoWindow.setContent(‘Thanks!<br /> Looks like you\’re about <strong> ‘ + distanceString + ‘</strong> away from us. <br />Directions are just below the map’);
  5. // re-open the infoWindow
  6. infoWindow.open(WPmap.map, marker);
  7. setTimeout(function () {
  8.     infoWindow.close()
  9. }, 8000); //close it after 8 seconds.

Step 8 Add the Event Listener That Will Load the Map

Are you still with me? We’ve made it all the way to end now and all that’s left to do is call the WPmap.init()method when the page loads. Add this to the bottom of map.js

  1. google.maps.event.addDomListener(window, ‘load’, WPmap.init);

Putting All the JavaScript Together

We’ve covered a lot of ground here, so let’s see how it looks when it’s all put together.

  1. var WPmap = {
  2.     // HTML Elements we’ll use later!
  3.     mapContainer   : document.getElementById(‘map-container’),
  4.     dirContainer   : document.getElementById(‘dir-container’),
  5.     toInput        : document.getElementById(‘map-config-address’),
  6.     fromInput      : document.getElementById(‘from-input’),
  7.     unitInput      : document.getElementById(‘unit-input’),
  8.     startLatLng    : null,
  9.     // Google Maps API Objects
  10.     dirService     : new google.maps.DirectionsService(),
  11.     dirRenderer    : new google.maps.DirectionsRenderer(),
  12.     map:null,
  13.     showDirections:function (dirResult, dirStatus) {
  14.         if (dirStatus != google.maps.DirectionsStatus.OK) {
  15.             alert(‘Directions failed: ‘ + dirStatus);
  16.             return;
  17.         }
  18.         // Show directions
  19.         WPmap.dirRenderer.setMap(WPmap.map);
  20.         WPmap.dirRenderer.setPanel(WPmap.dirContainer);
  21.         WPmap.dirRenderer.setDirections(dirResult);
  22.     },
  23.     getStartLatLng:function () {
  24.         var n = WPmap.toInput.value.split(« , »);
  25.         WPmap.startLatLng = new google.maps.LatLng(n[0], n[1]);
  26.     },
  27.     getSelectedUnitSystem:function () {
  28.         return WPmap.unitInput.options[WPmap.unitInput.selectedIndex].value == ‘metric’ ?
  29.             google.maps.DirectionsUnitSystem.METRIC :
  30.             google.maps.DirectionsUnitSystem.IMPERIAL;
  31.     },
  32.     getDirections:function () {
  33.         var fromStr = WPmap.fromInput.value; //Get the postcode that was entered
  34.         var dirRequest = {
  35.             origin      : fromStr,
  36.             destination : WPmap.startLatLng,
  37.             travelMode  : google.maps.DirectionsTravelMode.DRIVING,
  38.             unitSystem  : WPmap.getSelectedUnitSystem()
  39.         };
  40.         WPmap.dirService.route(dirRequest, WPmap.showDirections);
  41.     },
  42.     init:function () {
  43.         // get the content
  44.         var infoWindowContent = WPmap.mapContainer.getAttribute(‘data-map-infowindow’);
  45.         var initialZoom       = WPmap.mapContainer.getAttribute(‘data-map-zoom’);
  46.         WPmap.getStartLatLng();
  47.         // setup the map.
  48.         WPmap.map = new google.maps.Map(
  49.             WPmap.mapContainer,
  50.             {
  51.                 zoom: parseInt(initialZoom),     //ensure it comes through as an Integer
  52.                 center: WPmap.startLatLng,
  53.                 mapTypeId: google.maps.MapTypeId.ROADMAP
  54.             }
  55.         );
  56.         // setup the red pin marker
  57.         marker = new google.maps.Marker({
  58.             map: WPmap.map,
  59.             position: WPmap.startLatLng,
  60.             draggable: false
  61.         });
  62.         // set the infowindow content
  63.         infoWindow = new google.maps.InfoWindow({
  64.             content:infoWindowContent
  65.         });
  66.         infoWindow.open(WPmap.map, marker);
  67.         // listen for when Directions are requested
  68.         google.maps.event.addListener(
  69.             WPmap.dirRenderer,
  70.             ‘directions_changed’,
  71.             function () {
  72.                 infoWindow.close();         //close the first infoWindow
  73.                 marker.setVisible(false);   //remove the first marker
  74.                 // setup strings to be used.
  75.                 var distanceString = WPmap.dirRenderer.directions.routes[0].legs[0].distance.text;
  76.                 // set the content of the infoWindow before we open it again.
  77.                 infoWindow.setContent(‘Thanks!<br /> Looks like you\’re about <strong> ‘ + distanceString + ‘</strong> away from us. <br />Directions are just below the map’);
  78.                 // re-open the infoWindow
  79.                 infoWindow.open(WPmap.map, marker);
  80.                 setTimeout(function () {
  81.                     infoWindow.close()
  82.                 }, 8000); //close it after 8 seconds.
  83.             }
  84.         );
  85.     }//init
  86. };
  87. google.maps.event.addDomListener(window, ‘load’, WPmap.init);

Tutorial Notes

  1. Be sure to research anything you don’t understand on Google’s Maps API Website
  2. When writing this tutorial, I was testing my code using the stock TwentyEleven WordPress Theme. Something was causing the arrow at the bottom of the InfoWindow on the map to display incorrectly. It’s because .entry-content img on line 857 has a max-width set. This screws up the way that Google renders the infoWindow. To fix it, enter this somewhere below it:
    1. #map-container img { max-width: none; }

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s