地理位置用于获取有关设备的纬度和经度的信息。
步骤1 - 安装插件
我们可以通过在命令提示符窗口中键入以下代码来安装此插件。
- C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-geolocation
步骤2 - 添加按钮
在本教程中,我们将向您展示如何获取当前位置以及如何监视更改。我们首先需要创建将调用这些函数的按钮。
- <button id = "getPosition">CURRENT POSITION</button>
- <button id = "watchPosition">WATCH POSITION</button>
步骤3 - 添加事件监听器
现在我们要在设备准备就绪时添加事件监听器。我们将下面的代码示例添加到 index.js 中的 onDeviceReady 函数。
- document.getElementById("getPosition").addEventListener("click", getPosition);
- document.getElementById("watchPosition").addEventListener("click", watchPosition);
步骤3 - 创建函数
需要为两个事件侦听器创建两个函数。一个用于获取当前位置,另一个用于查看位置。
- function getPosition() {
- var options = {
- enableHighAccuracy: true,
- maximumAge: 3600000
- }
- var watchID = navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
- function onSuccess(position) {
- alert('Latitude: ' + position.coords.latitude + '\n' +
- 'Longitude: ' + position.coords.longitude + '\n' +
- 'Altitude: ' + position.coords.altitude + '\n' +
- 'Accuracy: ' + position.coords.accuracy + '\n' +
- 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
- 'Heading: ' + position.coords.heading + '\n' +
- 'Speed: ' + position.coords.speed + '\n' +
- 'Timestamp: ' + position.timestamp + '\n');
- };
- function onError(error) {
- alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
- }
- }
- function watchPosition() {
- var options = {
- maximumAge: 3600000,
- timeout: 3000,
- enableHighAccuracy: true,
- }
- var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
- function onSuccess(position) {
- alert('Latitude: ' + position.coords.latitude + '\n' +
- 'Longitude: ' + position.coords.longitude + '\n' +
- 'Altitude: ' + position.coords.altitude + '\n' +
- 'Accuracy: ' + position.coords.accuracy + '\n' +
- 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
- 'Heading: ' + position.coords.heading + '\n' +
- 'Speed: ' + position.coords.speed + '\n' +
- 'Timestamp: ' + position.timestamp + '\n');
- };
- function onError(error) {
- alert('code: ' + error.code + '\n' +'message: ' + error.message + '\n');
- }
- }
在上面的例子中,我们使用两个方法 - getCurrentPosition和watchPosition。两个函数都使用三个参数。一旦我们单击“当前位置"按钮,该警报将显示地理位置值。

如果我们点击 WATCH POSITION 按钮,每三秒钟就会触发相同的提醒。 这样我们可以跟踪用户设备的移动变化。
注意
此插件使用GPS。有时它不能按时返回值,并且请求将返回超时错误。这就是为什么我们指定 enableHighAccuracy:true 和 maximumAge:3600000 的原因。 这意味着如果请求没有按时完成,我们将使用最后一个已知的值。在我们的示例中,我们将maximumAge设置为3600000毫秒。
转载本站内容时,请务必注明来自W3xue,违者必究。