此文為筆者初次嘗試map組件后的學習筆記访雪,由于筆者功力有限,如有不足坝橡,還望指教
-
參考資料:
map組件
map組件相關api效果圖:
image
直接上代碼(其中有我個人理解的注釋):
- wxml
<view class="page-body">
<view class="page-section page-section-gap">
<map
id="myMap"
style="width: 100%; height: 300px;"
latitude="{{latitude}}"
longitude="{{longitude}}"
markers="{{markers}}"
show-location
></map>
</view>
<view class="btn-area">
<button bindtap="getCenterLocation" class="page-body-button" type="primary">定位到當前位置</button>
<button bindtap="translateMarker" class="page-body-button" type="primary">移動標注到指定位置</button>
<button bindtap="includePoints" class="page-body-button" type="primary">縮放視野展示所有經(jīng)緯度</button>
<button bindtap="getRegion" class="page-body-button" type="primary">獲取當前位置視野范圍</button>
</view>
</view>
- wxss
page {
background-color: #f8f8f8;
height: 100%;
font-size: 32rpx;
line-height: 1.6;
}
.page-body {
padding: 20rpx 0;
}
.page-section-gap {
box-sizing: border-box;
padding: 0 30rpx;
}
.btn-area {
margin-top: 60rpx;
box-sizing: border-box;
width: 100%;
padding: 0 30rpx;
}
.page-body-button {
margin-bottom: 30rpx;
}
- javascript
Page({
data: {
//緯度
latitude: 30.319739999999985,
//經(jīng)度
longitude: 112.222,
//標記點
markers: [{
//標記點 id
id: 1,
//標記點緯度
latitude: 32.319739999999985,
//標記點經(jīng)度
longitude: 120.14209999999999,
name: '行之當前的位置'
}],
},
onReady: function (e) {
//獲取map上下文
//參數(shù):
//string mapId
//Object this
this.mapCtx = wx.createMapContext('myMap')
},
//獲取當前位置經(jīng)緯度脂倦,并把定位到相應的位置
getCenterLocation: function () {
//獲取當前位置:經(jīng)緯度
this.mapCtx.getCenterLocation({
success:res=>{
//獲取成功后定位到相應位置
console.log(res);
//參數(shù)對象中設置經(jīng)緯度狼讨,我這里設置為獲取當前位置得到的經(jīng)緯度值
this.mapCtx.moveToLocation({
longitude:res.longitude,
latitude:res.latitude
})
}
})
},
//移動標記(marker)到指定位置
translateMarker: function() {
//平移marker
this.mapCtx.translateMarker({
//要平移的marker的id
markerId: 1,
//移動過程中是否自動旋轉 marker
autoRotate: true,
//動畫持續(xù)時長政供,平移與旋轉分別計算
duration: 1000,
//平移到的目的地,參數(shù)為經(jīng)緯度
destination: {
latitude:33,
longitude:113.3345211,
},
//平移動畫后的回調函數(shù)
animationEnd() {
console.log('動畫結束')
}
})
},
//縮放視野展示所有經(jīng)緯度
includePoints: function() {
this.mapCtx.includePoints({
//坐標點形成的矩形邊緣到地圖邊緣的距離离陶,單位像素招刨。
padding: [10],
//有哪些要縮放的點
points: [{
latitude:23.10229,
longitude:113.3345211,
}, {
latitude:24.00229,
longitude:113.545211,
}],
success:res=>{
console.log("縮放成功")
}
})
},
//獲取當前位置視野范圍
getRegion:function(){
this.mapCtx.getRegion({
success:res=>{
//東北角經(jīng)緯度
console.log(res.northeast);
//西南角經(jīng)緯度
console.log(res.southwest);
}
})
}
})
以上就是筆者對map組件的初次嘗試了沉眶。