Html5 Geolocation

The HTML5 Geolocation API is a new feature that help to manage and display the location of the user ,provided by a variety type of devices and Methods including : GPS , Bluetooth , Wifi , GSM/3G , IP Address ....

HTML5 Geolocation API

The main javascript object used is navigator.geolocation (learn more about the navigator object at javascript for browser).

Remember that the browser will not display the geolocation informations without the permission of the user.
For example , Firefox display this message :




First of all , it's better if you test if the browser support geolocation object or not , as some browsers especially, the  old one ,do not support this feature  :


Usually ,Our code will be inside the else block.

Geolocation in javascript is controlled by 3 methods :

1-getCurrentPosition(success,error,options) :  this method is used to detect the current position of the user.the success parameter is executed when the location is successfully returned , The error parameter executed in an error case.options help to control the occuracy of the location.
Actually,the success parameter is the most important one , error and options are optional.

2-watchPosition(success,error,options): watchPosition help to display the user position and update it when user change the location , this function is commonly used in smartphone applications.It has the same syntax and parameters of getCurrentPosition().

3-clearWatch(watchID) : This method is used to stop watching the user position . its parameter watchID is the result of watchPosition( )

Extract the latitude and longitude : Getting the latitude and longitude of the user can be performed using position.coords.longitude and position.coords.latitude

As everything begin with a simple Html document ,make a simple html document and add the following tags inside the body tag : 




Now , lets build our the geolocation script, we will use the getCurrentPosition() method .




When the user click on the show Button, a function called geolocation will be executed , this is the main function in the script  , Using Google Map API , This function will display a static map in the div block ,
The Idea is to extract longitude and latitude , then build the URL of the map using these details .In fact , the URL must be in this format : 

http://maps.googleapis.com/maps/api/staticmap?center=latitude,longitude&zoom=14&size=400x300&sensor=false

zoom = 14 is the zoom value to the position .
latitude and longitude are the values of position.coords
 400x300 is the dimension of the map. after building the map URL , Using innerHTML method ,add this URL as an src of an image to the DIV tag.

Demo :

                                                                       

0 comments

Posts a comment

 
© Articmo, web development blog | Api tutorial | seo | javascript | html | php

All rights reserved the content is copyrighted to Mohamed Mbarki.

Masters scholarships
Back to top