Browser geolocation and geocoding (2024)

What is browser geolocation and how does it relate to geocoding?

Browser geolocationis a technology supported by almost all web browserswhich enables users to share their location - in the form of geographiccoordinates (longitude and latitude) - with a web service.

Geocoding,on the other hand, is the process of turning coordinates into geographicinformation (address, placenames, etc) or vice versa.

The accuracy of the coordinates obtained from browser geolocation willdepend on the underlying technologybeing used to determine the user's location, which could be GPS, WiFinetwork, phone cell tower mapping, or IP address. If the user is on amobile device with a GPS signal, the coordinates can be highly accurate.If however the user is using an ISP and the location is coming from an IPto location lookup the location may not be accurate at all. The browserlocation may also be misleading if the user is accessing a web service viaa VPN or similar technologies.

Once you have used browser geolocation to obtain the user's location inthe form of coordinates, these coordinates can be reverse geocoded usingthe OpenCage geocoding API to be turned into geographic information like anaddress or a country, state/province, time zone, etc.

Please see the code example below or theOpenCage API referencefor details of how to do the geocoding.

Privacy considerations

Because a user's location is private information, browser geolocation isonly possible if the user explicitly grants permission to a web servicevia a browser prompt. You can see an example of what this looks like onthese screenshots.

First, the user is shown a button to start the browser geolocation process:

Browser geolocation and geocoding (1)

Then the browser (Firefox in this screenshot) prompts to ask the user iflocation info should be shared. Only if the user allows it does the browserget access to the user's location information.

Browser geolocation and geocoding (2)

It is not possible to perform browser geolocation without the user'sactive consent.

Technical details / Code Example

Most modern web browsers support browser geolocation, but only in a securecontext (HTTPS). Some older browsers may not support browser geolocation.It is advised to always check in your code whether browser geolocation issupported before attempting to use the functionality, as shown in thisjavascript example.

// browser location starts when this function is calledfunction getLocation() { // check to make sure geolocation is possible if (navigator.geolocation) { var options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }; navigator.geolocation.getCurrentPosition(success, error, options); } else { console.log('Geolocation is not supported'; } }}function error(err) { console.warn(`ERROR(${err.code}): ${err.message}`);}function success(pos) { var query = pos.coords.latitude + ',' + pos.coords.longitude; console.log('coordinates: ' + query); console.log('accuracy: ' + pos.coords.accuracy + ' meters.'); // now we have coordinates, it is time to use them to // do some reverse geocoding to get back the location information var api_url = 'https://api.opencagedata.com/geocode/v1/json' var apikey = 'YOUR-API-KEY'; var request_url = api_url + '?' + 'key=' + apikey + '&q=' + encodeURIComponent(query) + '&pretty=1' + '&no_annotations=1'; // now we follow the steps in the OpenCage javascript tutorial // full example: // https://opencagedata.com/tutorials/geocode-in-javascript var request = new XMLHttpRequest(); request.open('GET', request_url, true); request.onload = function() { // see full list of possible response codes: // https://opencagedata.com/api#codes if (request.status === 200){ // Success! var data = JSON.parse(request.responseText); alert(data.results[0].formatted); } else if (request.status <= 500){ // We reached our target server, but it returned an error console.log("unable to geocode! Response code: " + request.status); var data = JSON.parse(request.responseText); console.log('error msg: ' + data.status.message); } else { console.log("server error"); } }; request.onerror = function() { // There was a connection error of some sort console.log("unable to connect to server"); }; request.send(); // make the request}// trigger getLocation when the page is ready// change to be when a certain button is clicked or action is taken$(document).ready(function(){ getLocation();}

Further Reading

Happy geocoding!

Browser geolocation and geocoding (2024)
Top Articles
Latest Posts
Article information

Author: Rueben Jacobs

Last Updated:

Views: 5955

Rating: 4.7 / 5 (77 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Rueben Jacobs

Birthday: 1999-03-14

Address: 951 Caterina Walk, Schambergerside, CA 67667-0896

Phone: +6881806848632

Job: Internal Education Planner

Hobby: Candle making, Cabaret, Poi, Gambling, Rock climbing, Wood carving, Computer programming

Introduction: My name is Rueben Jacobs, I am a cooperative, beautiful, kind, comfortable, glamorous, open, magnificent person who loves writing and wants to share my knowledge and understanding with you.