preface

The Geolocation API allows users to provide their location to Web applications. For privacy reasons, users are asked for permission before reporting their location.

Geolocation object

Navigator. Geolocation is available:

if ("geolocation" in navigator) {
  /* Location services available */
} else {
  /* Location-based services are not available */
}
Copy the code

Get current location

GetCurrentPosition () is used to get the user’s current location.

navigator.geolocation.getCurrentPosition(success, error, options);
Copy the code
  • Success: The callback function to successfully get the Position information, using the Position object as the only argument.

    function success(pos) {
      // Geographical status
      var crd = pos.coords;
    
      console.log("Your current position is:");
      / / latitude
      console.log("Latitude : " + crd.latitude);
      / / longitude
      console.log("Longitude: " + crd.longitude);
      / / the accuracy
      console.log("More or less " + crd.accuracy + " meters.");
    }
    Copy the code

    By default, a low-precision result is returned as soon as possible

  • Error: Optional callback function for failure to get location information, using PositionError object as the only argument.

    function error(err) {
      console.warn("ERROR(" + err.code + ")." + err.message);
      switch (error.code) {
        case error.PERMISSION_DENIED:
          x.innerHTML = "User rejects geolocation request.";
          break;
        case error.POSITION_UNAVAILABLE:
          x.innerHTML = "Location information is not available.";
          break;
        case error.TIMEOUT:
          x.innerHTML = "Request user geolocation timed out.";
          break;
        case error.UNKNOWN_ERROR:
          x.innerHTML = "Unknown error.";
          break; }}Copy the code
  • Options: Optional, a PositionOptions object.

    • enableHighAccuracy: Whether to use its highest precision
      • falseBy default, the device saves as much resources as possible by responding faster, using less power, and so on
      • true, which can lead to slower response times or increased power consumption (such as for GPS-enabled mobile devices).
    • timeout: Limits the return time
      • Infinity, the default, waiting until the location is obtained.
    • maximumAge: Can return the cache location in milliseconds for how long.

Monitor positioning

WatchPosition () listens for changes in location data (a device has moved, or a more precise location has been retrieved), which takes the same arguments as getCurrentPosition().

id = navigator.geolocation.watchPosition(success[, error[, options]])
Copy the code

This method returns an ID that can be passed in clearWatch() to cancel listening.

navigator.geolocation.clearWatch(id);
Copy the code

Example:

var id, target, options;

function success(pos) {
  var crd = pos.coords;

  // Get to the destination
  if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
    console.log("Congratulations, you reached the target"); navigator.geolocation.clearWatch(id); }}function error(err) {
  console.warn("ERROR(" + err.code + ")." + err.message);
}

/ / destination
target = {
  latitude: 0.longitude: 0}; options = {enableHighAccuracy: false.timeout: 5000.maximumAge: 0}; id = navigator.geolocation.watchPosition(success, error, options);Copy the code

The Position object

attribute describe
coords.latitude The latitude of a decimal number
coords.longitude Longitude of a decimal number
coords.accuracy Location accuracy
coords.altitude Elevation in meters above sea level
coords.altitudeAccuracy Elevation accuracy of position
coords.heading Direction, starting due north in degrees
coords.speed Velocity in meters per second
timestamp Date/time of the response

HTML 5 series

  • To understand it
  • Enhanced forms
  • Audio and Video
  • Canvas nanny tutorial (part 1) : Drawing
  • Canvas Nanny tutorial (part 2) : Animation
  • Finally drawing in SVG
  • Geolocation
  • A drag-and-drop operation
  • Understand the Web Worker
  • Understand the Web Storage
  • Understand the WebSocket