Advertisement

Making Websites Location Aware With HTML5 Geolocation

by

Assumption can be a risky business in the world of UX, but some assumptions can enable you to deliver a more tailored user experience to your visitors. We're going to look at enhancing user experience by making your websites location aware.

User experience has sprung forward into the forefront of web design in the last ten years or so. As users we're constantly being asked to provide updated information about ourselves. Anything from Twitter asking us "What's happening?" to Facebook asking us what we 'like'. All of this allows these companies, amongst other things, to build up a pretty detailed and accurate profile of you so that they can provide you with a more personal user experience.

Around the same time that HTM5 was announced, another API was introduced to us from W3C. I'm pretty sure you may have heard of it; the Geolocation API. This allows your site to receive geographic positioning information using JavaScript.


How Does Geolocation Work?

Geolocation data can be accessed through various different sources. Traditionally on websites, it would be determined by a visitor's IP address. It would then hook up to a WHOIS service and retrieve the visitor's physical address from their whois information. Recently though, a more popular and accurate way to access this information has become common; using a device's built in GPS chip. These are found in most smart phones and tablets and are responsible for the rise in popularity of location aware services that we might use. Think of Foursquare or any other app that you might 'check in' to.


User Privacy

In the API specification released by the W3C it states:

User Agents must not send location information to Web sites without the express permission of the user.

Before a device or browser can access the geolocation data of a visitor, the visitor must first authorize it. This is how it appears in Google Chrome:

Now, more than ever, users are taking notice about what information websites store about them and your users will need to feel confident as to what you are using their data for. Advise them as to exactly why you need this information and point out how it will be useful to them in creating a better online experience.

When using a geolocation website or app it's good practice to control the amount of information that you share with other people. Most location sharing apps and services do offer some kind of privacy control, so make sure to utilize this and never share your personal address.


Uses for Geolocation

Once you have a location aware site or app, you are able to provide more accurate and appropriate content for your visitors. Let's take a look at how geolocation can come in handy.

Geomarketing

Geomarketing is a relatively new term and can be described as:

The integration of geographical intelligence into various aspects of marketing, including sales and distribution.

