Friday, December 4, 2015

The GeoLocation in HTML5


The GeoLocation in HTML5by Carmel Schvartzman
[HTML5  Geolocation   is supported in IE 9+, Opera, Chrome, Firefox, and Safari]

The GeoLocation in HTML5


The Geolocation element is exposed via the navigator.geolocation object,  and used to get the geographical position of the user.
Because the Geolocation use can compromise user privacy, the user’s position is not available unless the user approves it.
In this tutorial, we’ll use the Google Maps API to load a map exposing the user’s location.

The GeoLocation in HTML5


To sample the Geolocation use, let’s build an HTM file including a DIV placeholder to the map representing the user’s location, and a button to trigger this function:
The GeoLocation in HTML5


Next, add some style to the page:

The GeoLocation in HTML5

Save and open in a browser:

The GeoLocation in HTML5

Now let’s code the function called by the button, inserting also an “if” clause that checks whether the browser supports GeoLocation:

The GeoLocation in HTML5

Now browse to the JavaScript API documentation to see the getCurrentPosition() function of the geolocation object:

The GeoLocation in HTML5

As you can see, the first parameter gets a function pointer to be used as a callback: we’ll name the callback function fnShowMap:

The GeoLocation in HTML5

Now let’s code the fnShowMap() function:

The GeoLocation in HTML5

The callback function gets back the “position” of the user, which includes latitude, longitude, altitude and accuracy:

The GeoLocation in HTML5


That’s why we can get back the latitude and longitude and use them.
Next, google the Google Maps API and find the example in it:

The GeoLocation in HTML5

Copy-paste it to our function and replace the latitude and longitude in the URL string:
The GeoLocation in HTML5


Finally, create an img tag and set its source as the URL of the static map:

The GeoLocation in HTML5

Refresh the page and press the button. The browser will try to block the geolocation because of privacy:

The GeoLocation in HTML5

Allow temporarily to track your position:


The GeoLocation in HTML5

And your position has been exposed on the Google Map:

The GeoLocation in HTML5

The GeoLocation in HTML5


That’s all: enjoy HTML5!!!
עריכה: כרמל שוורצמן

Category: HTML5 GEOLOCATION

No comments:

Post a Comment