Html5 简明教程

HTML - Geolocation API

Web 应用程序中使用 HTML 地理位置 API 访问用户的地理位置信息。大多数现代浏览器和移动设备都支持地理位置 API。

HTML Geolocation API used by web applications to access geographical location of user. Most of the modern browsers and mobile devices support Geolocation API.

JavaScript 可以捕获用户的经度和纬度并将其发送到后端 Web 服务器上,并执行基于位置的信息任务,如找到本地业务或在地图上显示用户的当前位置。

JavaScript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map.

Syntax

var geolocation = navigator.geolocation;

地理位置对象是一个允许小组件检索有关设备地理位置信息的服务对象。

The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device.

Geolocation Methods

地理位置对象提供以下方法:

The geolocation object provides the following methods:

Method

Description

getCurrentPosition()

This method retrieves the current geographic location of the user.

watchPosition()

This method retrieves periodic updates about the current geographic location of the device.

clearWatch()

This method cancels an ongoing watchPosition call.

以下是一个使用上述任一方法的示例代码:

Following is a sample code to use any of the above methods:

function getLocation() {
   var geolocation = navigator.geolocation;
   geolocation.getCurrentPosition(showLocation, errorHandler);

   watchId = geolocation.watchPosition(showLocation, errorHandler, {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
  });

  navigator.geolocation.clearWatch(watchId);
}

在这里,showLocation 和 errorHandler 是一些回调方法,它们会像下一节中解释的那样,被用来获取实际位置,以及在有错误的时候处理错误。

Here showLocation and errorHandler are callback methods which would be used to get actual position as explained in next section and to handle errors if there is any.

Location Properties

地理位置方法 getCurrentPosition()getPositionUsingMethodName() 指定了检索位置信息回调方法。这些方法会与一个对象位置异步调用,该位置储存了完整的位置信息。

Geolocation methods getCurrentPosition() and getPositionUsingMethodName() specify the callback method that retrieves the location information. These methods are called asynchronously with an object Position which stores the complete location information.

Position 对象指定了设备当前的地理位置。位置被表示成一组地理坐标,以及关于航向和速度的信息。

The Position object specifies the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed.

下表描述了位置对象的属性。对于可选属性,如果系统无法提供一个值,那么属性的值就会被设置为 null。

The following table describes the properties of the Position object. For the optional properties if the system cannot provide a value, the value of the property is set to null.

Property

Type

Description

coords

objects

Specifies the geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed.

coords.latitude

Number

Specifies the latitude estimate in decimal degrees. The value range is [-90.00, +90.00].

coords.longitude

Number

Specifies the longitude estimate in decimal degrees. The value range is [-180.00, +180.00].

coords.altitude

Number

[Optional] Specifies the altitude estimate in meters above the WGS 84 ellipsoid.

coords.accuracy

Number

[Optional] Specifies the accuracy of the latitude and longitude estimates in meters.

coords.altitudeAccuracy

Number

[Optional] Specifies the accuracy of the altitude estimate in meters.

coords.heading

Number

[Optional] Specifies the device’s current direction of movement in degrees counting clockwise relative to true north.

coords.speed

Number

[Optional] Specifies the device’s current ground speed in meters per second.

timestamp

date

Specifies the time when the location information was retrieved and the Position object created.

下面是一个示例代码,它利用了位置对象。在这里,showLocation 方法是一个回调方法:

Following is a sample code which makes use of position object. Here showLocation method is a callback method:

function showLocation( position ) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;
  ...
}

Handling Errors

地理位置很复杂,很有必要抓住任何错误并巧妙地处理它。

Geolocation is complicated, and it is very much required to catch any error and handle it gracefully.

地理位置方法 getCurrentPosition() 和 watchPosition() 利用了报错处理回调方法,该方法给出了位置错误对象。这个对象有以下两个属性:

The geolocation methods getCurrentPosition() and watchPosition() make use of an error handler callback method which gives PositionError object. This object has following two properties:

Property

Type

Description

code

Number

Contains a numeric code for the error.

message

String

Contains a human-readable description of the error.

下表描述了在位置错误对象中返回的错误代码。