Although a new term, the actual principle of geo marketing has been around for a while. Facebook have been utilizing this approach for some time now. Facebook would gather location-based data (based on users' IP addresses) from this, then show adverts appropriate for that geographic region. Google and other search engines have also made use of this and include location based search results for their users.

Crowdsourcing

It's not just marketers who can benefit from geolocation services, but creative types have also leveraged it (probably without even realizing). People have used it to gain access to large numbers of people, all of whom are situated in the same area and have the same goal of "making something happen". This can range from flash mobs, to large scale dance routines, to creating community groups for people who share similar interests.

It has also been utilized in situations such as the Haiti earthquake in 2010, when large groups of ordinary people gathered together to raise aid all through the power of social networks and geo location.

Offers

Recently a large amount of "offer sites" have started to spring up everywhere. Most notably is Groupon which launched in November 2008. Groupon offers deal-of-the-day services to its users and each day the site has a predetermined amount of offers for each offer. Each item must interest enough users to sign up for that offer; on doing so they receive it, but only if it reaches the number of predetermined people.

This concept reduces the risk for retailers and allows them to sell in bulk, making the concept a winner all round. The power of Groupon lies within the tight integration that it has with its users location. By offering its users local offers and deals it has become one of the most popular coupon sites and has had its format replicated many times.


Practical Examples

Now you understand a little more about geolocation, let's take a look at some real world examples.

The Rocky Horror Show

The rocky horror website lets you get showtimes for the show at venues that are close by to you. Simply go onto the site and click "Find my location".

Flickr Places

Using the same technology, Flickr shows what others have been uploading to the website near to where you are.

Mapumental

Mapumanetal came around in 2006 when the Department for Transport in the UK contacted the startup to work with the information they held on public transport data. They describe what they do at Mapumental as "We create maps that help people make better decisions, quicker." It offers a variety of tools and services that offer ways to visualize real time travel data.


Implementing Geolocation

If you haven't previously implemented geolocation into any websites or apps then the good news is, it couldn't be simpler. In this tutorial I'm going to show how you can get a user's location on your website or web app.

The HTML Markup

I've designed this so that you can add it onto your own website quite easily. The aim is for the user to press a button which will then get their location, displaying it on the site with a little help from Google Maps API's.

We start with a wrapper to center the design. I've chosen to do this at 960px wide but you can opt to use whatever size suits your design. Within this 'wrapper' I have created a div which is where the map will sit once it has been generated. I have given this an ID of 'Map'.

Within the 'Map' div I then have a span that I've given a class called 'helper'. This will be a little helper guide that will instruct the user what they need to do. This may seem a little unnecessary but it's always good practice to help users when possible.

We then have a preloader image which I've given an ID of 'preloader'. If you're looking to find preloaders then you can check out preloaders.net.

This is what you should have so far:


<div class="wrapper">

<div id="map">
	<span class="helper">Click the button below to show your location on the map</span>
	<img id="preloader" src="images/257.gif">
</div>

</div><!--End Wrapper-->

After the 'map' div I use a simple anchor tag that will act as the button for the user to click. This has a class of (yup you guessed it) 'button'.

Once the user has clicked the button, not only do we want to display the map, but it also might come in useful to display the user's location, longitude and latitude. For this I've created a div with an ID of 'results' that then contains three spans each with a relevant class. For the markup that's it. This is what the whole markup should like:


<div class="wrapper">

	<div id="map">
		<span class="helper">Click the button below to show your location on the map</span>
		<img id="preloader" src="images/257.gif">
	</div>

	<a class="button" href="" title="">Find My Location</a>

	<div id="results">
		<span class="longitude"></span><br>
		<span class="lattitude"></span><br>
		<span class="location"></span>
	</div>
	
</div><!--End Wrapper-->

The CSS

The CSS is quite straightforward. Here it is in full:

@charset "utf-8";
html{
	background:#222222;
	font-family:helvetica, arial, sans-serif;
}
.wrapper{
	width:960px;
	margin: 0 auto;
	position:relative;
}
#map{
	position:relative;
	text-align: center;
	color: #363535;
	text-transform: uppercase;
	width: 425px;
	height: 350px;
	margin:0 auto;
	margin-top:20px;
	padding: 5px;
	border: 1px solid black;
	background: #474747;
	box-shadow: 0px 0px 3px 3px rgba(0, 0, 0, .3);
}
#map .helper{
	display: block;
	font-weight: bold;
	font-size: 12px;
	color: rgb(54, 54, 54);
	width: 180px;
	line-height: 135%;
	margin: 0 auto;
	margin-top: 140px;
}
#map #preloader{
	position: absolute;
	top: 141px;
	left: 190px;
	display:none;
}
#map iframe{
	border:1px solid black;
}
.button{
	padding:13px 40px;
	background-color:#00caa7;
	color:#00caa7;
	border-radius:3px;
	color:white;
	display:block;
	text-decoration:none;
	box-shadow: inset 0px 1px 0px rgba(255, 255, 255, 0.3);
	width:122px;
	margin:0 auto;
	margin-top:20px;
}
.button:hover{
	background-color:#00b495
}
#results{
	color: rgb(0, 180, 149);
	position: absolute;
	margin-top: 20px;
	text-align: center;
	line-height: 23px;
	width: 100%;
}

One thing to note is that the preloader is the only div element that is absolutely positioned. This is absolutely positioned in relation to the 'map' div. To achieve this just make sure that the 'map' div has its position set to relative. This will allow for the preloader to be positioned to its parent as opposed the whole document.

jQuery

Google offers a range of API's for its MAP services which are free up to certain usage limits. After that, charges will apply.

Luckily, both of the services we're going to use are completely free; in fact one of the techniques doesn't use the API at all, instead using the standard map embed iframe in which we will change some of the values that we get from the user's browser.

Firstly, within some <script> tags, or in a separate JavaScript file, let's define some variables for the HTML elements that we will be targeting through jQuery.

var button = jQuery('.button');
var preloader = jQuery('#preloader');
var longitudediv = jQuery('.longitude');
var lattitudediv = jQuery('.lattitude');
var locationdiv = jQuery('.location');

Once we've done that we must check that the browser supports the Geolocation API. We can test this with the following 'if' statement.

if (navigator.geolocation) {  	
	// Browser supports it, we're good to go!	  
	} else {  	
	alert('Sorry your browser doesn\'t support the Geolocation API');	 
	}

Once we have established browser support, we will then detect the button click within the part where it is commented 'Browser supports it, we're good to go'.

The button click event should look like this:

button.click(function(e) {
	e.preventDefault();
	preloader.show();
	navigator.geolocation.getCurrentPosition(exportPosition, errorPosition);
});

Once the button has been clicked it will show the preloader. The important part to look at here is the 2nd to last line containing 'navigator'. What this is effectively saying is: "get the users location and if successful send the location position to the 'exportPosition' function, otherwise send an error to the errorPosition function".

So let's jump in and create these functions. The error function is fairly straight forward:

function errorPosition() {  				
	alert('Sorry couldn\'t find your location');  		  		 
	pretext.show();  		
	}

In the above function you can see that the function will alert and error, then show the preloader again.

In the success function below which is called 'exportPosition' we get the latitude and longitude provided by the geolocation API and set these as variables with the same name.

Once we have these we can then use them within the iframe embed code from Google Maps. We can also use them within the spans which display the longitude and latitude to the user. Here's how it looks:

	function exportPosition(position) {

		// Get the geolocation properties and set them as variables
		latitude = position.coords.latitude;
		longitude  = position.coords.longitude;

		// Insert the google maps iframe and change the location using the variables returned from the API
		jQuery('#map').html('<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.uk/?ie=UTF8&amp;ll='+latitude+','+longitude+'&amp;spn=0.332359,0.617294&amp;t=m&amp;z=11&amp;output=embed"></iframe>');
		longitudediv.html('Longitude: '+longitude);
		lattitudediv.html('Latitude: '+latitude);
		
	}

The important part is the iframe url. Within the url I insert the variables '+latitude+' and '+longitude+'. Up close this looks like:


<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.uk/?ie=UTF8&amp;ll='+latitude+','+longitude+'&amp;spn=0.332359,0.617294&amp;t=m&amp;z=11&amp;output=embed"></iframe>

This will insert the MAP within the '#map' div and also reveal the longitude and latitude to the user. There's also one more thing that we would like to know; this being the name of the user's location. To do this we need to make a call to the Google Maps API through AJAX. We add this AJAX function within the 'exportPosition' function. This looks like:

//Make a call to the Google maps api to get the name of the location
	jQuery.ajax({
	  url: 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true',
	  type: 'POST',
	  dataType: 'json',
	  success: function(data) {
	  	//If Successful add the data to the 'location' div
	 locationdiv.html('Location: '+data.results[0].address_components[2].long_name);
	  },
	  error: function(xhr, textStatus, errorThrown) {
	  		 errorPosition();
	  }
	});

In the success response we take the name of the location received back from the AJAX call and add it to the '.location' span. If, for whatever reason, there is an error in that call, then it will run the 'errorPosition' function and alert the user that it couldn't find their location.

The Geolocation API works in all modern browsers. However some versions of Safari use CoreLocation to get geolocation data, which means that you must be connected to the internet using WIFI. If you are connected through ethernet or similar, then you may have problems gathering the location data.

It's also worth pointing out that these tutorial files need to be uploaded onto a live web server to work and won't work on localhost.


Conclusion

I hope now you have a greater understanding of the geolocation API, how it works and how you can implement it with very little effort. By using geolocation in creative and effective ways you should now be able to provide a better user experience for your users.

Have you implemented the geolocation API into any sites you've been working on to encourage a better user experience? Have you seen it used in a cool and creative way? Let us know in the comments below.

Advertisement