Geolocation in web browsers to find location & Google Maps examples

More and more services around us focus on where we physically are located at the moment, and how we can be assisted in the best fashion depending on that. Today I’d like to introduce the geolocation possibilities we developers have, and also play around a little with Google maps.

Introducing geolocation

Geolocation, i.e. finding out where someone is located, is extremely simple for a web developer. This is the code to accomplish that:

	// Check for geolocation support
	if (navigator.geolocation) {
		// Use method getCurrentPosition to get coordinates
		navigator.geolocation.getCurrentPosition(function (position) {
			// Access them accordingly
			alert(position.coords.latitude + ", " + position.coords.longitude);
		});
	}

That’s it! Pretty simple, right?

What happens when you utilize this code is that the web browser will show a notification to the end user, ask them if they want to share their location or not, and offer them an option to remember that choice for future preference. In Firefox, it looks like this:

A picture of the geolocation notification in Firefox

Web browser support

  • Firefox 3.5+
  • Firefox on Mobile (aka Fennec)
  • Safari on the iPhone (not the desktop)
  • Android web browser

It should also be noted that at the time of writing, a beta of Google Chrome supports it, and I feel certain the other web browser vendors will shortly follow suit.

Not a part of HTML5

Even though it is bundled with other features, let’s just clear out a common misunderstanding: geolocation is not a part of the HTML5 specification, but rather comes from the Geolocation API Specification. Not that it really matters, though. Geolocation is new, cool and very useful, and if you want to bundle it with HTML5 when you talk about (just like most people did using the word AJAX to sell any sort of JavaScripting), be my guest.

Using geolocation and showing current location

A picture of using geolocation to find out the current location of the user and display it with Google Maps

So, naturally, with this newfound knowledge, we want to utilize it with Google Maps and offer users an option to see where they are located on a map. The code to do this (with fallbacks if the user declines, or has a web browser that doesn’t support geolocation) looks like this:

HTML

	<div id="map"></div>

JavaScript

	/*
		A Google Maps API key can be attained at 
		http://code.google.com/apis/maps/signup.html
	*/	
	<script src="http://www.google.com/jsapi?key=[Your Google Maps API key]"></script>
	<script>
		(function () {
			google.load("maps", "2");
			google.setOnLoadCallback(function () {
				// Create map
				var map = new google.maps.Map2(document.getElementById("map")),
					markerText = "<h2>You are here</h2><p>Nice with geolocation, ain't it?</p>",
					markOutLocation = function (lat, long) {
						var latLong = new google.maps.LatLng(lat, long),
							marker = new google.maps.Marker(latLong);
						map.setCenter(latLong, 13);
						map.addOverlay(marker);
						marker.openInfoWindow(markerText);
						google.maps.Event.addListener(marker, "click", function () {
							marker.openInfoWindow(markerText);
						});
					};
					map.setUIToDefault();
					
				// Check for geolocation support	
				if (navigator.geolocation) {
					// Get current position
					navigator.geolocation.getCurrentPosition(function (position) {
							// Success!
							markOutLocation(position.coords.latitude, position.coords.longitude);
						}, 
						function () {
							// Gelocation fallback: Defaults to Stockholm, Sweden
							markerText = "<p>Please accept geolocation for me to be able to find you. <br>I've put you in Stockholm for now.</p>";
							markOutLocation(59.3325215, 18.0643818);
						}
					);
				}
				else {
					// No geolocation fallback: Defaults to Eeaster Island, Chile
					markerText = "<p>No location support. Try Easter Island for now.</p>";
					markOutLocation(-27.121192, -109.366424);
				}
			});	
		})();
	</script>

You can see this example in action an try it out at https://robertnyman.com/html5/geolocation/current-location.html.

Using geolocation and showing travel route and directions

Google are working on Google Maps JavaScript API V3, which is available as a Labs project. The cool thing about this, apart from very good performance, is the option to show routes between two points, and also displaying a list of directions.

A picture of using geolocation to find out the current location of the user and display directions to another location using with Google Maps

They way to do that looks like this in code (like above examples, contains fallbacks):

HTML

	<div id="map"></div>
	<div id="map-directions"></div>
	<script type="text/javascript" src="http://maps.google.se/maps/api/js?sensor=false"></script>
	<script>
		(function () {
			var directionsService = new google.maps.DirectionsService(),
				directionsDisplay = new google.maps.DirectionsRenderer(),
				createMap = function (start) {
					var travel = {
							origin : (start.coords)? new google.maps.LatLng(start.lat, start.lng) : start.address,
							destination : "Alexanderplatz, Berlin",
							travelMode : google.maps.DirectionsTravelMode.DRIVING
							// Exchanging DRIVING to WALKING above can prove quite amusing :-)
						},
						mapOptions = {
							zoom: 10,
							// Default view: downtown Stockholm
							center : new google.maps.LatLng(59.3325215, 18.0643818),
							mapTypeId: google.maps.MapTypeId.ROADMAP
						};
						
					map = new google.maps.Map(document.getElementById("map"), mapOptions);
					directionsDisplay.setMap(map);
					directionsDisplay.setPanel(document.getElementById("map-directions"));
					directionsService.route(travel, function(result, status) {
						if (status === google.maps.DirectionsStatus.OK) {
							directionsDisplay.setDirections(result);
						}
					});
				};
			
				// Check for geolocation support	
				if (navigator.geolocation) {
					navigator.geolocation.getCurrentPosition(function (position) {
							// Success!
							createMap({
								coords : true,
								lat : position.coords.latitude,
								lng : position.coords.longitude
							});
						}, 
						function () {
							// Gelocation fallback: Defaults to Stockholm, Sweden
							createMap({
								coords : false,
								address : "Sveavägen, Stockholm"
							});
						}
					);
				}
				else {
					// No geolocation fallback: Defaults to Lisbon, Portugal
					createMap({
						coords : false,
						address : "Lisbon, Portugal"
					});
				}
		})();
	</script>

This example is also available for viewing at https://robertnyman.com/html5/geolocation/current-location-and-directions.html

Maps are cool

I’ve always found maps very cool, and with all this new geolocation support, we can create some awesome services. Start playing with it now. 🙂

40 Comments

Leave a Reply to links for 2010-03-16 « burningCat Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.