- 本节主要介绍微信小程序API中获取位置和打开位置这两个接口的使用方法,以及获取位置接口在map标签上的应用。
接口用法:
注: 上图所演示的是页面加载完成后用map标签显示用户当前位置,当点击按钮时跳转至微信地图显示用户当前位置。
wxml
- <view>
- <button type="primary" bindtap="showLocation">获取当前地理位置并在地图中打开</button>
- </view>
- <map longitude="{{location.longitude}}" latitude="{{location.latitude}}" markers="{{markers}}" covers="{{covers}}"></map>
js
- Page({
- data:{},
- onLoad:function(options){
- var _this = this;
- wx.getLocation({
- type: 'wgs84',
- success: function(res){
- var longitude = res.longitude, latitude = res.latitude;
- _this.setData({
- location: {
- latitude: latitude,
- longitude: longitude,
- },
- markers:[{
- latitude: latitude,
- longitude: longitude,
- name: '微信小程序社区',
- desc: '我在这里'
- }],
- covers: [{
- latitude: latitude,
- longitude: longitude,
- iconPath: '../images/car.png',
- rotate: 10
- }]
- });
- }
- })
- },
- showLocation: function(e) {
- var _this = this;
- var location = _this.data.location;
- wx.openLocation({
- latitude: location.latitude, // 纬度,范围为-90~90,负数表示南纬
- longitude: location.longitude, // 经度,范围为-180~180,负数表示西经
- scale: 28, // 缩放比例
- name: '微信小程序社区', // 位置名
- address: '我还是在这里' // 地址的详细说明
- });
- }
- })
注: 由于map标签所有属性的值不支持动态变化,只能在页面加载完成时设置。所以本示例中为了达到将用户位置设置到map标签的效果,在onload函数中就直接调用了wx.getLocation并将位置信息绑定到了变量中。
wxss
- button {
- width: 700rpx;
- margin: 200rpx auto 0 auto;
- }
- map {
- width: 700rpx;
- height: 600rpx;
- margin: 30rpx auto;
- }
主要方法:wx.getLocation(OBJECT)
OBJECT参数说明
参数名称
|
数据类型
|
必填
|
说明
|
type | String | 否 | 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标 |
success | Function | 是 | 接口调用成功的回调函数,返回内容详见返回参数说明。 |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
参数名称
|
数据类型
|
说明
|
latitude | Number | 纬度,浮点数,范围为-90~90,负数表示南纬 |
longitude | Number | 经度,浮点数,范围为-180~180,负数表示西经 |
errMsg | String | 接口返回的message,成功为getLocationk |
wx.openLocation(OBJECT)
OBJECT参数说明
参数名称
|
数据类型
|
必填
|
说明
|
latitude | Float | 是 | 纬度,范围为-90~90,负数表示南纬 |
longitude | Float | 是 | 经度,范围为-180~180,负数表示西经 |
scale | INT | 否 | 缩放比例,范围1~28,默认为28 |
name | String | 否 | 位置名(可自行定义) |
address | String | 否 | 地址的详细说明(可自行定义) |
success | Function | 否 | 接口调用成功的回调函数 |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |