News

Use the Google Maps API to build a mobile HTML app that provides directions

Use JavaScript to locate a device and plot directions to a pre-determined address with Google’s Maps API.

GoogleMaps

One of the most common reasons for a smartphone user to visit a company website is to find out how to get to the firm – to grab an address, or see the location of the office on a map. Normally this involves copying and pasting the address or postcode into whichever maps app is installed on that device, and then using that to either see the location or plot a route. We’re planning to allow users to do both those things directly from our mobile-optimised site!

When we combine modern smartphones’ GPS support with the Google Maps API, we can push the location of the user’s device to the web, and then pull back a set of clear directions that will navigate from the user’s current location to a prescribed end location, plotting the route on a map.
To keep this all simple, we’re going to be using the jQuery Mobile library which will allow us to access predefined helper methods – this makes it easy to find the device’s current location using JavaScript and show it on our page. Once we’ve got that working, we’ll make use of a jQuery plug-in to create the maps, and we’ll take advantage of some sample code to generate the final directions and show these on the device’s screen!

DOWNLOAD TUTORIAL CODE

Create the page

The first thing we’ll need to make our web app work is a simple HTML5 page with a few placeholders for displaying our location data. Later on we’ll replace these placeholders with a map and directions; but to get started, create a page with a < div> that has an id of “location”. Add an empty set of < script> tags in the < head> section.

 001 < div id="placeholder">
 002 < /div>

Download jQuery Mobile

To save time and make our map code easier, we’re going to be making use of the jQuery Mobile JavaScript library. You can download this from www.jquerymobile.com. Download the script now and insert it into your page using a < script> tag in your < head> section before the blank < script> tags you added in step 1.

 001 < /script>< script src="http://code.jquery.com/ jquery-1.7.1.min.js">< /script>
 002 < script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js">< /script>

Set up events

When the user first opens our web app, we’ll want to get the current location of their device and use it to plot their position on the map. The first thing we need to do is find out where they are. We can do this using the new HTML5 location. Add the code below to your empty script tags to grab the device’s location when the page is ready.

 001 $(document).ready(function(){
 002 navigator.geolocation.getCurrentPosition(handle_geolocation_query);
 003 });
 
 004 function handle_geolocation_query(position){
 005 // do something with the position information
 006 lat = parseInt(position.coords. latitude*10000,10)/10000;
 007 lon = parseInt(position.coords. longitude*10000,10)/10000; 
 008 alert(lat + " " + lon);
 }

Print it to screen

Now we’ve got an object that contains a pair of values – one for latitude, and one for longitude. We can show this data on screen by using a callback function that takes each value and appends it to the location < div> we set up as a placeholder in step 1. Add the code below to set this up.

