The GeoLocation API is one of the most exciting new web technologies to surface in recent years. The API allows you to pinpoint a user’s location by taking advantage of a device’s location capabilities (such as a GPS receiver). You can also use the API with devices that don’t have GPS. In these cases the location will be determined using WiFi or the devices IP address. It is worth noting that this is significantly less accurate than using GPS.
In this tutorial you are going to learn how to use the GeoLocation API to build location aware web applications. You will be creating a mini web application that uses the GeoLocation API to pinpoint a user’s location and then display that location on a Google Map.
Note!
You will need to run a local development server on your computer for the GeoLocation API to work correctly. If you don’t already have a local development server installed you can get one at the links below.
- Mac – http://www.apachefriends.org/en/xampp-macosx.html
- Linux - http://www.apachefriends.org/en/xampp-linux.html
- Windows – http://www.apachefriends.org/en/xampp-windows.html
Lets Get Started
First off, you need to setup a couple of HTML and JavaScript files that will hold the code for your mini web application.
- Create a new directory for your application called
geolocation. Make sure that this is created in a place that is accessible by your local development server. - Now create a HTML file called
index.htmland a JavaScript file calledscript.js. Save both of these files in thegeolocationdirectory. - Open the
index.htmlfile in your favorite text editor and add the following HTML markup to it.<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>GeoLocation</title> <style> html, body, #map { margin: 0; padding: 0; height: 100%; } </style> </head> <body> <div id="map"></div> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> <script src="script.js"></script> </body> </html>This code sets up the main web page that will display your mini web application. You have included two JavaScript files. The first loads a JavaScript library for the Google Maps API (you will be using this later on), and the second loads the
script.jsfile that you created earlier. You have also added a<div>element that will contain the map and some basic CSS code that will style this<div>so that it takes up the whole browser window.
Using the GeoLocation API
Now that you have got your HTML file setup and some basic styling sorted it’s time to start writing the JavaScript code that will pinpoint the user’s location.
- Start by opening the
script.jsfile in your favorite text editor. - Now add the following code to the top of the file. Everything that you place between the curly braces will be executed when the page loads.
window.onload = function() { } - You need to check if the user’s browser supports geolocation. You can do this by looking for a
geolocationobject on the browsersnavigatorobject. Browsers that do not support geolocation will not have ageolocationobject.// Check to see if the browser supports the GeoLocation API. if (navigator.geolocation) { } else { // Print out a message to the user. document.write('Your browser does not support GeoLocation'); }In the else statement you have added a message that will be displayed to the user if the browser does not support geolocation.
- Now that you know whether the user’s browser supports geolocation you can write the code that will request the devices location. You do this using the
geolocationobjectsgetCurrentPosition()function. Add the following code to the if block in your if/else statement.// Get the location navigator.geolocation.getCurrentPosition(function(position) { });The
getCurrentPosition()function should itself contain a function. APositionobject will be passed to this function, which can then be examined to retrieve the location data. - Great, now you have the
positionobject you can extract the latitude and longitude values. To do this you need to access thepositionobjects,coordsinterface and then from there you can access thelatitudeandlongitudeproperties. Copy these two lines within the function block in yougetCurrentPosition()call.var lat = position.coords.latitude; var lon = position.coords.longitude;
- The last thing to do now is to add a call to the
showMap()function, passing in thelatandlonvariables as parameters. Add this line below the code you added in step 5.// Show the map showMap(lat, lon);
You will write the
showMap()function in the next section.
Displaying the User’s Location on a Map
Now that you have successfully obtained the user’s location lets display it on a map. To do this you will be using the Google Maps JavaScript API.
- At the very bottom of your
script.jsfile create a new function calledshowMapthat has two parameters,latandlon.// Show the user's position on a Google map. function showMap(lat, lon) { } - First you need to create a
LatLngobject for the Google Maps API. This object is used to position the map later. Add the following lines to theshowMap()function.// Create a LatLng object with the GPS coordinates. var myLatLng = new google.maps.LatLng(lat, lon);
- Now you need to setup some map options. These options define the zoom level, center point and map type. You can see a full list of map options and possible values in the Google Maps API docs. Add this code to your
showMap()function.// Create the Map Options var mapOptions = { zoom: 8, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP }; - At this stage we are ready to generate the map. To do this you need to retrieve the
<div>element that you created in your HTML markup and pass it to the Google Maps API. You also pass in themapOptionsobject that you created in the previous step.// Generate the Map var map = new google.maps.Map(document.getElementById('map'), mapOptions); - If you save the
script.jsfile and open theindex.htmlfile in your web browser you should now see a map that is centered on your location. The last thing to do is to add a marker to make the user’s location clearer. Add the following code to the bottom of yourshowMap()function.// Add a Marker to the Map var marker = new google.maps.Marker({ position: myLatLng, map: map, title: 'Found you!' }); - You’re done! Save your
script.jsfile and open upindex.html. You should now see a red marker on the map, as shown in the figure below.
Having Problems?
You can find all of the code for this tutorial on GitHub.
In closing…
In this tutorial you have used the GeoLocation and Google Maps APIs to create your very own mini web application. The GeoLocation API is one of my favorite new front-end web technologies. It is incredibly useful for building location aware web applications and for enhancing the functionality of existing webistes.
Are you using the GeoLocation API in any of your own projects? Let us know in the comments below.




Comments