The following table describes the possible error codes returned in the PositionError object.

Code

Constant

Description

0

UNKNOWN_ERROR

The method failed to retrieve the location of the device due to an unknown error.

1

PERMISSION_DENIED

The method failed to retrieve the location of the device because the application does not have permission to use the Location Service.

2

POSITION_UNAVAILABLE

The location of the device could not be determined.

3

TIMEOUT

The method was unable to retrieve the location information within the specified maximum timeout interval.

以下是利用 PositionError 对象的示例代码。此处 errorHandler 方法是一种回调方法:

Following is a sample code which makes use of PositionError object. Here errorHandler method is a callback method:

function errorHandler( err ) {
   if (err.code == 1) {
      // access is denied
   }
   ...
}

Position Options

以下是 getCurrentPosition() 方法的实际语法:

Following is the actual syntax of getCurrentPosition() method:

getCurrentPosition(callback, ErrorCallback, options)

这里的第三个参数是 PositionOptions 对象,它指定了一组用于检索设备地理位置的选项。

Here third argument is the PositionOptions object which specifies a set of options for retrieving the geographic location of the device.

以下是可指定为第三个参数的选项:

Following are the options which can be specified as third argument:

Property

Type

Description

enableHighAccuracy

Boolean

Specifies whether the widget wants to receive the most accurate location estimate possible. By default this is false.

timeout

Number

The timeout property is the number of milliseconds your web application is willing to wait for a position.

maximumAge

Number

Specifies the expiry time in milliseconds for cached location information.

以下是一个示例代码,它演示了如何使用上述方法:

Following is a sample code which shows how to use above mentioned methods:

function getLocation() {
   var geolocation = navigator.geolocation;
   geolocation.getCurrentPosition(showLocation,
                                  errorHandler,
                                  {maximumAge: 75000});
}

Examples of HTML Geolocation API

以下是一些显示如何访问 HTML 中的地理位置的示例。

Here are some examples that shows how to access geolocation in HTML.

Get Current Location

以下代码显示了如何使用 JavaScript 和 HTML 访问设备的当前位置。

The following code shows how to access current location of your device using JavaScript and HTML.

<!DOCTYPE html>
<html>
<head>
      <title>
         Geolocation API Example
      </title>
</head>
<body>

   <h2>Geolocation API Example</h2>
   <p id="demo">
      Click the button to get your coordinates:
   </p>
   <button onclick="getLocation()">
      Show Location
   </button>

   <script>
      var x = document.getElementById("demo");

      function getLocation() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
         } else {
            x.innerHTML =
            "Geolocation is not supported by this browser.";
         }
      }

      function showPosition(position) {
         x.innerHTML = "Latitude: " + position.coords.latitude +
         "<br>Longitude: " + position.coords.longitude;
      }

   </script>

</body>
</html>

Error Handling in Geolocation

以下代码显示了如何在用户访问位置时处理潜在的错误。

Following code shows how to handle potential errors while accessing location from user.

<!DOCTYPE html>
<html>
<head>
      <title>Geolocation API Example</title>
</head>

<body>
   <h2>Geolocation API Example</h2>
   <p id="demo">
      Turn off location service of your device,
      See how the error is handled.
   </p>
   <button onclick="getLocation()">
      Show Location
   </button>

   <script>
      var x = document.getElementById("demo");

      function getLocation() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
         } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
         }
      }

      function showPosition(position) {
         x.innerHTML = "Latitude: " + position.coords.latitude +
         "<br>Longitude: " + position.coords.longitude;
      }

      function showError(error) {
         switch(error.code) {
            case error.PERMISSION_DENIED:
                  x.innerHTML =
                  "User denied the request for Geolocation.";
                  break;
            case error.POSITION_UNAVAILABLE:
                  x.innerHTML =
                  "Location information is unavailable.";
                  break;
            case error.TIMEOUT:
                  x.innerHTML =
                  "The request to get user location timed out.";
                  break;
            case error.UNKNOWN_ERROR:
                  x.innerHTML =
                  "An unknown error occurred.";
                  break;
         }
      }
   </script>

</body>
</html>

Supported Browsers