# uni.getLocation(OBJECT)

Get the current location and speed.

注意

Web平台本API之前调用了腾讯地图的gcj02坐标免费转换接口,该接口从2024年7月18日起被腾讯逐步下线,导致老版本中本API无法使用。请立即升级到 uni-app 4.24版

升级后注意:

  1. cli项目需升级cli
  2. App平台 manifest中配置好自己的地图厂商key,在地图厂商的后台,填写正确包名和证书摘要。地图厂商的sdk会在运行时校验key、包名、证书的一致性
  3. Web平台 manifest中配置好自己的地图厂商key,使用web接口如涉及白名单,需确保自己的域名在地图厂商那里正确配置了域名白名单
  4. 确保在地图厂商那里配额足够
  5. 确保在地图厂商那里有周边服务的权限。否则无法获取周围地址

如果运行在微信浏览器中,可以使用微信的jssdk的定位能力。这个是微信向腾讯地图申请的key,开发者无需配置自己的key。

地图厂商的商业授权较贵,如需购买,请点击获取优惠

# getLocation 兼容性

HarmonyOS
HBuilderX 4.25

地图服务商说明

点击查看地图服务商兼容性

OBJECT parameter description

Parameter Name Type Required Description Platform Difference Description
type String 默认为 wgs84 返回 gps 坐标,gcj02 返回国测局坐标,可用于 uni.openLocation 和 map 组件坐标,App 和 H5 需配置定位 SDK 信息才可支持 gcj02。
altitude Boolean 传入 true 会返回高度信息,由于获取高度需要较高精确度,会减慢接口返回速度 抖音小程序、飞书小程序、支付宝小程序不支持
geocode Boolean No The default is false, whether to resolve the address information Supported only by the App platform (Android needs to specify the type as gcj02 and configure the three-party positioning SDK)
highAccuracyExpireTime Number No High Accuracy Positioning Timeout Time (ms), returns the highest accuracy within the specified time, this value is more than 3000ms for high accuracy positioning to be effective App (3.2.11+), H5 (3.2.11+), WeChat MiniApp(basic library 2.9.0+)
timeout String No The default is 5, the positioning timeout, in seconds Only supported by MiniApp
cacheTimeout Number No Location cache timeout, in seconds; the current location data is cached every time, and the timestamp is recorded. When the next call is within cacheTimeout, the cached data will be returned Only Feishu MiniApp, Alipay MiniApp Support
accuracy String 默认为 high,指定期望精度,支持 high,best。当指定 high 时,期望精度值为100m,当指定 best 时期望精度值为20m。当定位得到的精度不符合条件时,在timeout之前会继续定位,尝试拿到符合要求的定位结果 仅飞书小程序支持
isHighAccuracy Boolean 开启高精度定位 App (3.4.0+)、H5 (3.4.0+)、微信小程序 (基础库 2.9.0+)、抖音小程序(2.26.0+)
success Function is the callback function for the successful call of the interface. For details, please refer to the return parameter description.
fail Function No Callback function for interface call failure
complete Function No The callback function of the end of the interface call (the call will be executed if the call succeeds or fails)

success return parameter description

Parameters Description
latitude Latitude, a floating-point number, the range is -90~90, a negative number means south latitude
longitude Longitude, a floating point number, the range is -180~180, a negative number means west longitude
speed speed, float, unit m/s
accuracy Accuracy of location
altitude Altitude in m
verticalAccuracy Vertical Accuracy, in m (unavailable for Android, returns 0)
horizontalAccuracy Horizontal Accuracy, in m
address Address information (only supported by the App, you need to configure geocode to true)

address address information description

