HTML5 and the Geolocation API

HTML5 has a lot of pretty awesome features. One in particular that I have been playing around with lately is the geolocation API. With this API, you can detemine the geographical location of your users. This can be helpful for applications that might recommend local services or products based on a person’s location. Another use of this would be to display the user’s location on a map (we can do this by hooking into the Google Maps JavaScript API, which I will demonstrate).

In my experiments with HTML5 thus far, I have really loved discovering all of the JavaScript objects and methods that come ready out of the box. With the geolocation API, there is a built in navigator object that has a geolocation property, which has a getCurrentPosition method that will help you to extract location data. You can utilize this by writing something similar to the example below:

window.onload = findMyLocation;

function findMyLocation() {
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(displayLocation);
    } else { // geolocation is not supported
        alert("So very sorry, your browser does not support geolocation.");
    }
}

In this function, we first check that geolocation is supported. If it is, we call the getCurrentPosition method and pass it a callback function to run on success. The getCurrentPosition method will pass a position object to our callback function, displayLocation. Here’s what this function will look like:

function displayLocation(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    showMap(latitude, longitude);
}

As you can see, the position object that was passed from getCurrentPosition has a coords attribute. This attribute holds the latitude and longitude properties of the browser. With these values, we can now hook into the Google Maps JavaScript API and show the user’s location on a map. To access this, you’ll need to link to the API in the head of your html document:

<script src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>

Now that we have linked to the API, we are ready to start using it. First, you will need to create a new LatLng object for the Google Maps API to use. This represents the actual point on the map.

function showMap(latitude, longitude) {
    var myLatLng = new google.maps.LatLng(latitude, longitude);
}

We’re almost there. Before we can actually output the map, we need to set some options for it. For today, I’m only going to focus on the zoom level, center point, and the type of map, but you can get a full reference in the Google Maps API documentation.

var mapOptions = {
    zoom: 10,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

At last, we are ready to print the map on the page. You’ll need to make sure that you have an element to hold the map, and pass it to the Google Maps API (in the example below, it is simply a div with an id of “map”). This is also where you will pass the map options that you set up. We can do this like so:

var map = new google.maps.Map(document.getElementById('map'), mapOptions);

With this added, you should see a map like this:

Though we now have the map on the page, we are still missing an element: a map marker with an info window popup. These are usually integrated to provide additional information about a particular location. Without these, all we have is a map with a general location (in this case, a small portion of a metroplex). To add this, we’ll again use the Google Maps API:

var marker = new google.maps.Marker({ position: myLatLng, map: map, title: 'You are here.', clickable: true });

var infoWindow = new google.maps.InfoWindow({content: 'You are here.', position: myLatLng});

google.maps.event.addListener(marker, "click", function() {
    infoWindow.open(map);
});

Voila! We now have a beatiful map with a marker and even a fancy little popup with some text.

Putting it all together, here’s what our final code looks like:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>Get My Location</title>
    <style>
    #map {
        width: 600px;
        height: 300px;
        margin: 0 auto;
    }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
    <script>
        window.onload = findMyLocation;

        function findMyLocation() {
            if(navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(displayLocation);

            } else {
                alert("So very sorry, your browser does not support geolocation.");
            }
        }

        function displayLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;

            showMap(latitude, longitude);
        }

        function showMap(latitude, longitude) {
            var myLatLng = new google.maps.LatLng(latitude, longitude);

            var mapOptions = {
                zoom: 10,
                center: myLatLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map'), mapOptions);

            var marker = new google.maps.Marker({ position: myLatLng, map: map, title: 'You are here.', clickable: true });

            var infoWindow = new google.maps.InfoWindow({content: 'You are here.', position: myLatLng});

            google.maps.event.addListener(marker, "click", function() {
                infoWindow.open(map);
            });
        }
    </script>
</head>
<body>
    <div id="map"></div>
</body>
</html>

As you can see, with just a few lines of code we have built a miniature web application using the geolocation API. But this is just scratching the surface. There are more options and attributes than covered here and I hope that you will explore this in your own time and discover all that is has to offer.

No Comments

Comments are closed.

Recent Blog Posts in Local SEO, Web Development
In our opinion, Google My Business is the best upgrade since the birth of Google Plus. It allows a business to get into Google products such as Search, Maps and Google Plus...
I was really excited to have the opportunity to hear Bernadette Coleman, Advice Interactive CEO, recently present at the DFW Interactive Marketing, Internet SEO & SEM Meetup. Bernadette started in this industry in...
Intro Mobile menus have always been challenging, and over the last few years we’ve seen off-canvas menus, fixed navigation and everything in between. Today, we’ll be looking at the “Top primary menu”...