You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PhoneGap中使用cordova-plugin-mauron85-background-geolocation显示经纬度问题

解决cordova-plugin-mauron85-background-geolocation的经纬度获取问题

嘿,我来帮你理清这个插件里经纬度的存储位置,顺便修正你代码里的小问题!

首先明确:这个插件的位置数据都包含在**Location对象**里,你可以直接通过以下属性获取经纬度:

  • 纬度:location.latitude
  • 经度:location.longitude

下面针对你代码里的问题逐一修正:

1. 修正pos()函数

你的pos函数里回调参数命名为locations容易误解(其实是单个位置对象),而且缺少错误处理,修正后:

function pos() {
  alert("start pos function")
  BackgroundGeolocation.getCurrentLocation(
    // 回调参数是单个Location对象,命名为location更准确
    function (location) {
      alert(`纬度: ${location.latitude}, 经度: ${location.longitude}`);
    },
    // 加上错误回调,方便排查问题
    function(error) {
      alert(`获取位置失败: ${error.message}`);
    },
    // 可选配置:提高精度、设置超时
    {
      enableHighAccuracy: true,
      timeout: 10000
    }
  );
}

2. 修正stats()函数

这里你误用了标准HTML5 Geolocation API的coords属性,但这个插件的getCurrentLocation返回的Location对象是直接包含latitude和longitude的,不需要通过coords访问,同时你还存在options未定义、错误使用watchID的问题,修正后:

function stats() {
  BackgroundGeolocation.checkStatus();
  BackgroundGeolocation.getCurrentLocation(onSuccess, onError, {
    enableHighAccuracy: true,
    timeout: 10000
  });
  
  function onSuccess(location) {
    // 直接访问location.latitude和location.longitude
    const lat = location.latitude;
    const long = location.longitude;
    alert(`当前经度: ${long}`);
    alert(`当前纬度: ${lat}`);
  }
  
  function onError(error) {
    alert('GPS获取失败: ' + error.message);
  }
}

3. 后台定位时获取经纬度

如果你想在后台定位更新时alert经纬度(注意:iOS后台alert可能不显示,建议用日志或通知),可以在location事件回调里直接使用:

BackgroundGeolocation.on('location', function(location) {
  // 直接获取经纬度并alert
  alert(`后台位置更新:纬度${location.latitude},经度${location.longitude}`);
  
  // 保留原有的后台任务代码
  BackgroundGeolocation.startTask(function(taskKey) {
    // 这里可以做一些耗时操作,比如上传位置
    BackgroundGeolocation.endTask(taskKey);
  });
});

另外提醒下:debug模式下你可以通过控制台日志(console.log)查看位置数据,比alert更方便哦!

内容的提问来源于stack exchange,提问作者guzmange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:00:59