{"id":19069584,"url":"https://github.com/srect/taro_wx","last_synced_at":"2026-05-17T04:30:16.149Z","repository":{"id":114173138,"uuid":"424175761","full_name":"sRect/taro_wx","owner":"sRect","description":"taro微信小程序","archived":false,"fork":false,"pushed_at":"2022-02-25T01:41:19.000Z","size":188,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-02T15:45:21.663Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sRect.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-11-03T10:14:19.000Z","updated_at":"2021-11-04T08:24:36.000Z","dependencies_parsed_at":null,"dependency_job_id":"0cb31af9-3ef3-4d3e-a556-2606090c8bcc","html_url":"https://github.com/sRect/taro_wx","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sRect%2Ftaro_wx","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sRect%2Ftaro_wx/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sRect%2Ftaro_wx/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sRect%2Ftaro_wx/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sRect","download_url":"https://codeload.github.com/sRect/taro_wx/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240122573,"owners_count":19751142,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-09T01:14:50.068Z","updated_at":"2026-05-17T04:30:16.115Z","avatar_url":"https://github.com/sRect.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"## 微信小程序持续获取定位测试\n\n\u003e 文章内使用 Tarojs 开发微信小程序\n\n### 1. 客户端详情\n\n- 手机型号：小米 10\n- 操作系统及版本：Android 10\n- 客户端平台：android\n- SDKVersion：2.20.2\n\n### 2. 注意点\n\n1. taro 项目配置文件`src/app.config.js`中要添加以下配置\n\n```javascript\nexport default {\n  requiredBackgroundModes: [\"location\"],\n  permission: {\n    \"scope.userLocation\": {\n      desc: \"如实填写实际用途\", // 高速公路行驶持续后台定位\n    },\n  },\n};\n```\n\n2. 检查手机是否打开位置信息开关\n\n```javascript\nTaro.getSystemInfoAsync({\n  success(data) {\n    console.log(data.locationEnabled);\n  },\n});\n```\n\n3. 检查是否给微信开了定位权限\n\n```javascript\nTaro.getSystemInfoAsync({\n  success(data) {\n    console.log(data.locationAuthorized);\n  },\n});\n```\n\n4. 检查当前小程序是否开了后台定位权限\n\n```javascript\nTaro.getSetting({\n  success(res) {\n    const authSetting = res.authSetting;\n    if (\n      !authSetting[\"scope.userLocation\"] ||\n      !authSetting[\"scope.userLocationBackground\"]\n    ) {\n      // 让用户在弹出的选项中务必勾选“使用小程序期间和离开小程序之后”选项\n      Taro.openSetting();\n    }\n  },\n});\n```\n\n### 3. 完整代码\n\n```jsx\nimport React, { useState } from \"react\";\nimport Taro, { useReady, useDidShow, useDidHide } from \"@tarojs/taro\";\nimport { View, Map } from \"@tarojs/components\";\n\nconst hasOwnProperty = (obj, key) =\u003e {\n  return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nconst HandleLocation = () =\u003e {\n  const [systemSetting, setSystemSetting] = useState({});\n  const [location, setLocation] = useState({ longitude: \"\", latitude: \"\" });\n  const [locationList, setLocationList] = useState([]);\n\n  const handleGetLocation = () =\u003e {\n    if (Taro.canIUse(\"startLocationUpdateBackground\")) {\n      // https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/authorize.html\n      // 小程序全局配置\n      // https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html#permission\n      // wx.authorize({scope: \"scope.userInfo\"})，不会弹出授权窗口，请使用 \u003cbutton open-type=\"getUserInfo\"/\u003e\n      // 需要授权 scope.userLocation、scope.userLocationBackground 时必须配置地理位置用途说明\n\n      Taro.startLocationUpdateBackground({\n        success() {\n          Taro.onLocationChange((data) =\u003e {\n            setLocationList((pre) =\u003e [...pre, data]);\n\n            setLocation({ longitude: data.longitude, latitude: data.latitude });\n\n            // ajax发送数据到后台\n            // ...\n          });\n        },\n        fail(err) {\n          console.log(err);\n          Taro.showToast({\n            icon: \"error\",\n            title: \"定位失败\",\n          });\n\n          Taro.openSetting();\n        },\n      });\n    } else {\n      Taro.showToast({\n        icon: \"error\",\n        title: \"您的设备暂不支持定位\",\n      });\n    }\n  };\n\n  // 检查手机是否打开位置信息开关\n  // 检查是否给微信开了定位权限\n  const checkMobileLocationAuth = () =\u003e {\n    return new Promise((resolve, reject) =\u003e {\n      Taro.getSystemInfoAsync({\n        success(data) {\n          setSystemSetting(data);\n\n          if (\n            data \u0026\u0026\n            hasOwnProperty(data, \"locationEnabled\") \u0026\u0026\n            !data.locationEnabled\n          ) {\n            Taro.showModal({\n              title: \"提示\",\n              content: \"请打开手机设置-位置信息(GPS)开关\",\n              confirmText: \"确定\",\n              showCancel: false,\n            });\n\n            reject();\n          }\n\n          if (\n            data \u0026\u0026\n            hasOwnProperty(data, \"locationAuthorized\") \u0026\u0026\n            !data.locationAuthorized\n          ) {\n            Taro.showModal({\n              title: \"提示\",\n              content:\n                \"请打开手机设置-应用设置-应用管理-微信-权限管理-定位权限开关\",\n              confirmText: \"确定\",\n              showCancel: false,\n              success() {\n                // Taro.openSetting();\n              },\n            });\n\n            reject();\n          }\n\n          resolve();\n        },\n        fail() {\n          reject();\n        },\n      });\n    });\n  };\n\n  // 检查当前小程序是否开了定位权限\n  const checkMiniAppLocationAuth = () =\u003e {\n    return new Promise((resolve, reject) =\u003e {\n      if (!Taro.canIUse(\"getSetting\")) return reject();\n\n      Taro.getSetting({\n        success: function (res) {\n          const authSetting = res.authSetting;\n\n          if (\n            authSetting \u0026\u0026\n            hasOwnProperty(authSetting, \"scope.userLocation\") \u0026\u0026\n            hasOwnProperty(authSetting, \"scope.userLocationBackground\") \u0026\u0026\n            authSetting[\"scope.userLocation\"] \u0026\u0026\n            authSetting[\"scope.userLocationBackground\"]\n          ) {\n            resolve();\n          } else {\n            if (Taro.canIUse(\"openSetting\")) {\n              Taro.showModal({\n                title: \"提示\",\n                content:\n                  \"请在点击确定后，在弹出的选项中务必勾选“使用小程序期间和离开小程序之后”选项\",\n                confirmText: \"确定\",\n                showCancel: false,\n                success() {\n                  Taro.openSetting();\n                },\n              });\n            } else {\n              Taro.showModal({\n                title: \"提示\",\n                content:\n                  \"请点击右上角“...”更多-设置-位置信息，在弹出的选项中务必勾选“使用小程序期间和离开小程序之后”选项\",\n                confirmText: \"确定\",\n                showCancel: false,\n              });\n            }\n\n            reject();\n          }\n        },\n      });\n    });\n  };\n\n  useReady(() =\u003e {\n    console.log(\"useReady==\u003e\");\n  });\n\n  useDidShow(() =\u003e {\n    console.log(\"useDidShow==\u003e\");\n    if (Taro.canIUse(\"stopLocationUpdate\")) {\n      Taro.stopLocationUpdate({\n        complete() {\n          checkMobileLocationAuth()\n            .then(checkMiniAppLocationAuth)\n            .then(() =\u003e {\n              // 全部ok，可以进行持续定位\n              handleGetLocation();\n            })\n            .catch(() =\u003e {\n              console.log(\"err==\u003e\");\n            });\n        },\n      });\n    }\n  });\n\n  useDidHide(() =\u003e {\n    console.log(\"useDidHide==\u003e\");\n  });\n\n  return (\n    \u003cView\u003e\n      \u003cMap\n        style=\"width: 100%; height: 200px;\"\n        scale={16}\n        longitude={location.longitude}\n        latitude={location.latitude}\n      /\u003e\n    \u003c/View\u003e\n  );\n};\n```\n\n### 4. 实际测试\n\n- 经过本地开发实际测试，把小程序切到后台后，切换到其他 app\n- 或者手机直接锁屏\n\n以上两种情况，1 分钟后，`startLocationUpdateBackground`api 即失效，只有重新解锁手机，重新回到微信，api 的实时位置监控才被唤醒，尚未找到解决方法\n\n### 5. 其他\n\n钉钉小程序`dd.getLocation`只有当前钉钉小程序当前在激活状态下可以获取到，切换到后台和手机锁屏后，即失效\n\n### 6. 参考资料\n\n1. [微信小程序授权](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/authorize.html)\n2. [微信小程序全局配置](https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html#permission)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsrect%2Ftaro_wx","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsrect%2Ftaro_wx","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsrect%2Ftaro_wx/lists"}