property type description description
country String Country For example, "China", if this information cannot be obtained, return undefined
province String province name such as "Beijing", if this information cannot be obtained, return undefined
city String City name For example, "Beijing", if this information cannot be obtained, return undefined
district String District (county) name For example, "Chaoyang District", if this information cannot be obtained, return undefined
street String Street information For example, "Jiuxianqiao Road", if this information cannot be obtained, return undefined
streetNum String Get the street number information For example, "No. 3", if this information cannot be obtained, return undefined
poiName String POI information For example, "Electronic City. International Electronic Headquarters", if this information cannot be obtained, return undefined
postalCode String Postal code For example "100016", if this information cannot be obtained, return undefined
cityCode String City Code For example, "010", if this information cannot be obtained, return undefined

Example

uni.getLocation({
	type: 'wgs84',
	success: function (res) {
		console.log('当前位置的经度:' + res.longitude);
	}
});

注意事项

  • H5 Platform
    • On newer browsers, the H5 side obtains location information and requires deployment on the https service, and the local preview (localhost) can still use the http protocol.
    • On a domestic Android phone, if the H5 cannot be positioned, check whether the phone has enabled location services, GPS, whether the ROM has given the browser location permission, and whether the browser has given a positioning query box to the web page pop-up request.
    • Android phone cannot locate when the native app is embedded with H5, and the native app needs to process the Webview.
    • 移动端浏览器 普遍仅支持GPS定位,在GPS信号弱的地方可能定位失败。
    • PC 设备 使用 Chrome 浏览器的时候,位置信息是连接谷歌服务器获取的,国内用户可能获取位置信息失败,推荐使用Edge进行获取位置信息
    • WeChat public account can use WeChat js sdk, see details
    • Version 2.9.9 and above, optimize uni.getLocation to support location by IP. By default, it is obtained through GPS. If the acquisition fails, the alternative is to obtain it through IP positioning, and the secret key of the third-party map service platform needs to be filled in. key configuration: manifest.json ---> H5 configuration ---> positioning and map ---> key.
  • App Platform
    • Android is blocked by Google services, or there is no GMS on the mobile phone. If you want to locate normally, you need to apply for an SDK qualification from a third-party service provider such as AutoNavi and obtain an AppKey. Otherwise, the positioning will be inaccurate after packaging. When cloud packaging, you need to fill in the Appkey in the SDK configuration of the manifest. There are detailed application guidelines on the manifest visual interface, see: https://ask.dcloud.net.cn/article/29. Offline packaging is configured in the native project by itself. Note that package name, appkey, and certificate information must match. The real machine running can be positioned normally because the real machine running base uses the sdk configuration that DCloud applied to AutoNavi, which must be applied by the developer after packaging. If the mobile phone comes with GMS and the network environment can access the google positioning server normally, there is no need to fill in the sdk configuration of Gaode positioning in the manifest.
    • Note that the mobile phone itself must enable positioning, and at the same time give the App the positioning permission. Permission judgment can refer to: https://uniapp.dcloud.net.cn/api/system/getappauthorizesetting.html
    • The <map> component defaults to the coordinate gcj02 of the National Survey Bureau. When calling uni.getLocation to return the result to the <map> component, you need to specify the type as gcj02.
    • Positioning and map are two things. After getting the location coordinates through getLocation, it can be displayed on any map map, such as positioning using Gaode, and the map using google's webview version of the map. If the coordinate system is different, pay attention to converting the coordinate system.
    • If you use web-view to load the map, there is no need to configure the sdk configuration of the map in the manifest.
    • 持续定位方案:iOS端可以申请持续定位权限,参考。Android如果进程被杀,代码无法执行,可以在插件市场搜索保活相关原生语言插件避免App被系统杀死。即使使用了原生语言插件保活,也很容易被杀,此时可以使用unipush ,通过推送消息提示用户激活App
    • 3.3.0 版本以上 优化系统定位模块,可不使用三方定位SDK的进行高精度定位,具体参考:系统定位
    • 鸿蒙系统 不支持系统定位,需要配置三方sdk,比如高德,同时设置坐标系参数为 type: 'gcj02'
    • Android/iOS平台使用腾讯定位SDK需到 腾讯位置服务 官网申请应用Key并配置:
      • 4.31 版本及以上 HBuilderX内置支持腾讯定位,在manifest.json勾选配置,详情参考Geolocation定位
      • 4.31 版本之前 可下载腾讯定位插件,在插件中配置key打包后生效,腾讯定位是ext api插件引用到工程后,会覆盖uni.getLocation的实现,替换掉系统定位。
  • MiniApp Platform
    • The api does not return the Chinese description of the detailed address by default. There are two ways to need a Chinese address: 1. Using the AutoNavi map MiniApp sdk, you can get a Chinese address on the app and WeChat, Reference. 2. Only consider the app, you can also use plus.geolocation to get the Chinese address. The App SDK configuration in the manifest isonly used for the app, and the MiniApp not need to be configured here.
    • The user authorization API can be used to determine whether the user has granted the application location permission, see details
    • 微信小程序 中,当用户离开应用后,此接口无法调用,需要申请 后台持续定位权限 ,另外新版本中需要使用 wx.onLocationChange 监听位置信息变化;当用户点击“显示在聊天顶部”时,此接口可继续调用。
  • HarmonyOS Next平台调用此 API 需要申请定位权限ohos.permission.APPROXIMATELY_LOCATIONohos.permission.LOCATION,需自行在项目中配置权限。具体位置在 harmony-configs/entry/src/main/module.json5 中的 requestPermissions 字段。该配置文件在构建产物中原始鸿蒙工程相同目录内。
  • 如果在app模块中勾选了系统定位和其他定位,比如腾讯定位,由配置的type值决定调用规则,type值为wgs84使用系统定位,type值为gcj02则使用腾讯定位。

