How to Add Google Map Driving Directions in your Website ?

H

You might have come across a situation where you needed to insert business address in your company’s about page and felt that embedding a Google Maps driving directions would make it look better but you don’t know how you can do this. Always, there is a naive way of taking a screenshot and inserting in the web page but because you are reading this post on a tech blog, I assume that you are looking for a real solution.

There are many different ways to embed Google driving directions, Following are some options

  1. Fixed Destination
  2. Fixed Destination address and User provided source address
  3. Fixed Destination address and Dynamic Source Address Determination
  4. User provided Destination Address and User provided Source Address
  5. User provided Destination Address and Dynamic Source Address Determination

I cannot think of any other ways but there could be some other way that you might have in your mind. All these ways can be implemented in many different ways as pointed out earlier. Let us take a look at the options that we have

1) Embed Code from Google Maps

Google directly provides you with the embed code once you have loaded the map in Google Maps. But the disadvantage with this method is that you do not have neither the dynamic source or dynamic destination. If you do not need these dynamic determination of addresses, this is the way for you. All you have to do is load up the map in http://www.google.com/maps and provide the source and destination. This will load the map that you want and once it is loaded click on that little gear icon below to open up the settings menu. Here you find the “Share or embed map” option. In case if that button below is not available, you will find expand icon just above the source address which when clicked opens up the side panel where you have the same embed option.

Google Map Embed

Map below is embedded using this technique.

 

2) Google Map API

Google has the Embed API just for this, you can read more about this API @ https://developers.google.com/maps/documentation/embed/ . Although this is a simple API to use, you need to register your application to get the API key. Following is the syntax that you have to use to embed a map.

<iframe width="600" height="450" frameborder="0" style="border:0"
src="https://www.google.com/maps/embed/v1/directions?origin=...&destination=...&key="></iframe>

By looking at the pattern above we can notice that it is form data with origin, destination and key parameters. Hence we can develop our own form and submit the result to an iFrame to get the directions. I have written a sample HTML page to do this you can clone it from Google Map Directions GitHub.

<!doctype html>
<html lang="en">
   <head>
        <title>jQuery mobile with Google maps</title>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
        <script type="text/javascript">
        function setiFrameSource(){
            var iFrame = document.getElementById("iFrame");
            var Url = "https://www.google.com/maps/embed/v1/directions?";
            var origin = "origin=".concat(document.getElementById("origin").value).concat("&");
            var destination = "destination=".concat(document.getElementById("destination").value).concat("&");
            var key = "key=".concat(document.getElementById("key").value);
            Url = Url.concat( origin, destination, key );
            iFrame.src= Url;
        }
        function initialize() {
          // Create the autocomplete object, restricting the search
          // to geographical location types.
          origin = new google.maps.places.Autocomplete(
              /** @type {HTMLInputElement} */(document.getElementById('origin')),
              { types: ['geocode'] });
          destination = new google.maps.places.Autocomplete(
              /** @type {HTMLInputElement} */(document.getElementById('destination')),
              { types: ['geocode'] });
          // When the user selects an address from the dropdown,
          // populate the address fields in the form.
          google.maps.event.addListener(origin, 'place_changed', function() {
            fillInAddress();
          });
          google.maps.event.addListener(destination, 'place_changed', function() {
            fillInAddress();
          });
        }
        // [START region_geolocation]
        // Bias the autocomplete object to the user's geographical location,
        // as supplied by the browser's 'navigator.geolocation' object.
        function geolocate() {
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
              var geolocation = new google.maps.LatLng(
                  position.coords.latitude, position.coords.longitude);
              var circle = new google.maps.Circle({
                center: geolocation,
                radius: position.coords.accuracy
              });
              autocomplete.setBounds(circle.getBounds());
            });
          }
        }
</script>
    </head>
    <body onload="initialize()">
        <form method="get" target="iFrame">
        <input id="origin" style="width:82%;" placeholder="Put Origin here" name="origin" type="text" onFocus="geolocate()"/>
        <input id="destination" style="width:82%;" placeholder="Put Origin here" name="destination" type="text" onFocus="geolocate()"/>
        <input id="key" type="hidden" name="key" value="AIzaSyD4iE2xVSpkLLOXoyqT-RuPwURN3ddScAI">
        <input style="width:8%;" type="button" value="Go" onclick="setiFrameSource();"/>
        </form>
        <iframe id="iFrame" name="iFrame" src="https://www.google.com/maps/embed/v1/directions?origin=Hyderabad&destination=JNTU Busstop&key=AIzaSyD4iE2xVSpkLLOXoyqT-RuPwURN3ddScAI" style="height:500px;width:500px" ></iframe>


    </body>
</html>

This is just an example of what  you can do with Google Maps API, you can refer to the documentation to know more about it. While writing this post I have come across a stack overflow discussion page which was useful, you might want to see.

3) GMAPS jQuery Javascript

Generally the above methods should be able to do what you wanted to achieve but in case if you are a web-designer and looking through jQuery based maps, GMaps is one such library for embedding maps in a webpage. You can go through the library at Github for more information. It is very easy to setup and you can read through the documentation to know more about it. Following code is a function call to gMap with different parameters.

$('#map_controls').gMap(
{
     latitude: -2.206,
     longitude: -79.897,
     maptype: 'ROADMAP',
     zoom: 8,
     controls: {
         panControl: true,
         zoomControl: false,
         mapTypeControl: true,
         scaleControl: false,
         streetViewControl: false,
         overviewMapControl: false
     }
});

 4) Old Google Maps

In our previous example of Google Maps, we have seen that the new parameters are origin and destination but previous maps used to have these parameters as “saddr” meaning source address and “daddr” meaning destination address. Following example of HTML code may be helpful for you to get the directions. Note that this has been implemented in a HTML page and you might want to use it an iFrame to embed in a particular page.

<!doctype html>
<html lang="en">
   <head>
        <title>Google Map Directions</title>
</head>
<body>
<form action="http://maps.google.com/maps" method="get">
Enter your starting address:
<input type="text" name="saddr" />
<input type="text" name="daddr"/>
<input type="submit" value="Go" />
</form>
</body>
</html>

 

As you can see there are many possibilities for a simple requirement of embedding a map into a web page. I hope that above examples are useful for you to provide a starting point for your work. Thanks for reading, good day.

About the author

pavankumar.p1990

1 comment