HTML5 Geolocation

Certify and Increase Opportunity.
Be
Govt. Certified HTML5 Developer

geolocation

HTML5 Geolocation Basics

HTML5 Geolocation is the art of figuring out where you are in the world and (optionally) sharing that information with people you trust. There is more than one way to figure out where you are — your IP address, your wireless network connection, which cell tower your phone is talking to, or dedicated GPS hardware that calculates latitude and longitude from information sent by satellites in the sky.

HTML5 Geolocation API in HTML5
The geolocation API lets you share your location with trusted web sites. The latitude and longitude are available to JavaScript on the page, which in turn can send it back to the remote web server and do fancy location-aware things like finding local businesses or showing your location on a map.

The geolocation API centers around a new property on the global navigator object: navigator.geolocation.

The simplest use of the geolocation API looks like this:

function get_location() {
navigator.geolocation.getCurrentPosition(show_map);
}

That has no detection, no error handling, and no options. Your web application should probably include at least the first two of those.

The geolocation object
The geolocation API is published through the navigator.geolocation object.

If the object exists, geolocation services are available. You can test for the presence of geolocation thusly:

if (“geolocation” in navigator) {
/* geolocation is available */
} else {
/* geolocation IS NOT available */
}

Getting the current position
To obtain the user’s current location, you can call the getCurrentPosition() method. This initiates an asynchronous request to detect the user’s position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.

By default, getCurrentPosition() tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data (IP location or wifi) may be returned to getCurrentPosition().

navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords.latitude, position.coords.longitude);
});

The above example will cause the do_something() function to execute when the location is obtained.

Dynamic page support
Web storage

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?