Home>Article>Web Front-end> Learn the JavaScript geolocation API
For a Web development programmer, one of the most interesting aspects of development work is obtaining geographical location information; just imagine, where are the users browsing your webpage? Programmers can adjust the website's language, specific product introductions, etc. based on the user's geographical location information. What we are going to demonstrate below is to obtain detailed geographical information through the JavaScript geographical location information API in the browser!
Related learning recommendations:javascript video tutorial
Currently mainstream All browsers already have good support for the JavaScript geolocation information API. But if you are still not convinced, then the best way to confirm the geolocation information API support is to test the browser's functional features.
if("geolocation" in navigator) { //w00t! } else { alert("很不幸!你的浏览器并不支持Geolocation API功能"); }
To determine whether the browser supports the geolocation API, the most important thing is to look at thenavigator.geolocation
object and usein
instead of simply usingif(navigator.geolocation)
, this is very important, because the latter may initialize the geolocation information object, thus occupying/locking device resources.
Thisnavigator.geolocation.getCurrentPosition
method is the most critical interface for obtaining detailed location information:
if("geolocation" in navigator) { navigator.geolocation.getCurrentPosition(function(position) { console.log(position); }); }
Once you call After this method (if the request is successful, it will execute the callback method you provided in the parameter), the browser will ask the user whether to allow the program to obtain their geographical location information:
When the user runs the web page to obtain their location information, the browser can start to read the geographical information, and it will return you a location information object. The structure of the object is basically 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 think This geographical location information (geographical longitude and latitude coordinates) is not sufficient. If you want to know which country or city these geographical coordinates belong to, you need to call other third-party databases - we will not go into details here.
This geographical location information API is the most common API application in many mobile applications. As a web programmer, it should be a knowledge and skill that you must have. Fortunately, all popular browsers currently support this technology. Happy programming!
The above is the detailed content of Learn the JavaScript geolocation API. For more information, please follow other related articles on the PHP Chinese website!