How To Set Up and Implement Google Geolocation Services API

Did you know that monthly mobile data traffic is eXpected to hit 77 eXabytes by 2022? That’s a huge increase from 19.01 eXabytes per month in 2018. Ever consider what this means for your website and web app? It means they must be mobile friendly — if you want to stay relevant. Of course responsive design is an important first step in your mobile marketing strategy, but once that is accomplished, how can you enhance the usability of your site and make it even more mobile friendly? One way is by implementing Google’s geolocation services API.

This tutorial discusses how to use and implement the Google geolocation services API using the Google Maps Javascript API in conjunction with HTML5 geolocation API and the Gmap3 Jquery plugin to generate a map of a physical address and provide turn-by-turn directions and a map from the user’s location to the provided destination.

View demo

Continue reading to learn how to add a Google map to your website

1) The first thing we will do is display a map of the destination when the page loads.

The first thing we will do is load JQuery, the Gmap3 plugin, and the Google Maps API:

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/js/gmap3.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

Then we will use JQuery to load the map when the document is ready. We simply pass the address variables to the script and then load the map into a div with the id “gmap”.

<script>
$(document).ready(function() {
        var google_map_address = '1600 Pennsylvania Ave NW, Washington, DC, 20500';
        $(function(){
          $('#gmap-display').gmap3({
            marker:{
              address: google_map_address 
            },
            map:{
              options:{
                zoom: 14
              }
            }
          });
        });
    });
</script>

In this example we are simply statically hard-coding the address in the script; however, for dynamic applications, the address can be retrieved from a database and passed to the API script like so:

<script>
$(document).ready(function() {
        var google_map_address = '<?php echo $ADDRESS[0]->address_1 .', '.$ADDRESS[0]->address_2.', '.$ADDRESS[0]->city.', '.$ADDRESS[0]->state_abbr.', '.$ADDRESS[0]->zip; ?>';
        $(function(){
          $('#gmap-display').gmap3({
            marker:{
              address: google_map_address 
            },
            map:{
              options:{
                zoom: 14
              }
            }
          });
        });
});
</script>

google geolocation services api

2) That was easy enough, but if we want to generate turn-by-turn directions to this destination, we need to get the user’s starting point. To do this we will utilize the geolocation API in HTM5 to retrieve the user’s location as the starting point for the map when the user clicks the “directions” button.

First we need to check that the browser has this capability and provide error handling in the event that it does not.

function get_location() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(success, fail);
        } else {
            alert("Geolocation is not supported by this browser.");
        }
}

If the browser is capable, we will attempt to retrieve the user’s location. In order for this to take place, the user must first give their permission. Notice the permission dialog presented by the browser when the location request is initiated by the navigator.geolocation.getCurrentPosition method.

google geolocation services api

The method results in either success of failure and allows us to define call backs for either event. In the case of failure, we will provide graceful error handling to notify the user based on the error code returned by the method.

function fail(error) {
            switch(error.code) // Returns 0-3
            {
                    case 0:
                            // Unknown error alert error message
                            alert('Error: ' + error.message + '.');
                            break;

                    case 1:
                            // Permission denied alert error message
                            alert('Error: ' + error.message + '. Location services for your browser must be enable on your device to get directions from your current location.');
                            break;
                    case 2:
                            // Position unavailable alert error message
                            alert('Error: ' + error.message + '. Your current position is unavailable. Please try again later.');
                            break;
            }
}

If the method is successful, we will initiate the get_directions function defined below.

function success(position) {
        get_directions(position.coords.latitude + ',' + position.coords.longitude);
}

The get_directions function will take the starting position retrieved from the HTML5 object. Our destination address is retrieved from the database and the Gmap3 JQuery plugin will generate the map with turn-by-turn directions and display it in the same div used to display the original map.

function get_directions(start_position) {            
        
        $(function(){$("#gmap-display").gmap3({ 
          getroute:{
            options:{
                origin: start_position,
                destination: "1600 Pennsylvania Ave NW, Washington, DC, 20500",
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            },
            callback: function(results){
              if (!results) return;
              $(this).gmap3({
                map:{
                  options:{
                    zoom: 13,  
                    center: [-33.879, 151.235]
                  }
                },
                directionsrenderer:{
                  container: $(document.createElement("div")).addClass("googlemap").insertAfter($("#gmap-display")),
                  options:{
                    directions:results
                  } 
                }
              });
            }
          }
        });
     });
}

3) Finally, we need the markup to display the maps (using Bootstrap 3 styling):