# uni.chooseLocation(OBJECT)

打开地图选择位置。chooseLocation会使用项目配置的地图服务商来展示地图,地图服务商支持情况参考:map组件

注意

Web平台和App平台,本API之前调用了腾讯地图的gcj02坐标免费,该接口从2024年7月18日起被腾讯逐步下线,导致老版本中本API无法使用。请立即升级到 uni-app 4.24版

升级后注意:

  1. 如果是cli或离线打包,需要配套升级cli和离线sdk
  2. manifest中配置好自己的地图厂商key。web和app都需要。一般标准基座正常,自定义基座和打包后异常,都是这个原因
  3. 确保在地图厂商那里配额足够
  4. 确保在地图厂商那里有周边服务的权限。否则无法获取周围地址
  5. web平台确保自己的域名在地图厂商那里正确配置了域名白名单

地图厂商的商业授权较贵,如需购买,请点击获取优惠

Platform Difference Description

App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 京东小程序 元服务
x x x

# chooseLocation 兼容性

HarmonyOS
HBuilderX 4.23

地图服务商说明

点击查看地图服务商兼容性

OBJECT parameter description

Parameter Name Type Required Description Platform Difference Description
latitude Number No Destination latitude WeChat MiniApp(2.9.0+), H5-Vue3 (3.2.10+)
longitude Number No Destination longitude WeChat MiniApp(2.9.0+), H5-Vue3 (3.2.10+)
keyword String 搜索关键字,仅App平台支持
useSecureNetwork Boolea 是否通过安全网络调用地点搜索、逆地址解析,默认false
success Function is the callback function for the successful call of the interface. For details, please refer to the return parameter description.
fail Function No The callback function of the failed API call (triggered when the location fails to be acquired, the user cancels, etc.)
complete Function No The callback function of the end of the interface call (the call will be executed if the call succeeds or fails)

腾讯地图服务商说明

出于安全考虑,安卓、iOS端manifest.json内配置的key仅用来展示地图,uni.chooseLocation所依赖的地点搜索、逆地址解析功能需要通过uniCloud云对象uni-map-co来调用,开发者可以通过安全网络来保障服务端api不被他人盗用。

鸿蒙平台由于暂不支持安全网络,所以chooseLocation依然使用manifest.json内配置的key来调用地点搜索、逆地址解析。

