Several useful Web apis — geolocation apis
The original link
API usage – Three methods for one object
Navigator. Geolocation returns a Geolocation object that has a method, getCurrentPosition(), which is an asynchronous request that calls the Google API, so you might need to jump the wall and call the method:
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
Copy the code
SuccessCallback returns a Position object that looks like this:
Longitude: longitude of a decimal number coords. Accuracy: position accuracy coords. Altitude: longitude longitude of a decimal number Altitude, above sea level in meters coords. AltitudeAccuracy: altitudeAccuracy of position coords. Heading: starting from due north in degrees coords. Speed: timestamp: date/time of responseCopy the code
ErrorCallback returns an error message that looks like this:
Code: error code: 1: the user forbids obtaining location information. 2: the network is unavailable or the satellite fails to be connected. 3: it takes too long to obtain location informationCopy the code
Options are setting parameters, such as the maximum timeout period.
{enableHighAccuracy: true, // Whether to try to read latitude and longitude more accurately. On mobile devices, this may require using GPS on the phone, which consumes more power on the mobile device and takes longer to locate. Default is false maximumAge: 30000, // Cache time timeout: 27000 // Maximum time to wait for a response, default is 0 ms, indicating infinite time}Copy the code
In addition, navigator. Geolocation has two useful methods: watchPosition and clearWatch. The former is a tracker that asynchronously returns real-time location information based on the geographical location of the device to achieve real-time location tracking, and is called in the same way as getCurrentPosition. This method returns a unique Watcher ID that can be turned off using clearWatch(ID), much like setInterval and clearInterval work.
var watcherId = navigator.geolocation.watchPosition(successCallback, errorCallback, options); / / start tracking the navigator. Geolocation. ClearWatch (watcherId); // Turn off the traceCopy the code
Not: native geolocation. GetCurrentPosition
Main code:
onGetGeoLocation () { if('geolocation' in navigator) { let center, map, marker, options = { enableHighAccuracy: false, maximumAge: 10 * 1000, timeout: 30 * 1000, }; navigator.geolocation.getCurrentPosition(position => { console.log(position); this.errMsg = ''; / / get the latitude and longitude center = [position. Coords. Longitude, position. Coords. Latitude]; Map = new amap. map ('geolocation-container', {resizeEnable: true, zoom: 15, center: center }), marker = new AMap.Marker({ position: center, map: map }); }, err => { console.log(err); ErrMsg = err. Message | | 'error'; }, options); } else {alert(' Your browser does not support location '); }}Copy the code
Some attention
The main influencing factors of location function
The network is the main factor that affects the location function.
Positioning function In the mobile network environment, positioning is through the base station or WIFI positioning, the success rate of obtaining positioning information is high, the speed is fast.
In the physical network environment, it is a bit complicated. First, the browser invokes the location interface of the corresponding location server, and then the location server connects to the satellite to locate the location using the user’s IP address, and then returns the location information to the browser and sends it to the user. It is difficult to guarantee the success rate of fixed location due to the influence of two factors: the successful connection between browser and location server and the successful connection between location server and satellite.
Due to the weak signal, the success rate of GPS positioning is low. Even if successful positioning, it takes a long time. Generally, base station and WIFI will be used to assist positioning when GPS positioning is used.
Positioning accuracy
As for the positioning accuracy, in most cases, the positioning information of the device is returned through WIFI positioning, and the error is generally within tens of meters. (Because GPS positioning takes too long, it is generally skipped, and the positioning accuracy of the base station is lower and the priority is not as good as WIFI positioning.)
In the getCurrentPosition configuration parameter, enableHighAccuracy is set to true, which indicates that GPS positioning is only enabled. It is rarely used in applications based on the features of GPS positioning. So the default flase is generally sufficient.
Pay attention to
Chrome and IOS10+ no longer support locating requests in non-secure domains
In short, pure browser positioning, for a variety of reasons, is very — not — accurate 😂.
If it is used for business development, third-party map tools, such as amap. Geolocation plug-in of AMap, can be used to integrate browser positioning, high-precision IP positioning, Android positioning SDK auxiliary positioning and other means to provide the current accurate location, the current city information, continuous positioning (browser positioning) and other functions.
Demo2: Amap. Geolocation
Main code:
let map = new AMap.Map('geolocation-container2', { resizeEnable: true, zoom: 15 }); map.plugin('AMap.Geolocation', function() { let geolocation = new AMap.Geolocation({ enableHighAccuracy: Default :true timeout: 10000, // stop positioning after 10 seconds, default: infinite buttonOffset: New amap.pixel (10, 20),// The offset between the location button and the set dock position, default: Pixel(10, 20) zoomToAccuracy: False buttonPosition:'RB'}); map.addControl(geolocation); geolocation.getCurrentPosition(); AMap.event.addListener(geolocation, 'complete', onComplete); // Return location information amap.event. addListener(geolocation, 'error', onError); // Return location error message}); function onComplete (data) { console.log(data); } function onError (data) { console.log(data); }Copy the code
The resources
- Using geolocation
- HTML5 positioning experience
- Autonavi Open Platform