How To Setup and Implement Google Geolocation Services API

As our society becomes increasingly mobile, more web traffic is coming from mobile devices than any other platform. Consequently, it is more important than ever for your web site and web applications to be mobile friendly. 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 will discuss 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. Download demo files. 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 they click 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 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, they can generate the map with detailed directions. Thanks for learning how to embed a Google map in websites!

About Excelisys, Inc.: Founded in 2001, Excelisys (www.excelisys.com) is an FBA Platinum Partner and FileMaker Certified developer organization. Excelisys specializes in designing, developing, customizing, supporting, consulting, migrating, upgrading, fixing, and integrating of FileMaker Pro and FileMaker Go database solutions, MySQL, PHP, CodeIgniter, PostgreSQL, QuickBooks-FileMaker Pro Integration, Excel and MS Access to FileMaker Pro conversions/migrations, iPhone and iPad business solutions, and other various database frameworks and web technologies that automate your organization’s data solution needs for use on the web, mobile, and desktop platforms. Contact Excelisys today for a free estimate and consultation about your business software automation needs @ 866-592-9235.