Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

HTML5 geolocation – What If the User Doesn’t Share His Position?

DZone's Guide to

HTML5 geolocation – What If the User Doesn’t Share His Position?

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

So far we were used to expect something like this from our mobile phones with built-in GPS support. Every image or video clip then was automatically “tagged” with latitude & longitude geo data. With HTML5 coming features we discover new cool things we can do with our browsers. Such cool thing is the geolocation.



Support

As you may guess not every browser is supporting these HTML5 features, but out in the web there is quite good collection of tables comparing different browsers and their support level.

Firefox

This – as expected is a browser that supports this geo tagging. First of all you’ve to allow your browser to use your geo coordinates, as this can be private information.


Once you do it you can access the geo coordinates, which by the way are quite accurate, with JavaScript.

What if you don’t share your position?

What happens if you don’t want to share your position? Actually I ran in this situation and as my application waited the coordinates – it was completely blocked.

The examples doesn’t show you something special. They simply describe how to get the coordinates, but doesn’t tell you what if the user doesn’t click on the “share” button.

if (!!navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPos);
}
...

function getPos(position)
{
position.coords.latitude;
position.coords.longitude;
}

Of course getPos() can be simply an anonymous function:

if (!!navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
position.coords.latitude;
position.coords.longitude;
});
}

Only the Firefox documentation tells you how to handle errors, simply add one more parameter – callback, for getCurrentPosition() method:

if (!!navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPos, onError);
}
...

function getPos(position)
{
position.coords.latitude;
position.coords.longitude;
}

function onError()
{
// handle error
}

Now you know where you don’t want to be.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}