For a web development programmer, one of the most interesting aspects of development work is to obtain geographical location information; just imagine where are the users browsing your web pages? Programmers can adjust the website's language, specific product introduction, etc. based on the user's geographical location information. What we are going to demonstrate below is to obtain detailed geographic information through the JavaScript geolocation information API in the browser!
Check whether your browser supports the Geolocation API
Currently, mainstream browsers have better support for the JavaScript geolocation information API. But if you are not at ease, then the best way to confirm the support of the Geolocation Information API is to test the browser's feature feature.
if("geolocation" in navigator) { //w00t!}else { alert("Unfortunately! Your browser does not support Geolocation API functionality");}For determining whether the browser supports the geolocation API, the most important thing is to look at the navigation.geolocation object, use in, rather than simply using if (navigator.geolocation). This is very important, because the latter may initialize the geolocation information object, thereby occupying/locking device resources.
Query geographic location information
The navigator.geolocation.getCurrentPosition method is the most critical interface to obtain detailed location information:
if("geolocation" in navigator) { navigator.geolocation.getCurrentPosition(function(position) { console.log(position); });}Once you call this method (if the request succeeds, it will execute the callback method you provide in the parameter), the browser will ask the user whether to allow the program to obtain their geolocation information.
When users run a web page to obtain their location information, the browser can start reading geographic information. It will return you a location information object. The structure of the object is basically as follows:
// "Position" object{ coordinates: { "Coordinates" object accuracy: 65, altitude: 294.4074401855469, altitudeAccuracy: 10, heading: -1, latitude: 43.01256284360166, longitude: -89.44531987692744, speed: -1 }, timestamp: 1429722992094269}If you think these geographical location information (geographical latitude and longitude coordinates) are not sufficient and want the country or city that these geographical coordinates belong to, you need to call other third-party databases - we won't explain in detail here.
This geolocation 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, this technology is supported by all popular browsers at present.
The above is all about this article, I hope it will be helpful for everyone to learn JavaScript programming.