001 $(document).ready(function(){
 002 navigator.geolocation.getCurrentPosition(handle_geolocation_query);
 003 });
 004 function handle_geolocation_query(position){
 005 // do something with the position information
 006 lat = parseInt(position.coords.latitude*10000,10)/10000;
 007 lon = parseInt(position.coords.longitude*10000,10)/10000;
 008 $("#placeholder").html("
Lat: 009"+lat+" Lon: "+lon+"
");
 }

Test!

You’re ready to conduct your first test of the script. When you open the page on your smartphone, you’ll see a permission dialog asking you to share your location with the website. Once you agree, your location should be shown on the page expressed as a pair of numbers with lots of decimal points.

Create a web app

Now that we’ve got our location being grabbed, and we’ve demonstrated the return values on our page, it’s time to start creating our map. To do this, we’re going to create a jQuery Mobile web app. This means we need to grab some sample code from the jQuery Mobile website to create a simple paged app, and paste it into oursection in place of the existing code. You can find the code for this on the cover disc.

Tabs galore

When the final app is completed, you’ll want the map and directions to be a part of a bigger mobile website. Create some tabs for this purpose now so you can add the rest of your pages and contents later. Add the code (as featured on the cover disc) into your page HTML to put this in place.

Integrate Google Maps

Our opening page will show a map that has the office location and/or route plotted on to it. To get started, we’ll need to integrate the Google Maps API by including the API JavaScript file. Add the code shown below to yoursection to include the Google Maps API ready for use.

001 < script type="text/javascript"
 002 src="http://maps.google.com/maps/api/
 003 js?sensor=true">< /script>

Create a map

The first thing we’ll need is a map to work with. Create a < div> with an id of “map” inside your first page section of code. Style this using CSS to make sure it fills the tab perfectly, regardless of the size of the screen we’re viewing the web app on. (see code download)


Initialise the map

Before we can do anything with our map, we need to call the Google Maps initialize code to create an instance of a map. Add the code below inside your existing callback JavaScript function to create a map inside our map < div>, and make it available to our script for further work.

001 $(document).ready(function() {
 002 $('#map').gmap({'center':
 003endlocation.center, 'zoom': endlocation. zoom, 'disableDefaultUI':true, 'callback':
 004function() {
 005 themap = this;
 006 });

Pan the map

We’re going to want to centre the map on the device’s current location. To do this, once we’ve successfully located the device we’ll want to use the panTo() method to re-centre the map on the user’s current position. We can do this by creating a reference to the map when we create it, and adding the code below to the handle_geolocation_query function.

001 function handle_geolocation_query(position){ 
 002 lat = parseInt(position.coords.
 003latitude*10000,10)/10000;
 lon = parseInt(position.coords.longitude*10000,10)/10000; 
 004 start = new google.maps.LatLng(lat, 
 lon);
 005 themap.get(‘map’).panTo(start);
 }

Test

Now that we’ve created a web app, initiated a map and panned to the correct location, it’s time to check that it’s all working before we move onto the final stages of development. Grab your phone and go for a walk! Check that as you refresh the page in your browser, your location is reflected on the map correctly.

Where’s the office?

Now we’ve got the device’s location, we need to tell our script where we’re going to end up! We’ll do this by creating a variable to store the location of the office, and later we’ll use this in the call to the directions API as the destination value. Add the code (from code download) to set this up, but use your own address!

The Directions API

Now we know both where we are, and where we want to get to – so we can start to build our directions request. This is quite simple if you refer to the Google Maps Directions API, which you can find documentation for by heading to developers.google.com/maps/documentation/directions.

Include the files

We’re going to make use of the jQuery UI Maps plug-in to make this all a bit easier for ourselves. Firstly, navigate to the Google Code page for this project at code.google.com/p/jquery-ui-map/ and download the plug-in. You can also see the example code we’re using at the same place! We’re going to need the basic maps script, extensions and services scripts.

Build your request

We’re finally ready to start building our directions request. Start off by creating a function that’s called when the #submit button is tapped. Inside this we’ll need a call to the displayDirections() method. This needs a few parameters passing in to make it work, but start by adding the following code.

001 $('#submit').click(function() {
 002 themap.displayDirections(
 003 return false;
 004 });
 005 }}); 

The start and finish

The first thing we need to pass into the directions request is an object containing all of our location parameters. We need to define the origin (the place we’re starting), destination (the place we want to end up) and travel mode (walking, driving or cycling etc). Update your code to look like that shown in the code download.

Define the directions

The Google Maps Directions API has a handy helper method that will automatically render out the returned directions for us. We don’t have to use this, but it saves a lot of manual data management, so let’s add the second element to our directions request by defining the container in which the directions should be shown:

001 $('#submit').click(function() {
 002 themap.displayDirections(
 003 { 'origin': start, 004'destination': destination, 'travelMode': 
 005google.maps.DirectionsTravelMode.DRIVING },
 006 { 'panel': document. getElementById('directions')}, 
 007 return false;
 008 });
 009 }}); 

Callback when complete

Finally, we need to show the directions panel once the directions have been grabbed and are available on the page, so add the code below to complete the request with a callback function that gets fired once the data has loaded. The function will show the directions < div> when it’s ready.

001 $('#submit').click(function() {
 002 themap.displayDirections(
 003 { 'origin': start, 004'destination': destination, 'travelMode': 
 005google.maps.DirectionsTravelMode.DRIVING},
 006 { 'panel': document. getElementById('directions')}, 007 function(response, status) {
 008 ( status === 'OK' ) ? 009$('#results').show() : $('#results').hide();
 010 });
 011 return false;
 012 });
 013 }}); 

Test!

It’s time to test out your completed code. If you’ve set your destination to be the same place you’re developing your code, you’ll need to take a walk to make sure you get a sense of the directions being returned, or update the address to a friend’s house for test purposes!

Update to use miles

One thing you’ll notice is that the directions are being quoted in metric rather than imperial measurements – kilometres instead of miles. We can
fix this by adding in an extra property to our directions request object. Update your code to look like the code below, and then retest it to make sure that it now uses miles instead.

001 $('#submit').click(function() {
 002 themap.displayDirections(
 003 { 'origin': start, 004'destination': destination, 'travelMode': 005google.maps.DirectionsTravelMode.DRIVING, 006'unitSystem':google.maps.UnitSystem.IMPERIAL }, 
 007 { 'panel': document.
 getElementById('directions')},
 008 function(response, status) { 009 ( status === 'OK' ) ? 
 010$('#results').show() : $('#results').hide();
 011 });
 012 return false;
 013 });

Next steps

We’ve only handled the maps and directions part of a mobile website in this tutorial, but we have set up pages ready for any other content – so you could now go on to add these extra pages. You could also allow the user to enter an address to get directions from, instead of plotting it using their device. The Google Maps Directions API has additional options, including waypoints, that you can investigate at the API reference site!

×