Geolocation in HTML5



The Geographical location of an object can be easily found and represented in HTML5. A separate API is used for this purpose. In this tutorial we will use html 5 geolocation api to get the location of the user including error handling features, also we will see how can we represent the positions on map.
Step # 1 – Geolocation Basic Code
The code shown in the image below could be used to understand how HTML5 Geolocation api works.
navigator.geolocation, is used to check whether the geolocation feature is supported by our browser or not
getCurrentPosition() function shows the co-ordinates of the position by using the function showPosition as parameter.
And showPosition basically returns the latitudes and longitudes of the position.
Geolocation Coding Structure

Step # 2 – Custom function to show errors
To include error handling for geolocations in html5, we can create our custom function.
Here we are using the function name as “ShowError”
Let us explain the terms being used in the function:
PERMISSION_DENIED means that the permission to get the position is denied by user
POSITION_UNAVAILABLE means that the geolocation position is not available
TIMEOUT means that the request for getting position has been timed out
And,
UNKNOWN_ERROR is self explanatory as it will show if any unknown error has occurred.
Geolocation with Error Handling (Errors)

Step # 3 – Using the Custom Function
To include error handling in our code, we just have to use the custom made function which we have just created.
The image below illustrates the usage of the custom function in the code.
Geolocation with Error Handling

Step # 4 – Geolocation in Map
To give more meaningful and interactive look, we can display the results in map too, for that we will request the services from google api and use the code in the same “ShowPosition “function which have already been made.
The image below illustrates the idea.
Showing Result on Map

And this was all about using geolocations in html5.