Using JavaScript to Get Location

Firstly, we will use Canuse cmd to check the compatibility of geolocation, as almost all modern browsers support geolocation

Geolocation

By using GPS, WIFI, and IP addresses to detect their location information, developers can use this information to provide users with better search suggestions, such as nearby convenience stores, and achieve interaction.

Local resources

JavaScript provides a simple but powerful tool to locate devices in the form of a geolocation API. It includes a small set of easy-to-use methods to obtain the location of the device:

GPS – mainly used on mobile devices, accurate to 10 meters

WIFI – Almost all connected devices

IP – Regional only, alternative options

The choice of solution depends on browser support. Generally, WIFI is faster than GPS and faster than IP

Using the geolocation API

By using Canuse cmd, we know that most browsers support geolocation, but we need to make a good judgment to ensure that geolocation can be used normally.

There are several methods for navigator.geolocation:

Geolocation. getCurrentPosition() – Get current position

Geolocation. watchPosition() – Monitoring and positioning

Geolocation. clearWatch() – Clear Monitoring

The working methods of getCurrentPosition() and watchPosition() are basically the same. These two methods have the same purpose, both of which are used to obtain device location information. They both work asynchronously and rely on the result of an attempt call to obtain location information.

As mentioned above, using the geolocation API is very simple, just call the method correctly and wait for the return coordinates.

User permissions

Due to the geolocation API exposing user information, when an application accesses it, it will request user actions with a pop-up window, as follows

Host security

Another protective measure is to use HTTPS connections. Due to a new network security policy, Google Chrome (desktop and mobile versions) no longer allows geolocation APIs to run on non secure hosts. The use of HTTPS can minimize the risk of data information theft or abuse.