GeolocationCoordinates: longitude 属性
GeolocationCoordinates 接口的只读属性 longitude 是一个数字,表示地理位置的经度,以十进制度表示。结合表示测量时间的 Unix 时间戳(毫秒),GeolocationCoordinates 对象是 接口的一部分,该接口是 Geolocation API 函数返回的地理位置信息的对象类型。GeolocationPosition
值
longitude 中的值是 Coordinates 对象所描述的地球上位置的地理经度,以十进制度表示。该值由世界大地测量系统 1984 (WGS 84) 规范定义。
注意:零子午线(也称为本初子午线或参考子午线)与大多数人认为的格林威治子午线并不完全相同。它实际上是 国际地球自转参考系参考子午线 (IERS Reference Meridian),它位于格林威治子午线以东 5.3 角秒(102 米 / 335 英尺)。这是 全球定位系统 (GPS) 使用的相同标准。
示例
在这个简单的示例中,我们获取用户的位置,并在坐标返回后显示它们。
JavaScript
下面的 JavaScript 代码创建了一个事件监听器,以便在用户点击按钮时,检索并显示位置信息。
let button = document.getElementById("get-location");
let latText = document.getElementById("latitude");
let longText = document.getElementById("longitude");
button.addEventListener("click", () => {
navigator.geolocation.getCurrentPosition((position) => {
let lat = position.coords.latitude;
let long = position.coords.longitude;
latText.innerText = lat.toFixed(2);
longText.innerText = long.toFixed(2);
});
});
在设置了方便引用按钮元素以及将要显示纬度和经度的两个元素的变量后,通过在 <button> 元素上调用 addEventListener() 来建立事件监听器。当用户点击按钮时,我们将获取并显示位置信息。
在接收到 click 事件后,我们调用 getCurrentPosition() 来请求设备当前的位置。这是一个异步请求,因此我们提供一个回调函数,该函数接收一个描述已确定位置的 GeolocationPosition 对象作为输入。
从 GeolocationPosition 对象中,我们使用 position.coords.latitude 和 position.coords.longitude 获取用户的纬度和经度,以便更新显示坐标。在将这两个 <span> 元素转换为保留两位小数的值后,更新它们以显示相应的值。
HTML
用于展示结果的 HTML 如下所示:
<p>
Your location is <span id="latitude">0.00</span>° latitude by
<span id="longitude">0.00</span>° longitude.
</p>
<button id="get-location">Get My Location</button>
结果
在此处试用此示例
规范
| 规范 |
|---|
| Geolocation # latitude-longitude-and-accuracy-attributes |
浏览器兼容性
加载中…
另见
- 使用 Geolocation API
- 它所属的
GeolocationCoordinates接口。 接口,这是 Geolocation API 函数GeolocationPositionGeolocation.getCurrentPosition()和watchPosition()返回地理位置数据的顶层接口。