Google Gears provides geolocation across the major browsers. This free tutorial will show you how to use Google Gears to map a users position on a map.
DOWNLOAD THE SOURCE CODE
VIEW THE DEMO
Location awareness, or GeoLocation, adds a whole world of possibilities to web based applications. In fact if you have ever used Google Maps on the iPhone, you have used GeoLocation. It could be used to find local resturants, train stations, traffic conditions and any other information that is local to a physical area.
GeoLocation is part of the upcoming HTML5 standard, and today quite a few browsers support it. The big omission is IE, which has not made much attempt to include any features of the draft HTML5 standard. Thankfully Google Gears provides GeoLocation across all the major browsers.
Download the gears_init.js file from here. This file is needed to initialise the Google Gears library.
Sign up for a Google Maps API key here. This key is needed to initialise the Google Maps library.
Create a HTML file to display the map. There are 4 important elements that need to be included in the HTML file:
- A reference to the gears_init.js file (<script type="text/javascript" src="gears_init.js"></script>)
- A reference to the Google Maps JavaScript file (<script type="text/javascript" src="http://www.google.com/jsapi?key=YourMapsAPIKey"></script>
- A reference to the JavaScript file that will be created to call Google Gears and Google Maps (<script type="text/javascript" src="application.js"></script>)
- A DIV element where the map will be displayed, with an ID of map (<div id="map" style="width: 480px; height: 384px;"> </div>)
<html>
<head>
<title>Google Gears Geolocation Demo</title>
<script type="text/javascript" src="gears_init.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi?key=YourMapsAPIKey"></script>
<script type="text/javascript" src="application.js"></script>
</head>
<body>
<p style="font-family: Arial, Helvetica, sans-serif;">
<strong>
<a href="http://www.brighthub.com/hubfolio/matthew-casperson.aspx">Google Gears Geolocation Demo</a>
</strong>
</p>
<div id="map" style="width: 480px; height: 384px;"> </div>
</body>
</html>
The application.js file will host the JavaScript that calls the Google Gears GeoLocation functions and then maps the returned position to a Google Map.
The first thing we need to do is make sure that Google Gears has been installed.
if (!window.google || !google.gears)
{
location.href = "http://gears.google.com/?action=install"+
"&message=Welcome to Google Gear Installation" +
"&return=http://www.brighthub.com/hubfolio/matthew-casperson.aspx";
}
This detection code comes from this Google Gears FAQ item, and it is the recommend way to detect if Google Gears is installed in the browser. If not, the user is redirected to the Gears installation page.