本文編輯: Mirror瀏覽 7244
版權所有,嚴禁轉載
注: 上圖所演示的是頁面加載完成后用map標簽顯示用戶當前位置,當點擊按鈕時跳轉至微信地圖顯示用戶當前位置。
<view>
<button type="primary" bindtap="showLocation">獲取當前地理位置并在地圖中打開</button>
</view>
<map longitude="{{location.longitude}}" latitude="{{location.latitude}}" markers="{{markers}}" covers="{{covers}}"></map>
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并將位置信息綁定到了變量中。
button {
width: 700rpx;
margin: 200rpx auto 0 auto;
}
map {
width: 700rpx;
height: 600rpx;
margin: 30rpx auto;
}
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,成功為getLocation:ok |
OBJECT參數說明
參數名稱 | 數據類型 | 必填 | 說明 |
---|---|---|---|
latitude | Float | 是 | 緯度,范圍為-90~90,負數表示南緯 |
longitude | Float | 是 | 經度,范圍為-180~180,負數表示西經 |
scale | INT | 否 | 縮放比例,范圍1~28,默認為28 |
name | String | 否 | 位置名(可自行定義) |
address | String | 否 | 地址的詳細說明(可自行定義) |
success | Function | 否 | 接口調用成功的回調函數 |
fail | Function | 否 | 接口調用失敗的回調函數 |
complete | Function | 否 | 接口調用結束的回調函數(調用成功、失敗都會執行) |