[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.
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:
Next, add some style to the page:
Save and open in a browser:
Now let’s code the function called by the button, inserting
also an “if” clause that checks whether the browser supports GeoLocation:
Now browse to the JavaScript API documentation to see the getCurrentPosition() function
of the geolocation object:
As you can see, the first parameter gets a function pointer
to be used as a callback: we’ll name the callback function fnShowMap:
Now let’s code the fnShowMap() function:
The callback function gets back the “position” of the user,
which includes latitude, longitude, altitude and accuracy:
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:
Copy-paste it to our function and replace the latitude
and longitude in the URL string:
Finally, create an img tag and set its
source as the URL of the static map:
Refresh the page and press the button. The browser will try
to block the geolocation because of privacy:
Allow temporarily to track your position:
And your position has been exposed on the Google Map:
That’s all: enjoy HTML5!!!
עריכה: כרמל שוורצמן
No comments:
Post a Comment