Wednesday, January 18, 2012

GeoLocation with HTML 5

Lately, I have been working on a project that needs to locate user's location. I used HTML5 GeoLocation to accomplish that, and I want to share here how I did it.

First let's check if your browser supports the GeoLocation.

Browser will have a pop up to ask you if you want to share your location. If you click YES, you should be able to see the results.

Let's look at the GeoLocation API structure.
 if (navigator.geolocation) {
// GeoLocation is supported
                    } 
else {            
 alert("GeoLocation is not supported by your browser.");     
    }

To find the latitude and longtitude of our client we need to use the function named getCurrentPosition.

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {maximumAge, timeout});

Let's try to use this.

var timeoutVal = 10 * 1000 * 1000; navigator.geolocation.getCurrentPosition(displayPosition, displayError, { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 });

displayPosition is the name of the function that is going to do the work when we have the geolocation information. For somereason if geolocation request would fail then displatError is going to take care of the failure.

When browser retrieves the location of the client, It returns the location information in position object.
Here is the position object structure.

 [NoInterfaceObject]
  interface Position {
    readonly attribute Coordinates coords;
    readonly attribute DOMTimeStamp timestamp;
  };
[NoInterfaceObject]
  interface Coordinates { readonly attribute double latitude;
    readonly attribute double longitude;
    readonly attribute double? altitude;
    readonly attribute double accuracy;
    readonly attribute double? altitudeAccuracy;
    readonly attribute double? heading;
    readonly attribute double? speed;
  };

 We need to create two functions, I named them displayPosition, and displayError

if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
 navigator.geolocation.getCurrentPosition(displayPosition, displayError, { 
            enableHighAccuracy: true
            timeout: timeoutVal, maximumAge: 0 }
);
}
else {
  alert("GeoLocation is not supported by your browser.");         
}
function displayPosition(position) {
alert("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);
        }
 
function displayError(error) {
            var errors = {
                1: 'Permission denied',
                2: 'Position unavailable',
                3: 'Request timeout'
            };
            alert("Error: " + errors[error.code]);
        }

Now, you should be able to see the longtitude and latitude of your computer. With these values you can show your location on Google Maps if you like. To do that we need to do some more work in displayPosition function...

function displayPosition(position) {
            var pos = new google.maps.LatLng(position.coords.latitude, 
                                     position.coords.longitude);             var options = {zoom: 10,center: pos,                 mapTypeId: google.maps.MapTypeId.ROADMAP};             var map = new google.maps.Map(document.getElementById("map"), options);             var marker = new google.maps.Marker({                 position: pos,                 map: map,                 title: "User location"             });             var contentString = "<b>Timestamp:</b> " + parseTimestamp(position.timestamp) + "<br/><b>User location:</b> lat " + 
position.coords.latitude + ", long " + position.coords.longitude + ", accuracy " + 
position.coords.accuracy;             
            var infowindow = new google.maps.InfoWindow({content: contentString});      
            google.maps.event.addListenermarker, 'click'function () {
                infowindow.open(map, marker);
            });
}

You can do much more than that. For example....
  1. Find the zip code of your client.
  2. Find the near by cities.
  3. Check out the weather of your client.
  4. Find the intersections, streets, counties....

Unfortunatelly, Geolocation API doesn't support those. In future we might see the Address information too. If you want to do more than that, you need to use Web Services for your needs, In my project I need to find the zip code of my client so I can show the closest data to my client. I used GeoNames WebServices to accomplish that. Some of the GeoNames webservices are free, and findNearByPostalCodes function is one of them.
Here is their web services page.



No comments:

Post a Comment