默认情况下,uni.chooseLocation不会使用安全网络请求uni-map-co。如果需要使用安全网络请求uni-map-co,需按如下步骤操作:

  1. 项目关联uniCloud服务空间
  2. 参考uni-map-co文档导入uni-map-common插件,并配置好地图的key。
  3. 参考安全网络文档,将应用关联到服务空间。
  4. 在项目manifest.json中安卓/iOS模块配置中勾选安全网络模块。
  5. 修改uni-map-co入口文件index.obj.js内添加如下代码,拦截非法请求:
module.exports = {
  _before: function() {
    const clientInfo = this.getClientInfo()
    const methodName = this.getMethodName()
    const secretType = clientInfo.secretType
    if(methodName === 'chooseLocation' && secretType !== 'both' && secretType !== 'request') {
      throw new Error('Unauthorized client')
    }
  }
}
  1. 上传uni-map-co云对象、uni-config-center公共模块、uni-map-common公共模块。
  2. 调用uni.chooseLocation时,将useSecureNetwork设置为true。

Notice

  • 因平台差异,如果SDK配置百度地图,需要设置 keyword,才能显示相关地点
  • 非 weex 编译模式不支持百度地图

success return parameter description

Parameters Description
name Location Name
address Detailed address
latitude Latitude, a floating-point number, the range is -90~90, a negative number represents the southern latitude, using the gcj02 National Survey Bureau coordinate system.
longitude Longitude, a floating-point number, the range is -180~180, the negative number represents the west longitude, using the gcj02 National Survey Bureau coordinate system.

Example

uni.chooseLocation({
	success: function (res) {
		console.log('位置名称:' + res.name);
		console.log('详细地址:' + res.address);
		console.log('纬度:' + res.latitude);
	}
});

Notice

  • Different terminals use different underlying map engines for map selection. For details, see map service provider support for the map map component.
    • Baidu positioning can also be used in app, configured in the manifest, and it will take effect after packaging.
    • Only AutoNavi and Google Maps (3.4+) can be used in app-nvue, but Baidu Maps cannot be used. In addition, the API for selecting a map and viewing the map location only supports AutoNavi and Google Maps (3.4+). Therefore, if there is no special need on the App side, it is recommended to use the Gaode map.
  • H5 terminal uses maps and positioning related, you need to configure the secret key (key) applied by third-party map service providers such as Tencent or Google in manifest.json.
  • WeChat js sdk can be used in WeChat built-in browser, see details
  • chooseLocation is an encapsulated API. If developers feel that it is not flexible enough, they can encapsulate it based on the original map component. The plugin market already has a variety of packaging examples.
  • Android App端 位置不准,见上文 uni.getLocation 的注意事项
  • 微信小程序在2023年10月17日之后,使用API需要配置隐私协议

# 三方定位和地图服务收费说明

使用三方定位或者地图服务,需向服务提供商(如:高德地图、百度地图、腾讯地图、谷歌地图)申请商业授权和缴纳费用(5万/年)。

DCloud为开发者争取了福利,可优惠获取高德、腾讯的商业授权。如有需求请发邮件到bd@dcloud.io(注明你的公司名称、应用介绍、HBuilder账户);你也可以直接通过uni-im发起在线咨询,在线咨询地址:DCloud地图服务专员

详见:https://uniapp.dcloud.net.cn/tutorial/app-geolocation.html#lic

# unicloud-city-select 城市选择组件

若想要实现城市选择功能,可以使用 unicloud-city-select 城市选择组件。

运行效果图

下载地址:https://ext.dcloud.net.cn/plugin?name=unicloud-city-select

文档地址:https://doc.dcloud.net.cn/uniCloud/unicloud-city-select.html

# 【福利】高德拉新活动

一键注册高德企业开发者,最高可获取210元奖励金,详见https://ask.dcloud.net.cn/article/41279