Geolocation API — How to get current user location

Before using Geolocation API, lets understand why need to use it.

If you are building a web application, there will come a time where your need to know the current location of the users. Why I need to know the location of the users? Because you might need to show contents relevant to the location of the user or even change your locale based on it or even you can allow use to track location using app ex. fitness apps.

Geolocation API

JavaScript has an API which can be used to retrieve the user location, only if user allows permission. Below is a script simple script to do that!

Breakup of above Geolocation API

1) Getting Geolocation object

We check for whether geolocation api is currently supported in our browser.

2) Getting Current Position

Now if the thing is supported, we can easily pull the latitude and longitude of the current user location.

Make sure to provide permission for browser to pull your current location

geolocation-api
Geolocation allowing permission

 3) Watch Position for Change.

Finally, you can use the watch to track the changes in user location and update it. (cases in which we provide mobile apps like fitness app to track user jogging locations)

4) Using Google Maps or OpenStreepMap to display the fetch information in a awesome map

Google Maps:

OpenStreeMaps: (Make sure to include OpenLayers.js)

You can even revoke permission later to any site by clicking the label in address bar.

geolocation-revoking-permission
Geolocation revoking permission

Geolocation Accuracy

Geolocation is most accurate for devices with GPS.

“W3C Geolocation” — the Web site will get the accuracy of whatever geolocation method (whether based on IP, access point MAC, GPS, cell-ID, etc.)

Some Web browsers have access to GPS receivers. Some of them (like Firefox and Chrome/Chromium) can use the MAC address of a WiFi access point to query Google’s database of the locations of WiFi access points.

Geolocation API removed from unsecured origins in Chrome 50

 According to Google API, https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only
It is an important issue as it will directly impact any site that requires use of the geolocation API and is not served over https, but it is a change that we do believe is beneficial to all users on the web. This post should help you understand the reasoning and how to proceed.

 Browser Support

http://caniuse.com/#search=geolocation

geolocation browser support
geolocation browser support

References

  1. https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation
  2. http://caniuse.com/#search=geolocation

 

Leave a Reply