<div class="container">
	<div class="row">
		<div class="col-md-6">
			<h4>Google Maps Javascript API Demo</h4>
			<h5>Using the Gmaps3 JQuery plugin and HTML5 Geolocation API</h5>
			<p>When the document initially loads a Google map is displayed with a marker placed at the White House.  Clicking the directions button results in a permission dialog from the browser to share the user's location via HTML5 geolocation services.  When permission is granted, a map from the user's location to the destination with turn-by-turn directions is displayed.</p>
		</div>
	</div>
	
	<div class="row">
		<div class="col-md-6">
			<h5>Location: 1600 Pennsylvania Ave NW, Washington, DC 20500</h5>
		</div>
	</div>

	<div class="row">
    	<div class="col-md-6">
        	<!-- GOOGLE MAP -->
        	<div class="gmap" id="gmap-display"></div>
    	</div>
                    
    	<div class="col-md-3">
        	<button id="directions" class="btn btn-primary" onclick="get_location()">Directions</button>
    	</div>
	</div>
</div>

google geolocation services api

Putting it all together:

<style>
	.gmap {
  		height: 300px;
	}
	.gmap img {
	  	max-width: none;
	}
</style>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="https://demos.excelisys.com/fred/gmaps/js/gmap3.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>




<script>

    function get_location() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(success, fail);
        } else {
            alert("Geolocation is not supported by this browser.");
        }
    }

    function success(position) {
        get_directions(position.coords.latitude + ',' + position.coords.longitude);
    }
    
    function fail(error) {
            switch(error.code) // Returns 0-3
            {
                    case 0:
                            // Unknown error alert error message
                            alert('Error: ' + error.message + '.');
                            break;

                    case 1:
                            // Permission denied alert error message
                            alert('Error: ' + error.message + '. Location services for your browser must be enable on your device to get directions from your current location.');
                            break;
                    case 2:
                            // Position unavailable alert error message
                            alert('Error: ' + error.message + '. Your current position is unavailable. Please try again later.');
                            break;
            }
    }



    function get_directions(start_position) {    
        
        $(function(){$("#gmap-display").gmap3({ 
          getroute:{
            options:{
                origin: start_position,
                destination: "1600 Pennsylvania Ave NW, Washington, DC, 20500",
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            },
            callback: function(results){
              if (!results) return;
              $(this).gmap3({
                map:{
                  options:{
                    zoom: 13,  
                    center: [-33.879, 151.235]
                  }
                },
                directionsrenderer:{
                  container: $(document.createElement("div")).addClass("googlemap").insertAfter($("#gmap-display")),
                  options:{
                    directions:results
                  } 
                }
              });
            }
          }
        });
        });
    }
    
    

    $(document).ready(function() {
        var google_map_address = '1600 Pennsylvania Ave NW, Washington, DC, 20500';
        $(function(){
          $('#gmap-display').gmap3({
            marker:{
              address: google_map_address 
            },
            map:{
              options:{
                zoom: 14
              }
            }
          });
        });
    });
</script>

<div class="container">
	<div class="row">
		<div class="col-md-6">
			<h4>Google Maps Javascript API Demo</h4>
			<h5>Using the Gmaps3 JQuery plugin and HTML5 Geolocation API</h5>
			<p>When the document initially loads a Google map is displayed with a marker placed at the White House.  Clicking the directions button results in a permission dialog from the browser to share the user's location via HTML5 geolocation services.  When permission is granted, a map from the user's location to the destination with turn-by-turn directions is displayed.</p>
		</div>
	</div>
	
	<div class="row">
		<div class="col-md-6">
			<h5>Location: 1600 Pennsylvania Ave NW, Washington, DC 20500</h5>
		</div>
	</div>

	<div class="row">
    	<div class="col-md-6">
        	<!-- GOOGLE MAP -->
        	<div class="gmap" id="gmap-display"></div>
    	</div>
                    
    	<div class="col-md-3">
        	<button id="directions" class="btn btn-primary" onclick="get_location()">Directions</button>
    	</div>
	</div>
</div>

 

Et voilà! You now have a map with turn-by-turn directions from the user’s location to the provided destination, thus increasing the usability of your application and enhancing your mobile marketing strategy. Best of all, this implementation of the Google geolocation services API is device independent. As long as the browser supports HTML5 (whether your user accesses your site from a mobile device, tablet, or desktop) it can generate the map with detailed directions. Thanks for learning how to embed a Google map in a website!

About Excelisys, Inc.: Founded in 2001, eXcelisys (www.excelisys.com) is an FBA Partner and FileMaker Certified developer organization. eXcelisys specializes in designing, developing, customizing, supporting, consulting, migrating, upgrading, fixing, and integrating of database solutions for Desktop, Mobile, and Web applications. Our core technology competencies are the Claris FileMaker desktop and web tools suite, MySQL and PostgreSQL for database frameworks, along with WordPress, PHP, CodeIgniter, Joomla, Drupal, Magento and WooCommerce for websites and web applications. Aside from providing eXcellent customer service, our goals are to use these technologies to intuitively automate your organization’s data solution needs seamlessly and flawlessly across the web, mobile, and desktop platforms. Contact eXcelisys anytime for a free estimate and consultation about making your business more efficient through intuitive and effective software automation. 866-592-9235