Getting Started with the GeoLocation API

geolocation-feature

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.


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.

  1. 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.
  2. Now create a HTML file called index.html and a JavaScript file called script.js. Save both of these files in the geolocation directory.
  3. 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.js file 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.

  1. Start by opening the script.js file in your favorite text editor.
  2. 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() {
    
    }
  3. You need to check if the user’s browser supports geolocation. You can do this by looking for a geolocation object on the browsers navigator object. Browsers that do not support geolocation will not have a geolocation object.
    // 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.

  4. 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 geolocation objects getCurrentPosition() 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. A Position object will be passed to this function, which can then be examined to retrieve the location data.

  5. Great, now you have the position object you can extract the latitude and longitude values. To do this you need to access the position objects, coords interface and then from there you can access the latitude and longitude properties. Copy these two lines within the function block in you getCurrentPosition() call.
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
  6. The last thing to do now is to add a call to the showMap() function, passing in the lat and lon variables 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.

  1. At the very bottom of your script.js file create a new function called showMap that has two parameters, lat and lon.
    // Show the user's position on a Google map.
    function showMap(lat, lon) {
    
    }
  2. First you need to create a LatLng object for the Google Maps API. This object is used to position the map later. Add the following lines to the showMap() function.
    // Create a LatLng object with the GPS coordinates.
    var myLatLng = new google.maps.LatLng(lat, lon);
  3. 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
    };
  4. 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 the mapOptions object that you created in the previous step.
    // Generate the Map
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  5. If you save the script.js file and open the index.html file 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 your showMap() function.
    // Add a Marker to the Map
    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: 'Found you!'
    });
  6. You’re done! Save your script.js file and open up index.html. You should now see a red marker on the map, as shown in the figure below.
Google map showing a user's location obtained using the geolocation API

The finished geolocation app, with red position marker.


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.

Further Reading and Links

Comments

Comments are closed.