JavaScript Geographic Location Information API

  • 2021-06-28 08:34:59
  • OfStack

For an Web developer, one of the most interesting aspects of development work is the acquisition of geographic location information;Imagine, for a moment, where are the users who browse your web page?Programmers can adjust the language of the website, specific product descriptions, and so on, based on the user's geographic location information.Next we will show you how to get detailed geographic information from the JavaScript geographic location information API in your browser!

Check if your browser supports geographic location information API

Currently, the mainstream browsers have better support for JavaScript geographic location information API.But if you're not sure, the best way to confirm API support for geographic location information is to test the browser's functional characteristics.

if("geolocation" in navigator) {
else {
 alert(" Unfortunately!Your browser doesn't support it Geolocation API function ");

To determine whether a browser supports the geographic location API, it is important to look at the object navigator.geolocation, which uses in instead of if (navigator.geolocation), which may initialize the geographic location information object and thus occupy/lock the device resources.

Query geographic location information

This navigator.geolocation.getCurrentPosition method is the most critical interface for getting detailed location information:

if("geolocation" in navigator) {
 navigator.geolocation.getCurrentPosition(function(position) {

Once you invoke this method (if the request succeeds, it executes the callback method you provided in the parameter), the browser asks the user if they want the program to get their geographic location information.

When users run a web page to get their location information, the browser can start reading the geographic information, and it will return you a location information object, which is basically structured like this:

// "Position" object
 coords: { "Coordinates" object
 accuracy: 65,
 altitude: 294.4074401855469,
 altitudeAccuracy: 10,
 heading: -1,
 latitude: 43.01256284360166,
 longitude: -89.44531987692744,
 speed: -1

 timestamp: 1429722992094269

If you don't think these geographic locations (latitude and longitude coordinates) are sufficient and you want to know which country or city these geographic coordinates belong to, you need to call another third-party database -- we won't go into details here.
This geographic location information, API, is the most common use of API in many mobile applications. As an Web programmer, it should be a skill you must have.Fortunately, all popular browsers now support this technology.

This is the whole content of this article, and I hope it will be helpful for you to learn javascript program design.

Related articles: