Home » Labs »

Geolocation with Google Maps

Geolocation with Google Maps

A kick-starer demo to teach you how to deal with in-browser geolocation by making use of Google Maps' awesome API.

The Basic Structure

Since we're doing most of the magic in Javascript, the HTML is quite simple.
<div id="map"></div>. To kick-start the Javascript side, we're going to get old school and mix it with the new school.

  1. window.onload = function(){
  2. if(navigator.geolocation)
  3. navigator.geolocation.getCurrentPosition(onSuccess, onError);
  4. }

navigator.geolocation

The navigator.geolocation object is the godsend. The method you'll be using the most is getCurrentPosition(onSuccess, onError). This method will make the browser call the onSuccess function, passing a special object as a parameter. That object holds information relating to the user's current geographical location, as best as the browser and machine can tell.

A look at the position object

The position object passed to the onSuccess function has a coords property, of type Coordinates, and a timestamp property, which is useful for caching.
Below is what mine looks like. Note the accuracy property and its value. It's the radius, expressed in meters, of the area around the described lat,long pair where you are in. A large value, such as mine, suggests the geolocation detection is at city level.

  1. position = {
  2. coords: {
  3. accuracy: 122000,
  4. altitude: null,
  5. altitudeAccuracy: null,
  6. heading: null,
  7. latitude: 45.755539,
  8. longitude: 21.237499,
  9. speed: null,
  10. },
  11. timestamp: 1278240363889.1726
  12. }

What else is there?

The navigator.geolocation object provides such a spiffy API. The watchPosition(onUpdate, onError) method can turn your Javascript App into a turn by turn GPS application, making use of the user's current location and getting notified each time it changes.

This comes in handy when dealing with handhelds, or devices with a certain autonomy. Still, be careful about using watchPosition, specifically you can stop listening for position changes when you don't need frequent updates. Use navigator.geolocation.clearWatch(watchID) to cancel a watch. watchID is an identifier to a watchLocation listener, the return value of a navigator.geolocation.watchPosition call. Free tip: remember the timestamp property of the position object? Use that for caching or deciding when to ask for a location update.

A quick look at Google Maps API

The demo makes use of two GMaps API functions: a map with a marker; the geocoder API. While the map and marker part seems simple, bare in mind that these are just simple building blocks that the devs at Google provide. Just by looking at the code, I can think of a million ways I can iterate over the simple function.

  1. function handleGetCurrentPosition(location){

  2. var position = new google.maps.LatLng(location.coords.latitude, location.coords.longitude)

  3. var map = new google.maps.Map(mapDiv, {
  4. zoom: 16,
  5. center: position,
  6. mapTypeId: google.maps.MapTypeId.HYBRID
  7. });

  8. var marker = new google.maps.Marker({
  9. position: position,
  10. map: map
  11. })

  12. new google.maps.Geocoder().geocode({location: position}, handleGeocoderGetLocations);
  13. }

The first part of the function creates a simple map, centered at the user's current location, pinpointed by a marker.
The last line of the above function makes use of Google's incredibly handy geocoder interface. Basically, what we're doing is called reverse geocoding; we're giving Google a point on the globe ( a lat,lng pair ) and we're asking them to tell us where in the world that point is. That information will be passed to the handleGeocoderGetLocations function. Here's how that information looks like:

  1. addresses = [{
  2. address_components: [{
  3. long_name: "Bulevardul Revoluţiei din 198...",
  4. short_name: "Bulevardul Revoluţiei din 198...",
  5. types: ["route"]
  6. }, ...],
  7. formatted_address: "Bulevardul Revoluţiei din 1989, Timisoara, Romania",
  8. geometry: {
  9. bounds: Object,
  10. location: Object,
  11. location_type: "APPROXIMATE",
  12. viewport: Object
  13. },
  14. types: [ "route" ]
  15. }, ...]

We can be lazy and just use the formatted_address property from the first of the results Google gives us. We can also search through them, looking only for the country, or city, or region, what have you. I've also included such an utility in the source code. Make sure you get it.

Further reading: Google Maps Javascript API Docs and Geolocation on MDC. But do check out the demo and source code first!



Leave a Comment :

(required)


(required)




(required)




(required)




 
Page generated in: 0.12s