今天弄了下微信小程序里获取当前位置。
首先有一个官方的demo,但是这个demo里只有获取当前位置的经度和纬度坐标。不是我想要的,我要的是一般地图里那种点击button地图上定位到我的当前位置。百度了一下,然后自己尝试了一下,代码如下。
index.wxml里没什么,<map>标签直接copy官方demo里的即可。
<view class="page-body">
<view>
<map id="map"
longitude="{{longitude}}"
latitude="{{latitude}}"
scale="14"
controls="{{controls}}"
bindcontroltap="controltap"
markers="{{markers}}"
bindmarkertap="markertap"
polyline="{{polyline}}"
bindregionchange="regionchange"
show-location
style="width: 100%; height: 300px;">
</map>
</view>
<view class="usermotto">
<text class="user-motto">{{motto}}</text>
<button bindtap="getCenterLocation" type="primary">获取位置</button>
<text >经度:{{longitude}}</text>
<text >纬度:{{latitude}}</text>
</view>
</view>
index.js里,主要就是调到wx.getLocation来实现的。
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
motto: 'Hello World',
latitude: 30.560385546235004,
longitude: 114.19691428542137,
markers: [{
id: 1,
iconPath: '/image/location.png',
latitude: 30.560385546235004,
longitude: 114.19691428542137,
name: '中铁国际城',
callout: { content : '中铁国际城'}
}],
controls: [
{
id: 1,
iconPath: '/image/location.png',
position: {
top: 300 - 50,
width: 30,
height: 30
},
clickable: true
}
]
},
//事件处理函数
onReady: function (e) {
this.mapCtx = wx.createMapContext('map')
},
getCenterLocation: function () {
var that = this;
this.mapCtx.getCenterLocation({
success: function (res) {
console.log(res.longitude)
console.log(res.latitude)
that.setData({
latitude: res.latitude,//纬度
longitude: res.longitude,//经度
})
}
})
},
controltap(e) {
var that = this;
wx.getLocation({
type: 'gcj02', //返回可以用于wx.openLocation的经纬度
success: function (res) {
var latitude = res.latitude
var longitude = res.longitude
that.setData({
latitude: latitude,//纬度
longitude: longitude,//经度
})
}
})
}
})