微信小程序 開發MAP(地圖)實例詳解
在創建MAP(地圖)前,請各位小伙伴們認真的去了解微信小程序開發的說明。
https://mp.weixin.qq.com/debug/wxadoc/dev/component/map.html#map
了解完MAP(地圖)里的屬性之后,接下來我們就來創建一個簡單的MAP(地圖)控件。
第一步:肯定是創建項目、起項目名、項目地址
PS:我這里以index的文件為名
第二步:我們來寫 index.wxml 文件的代碼
WXML文件代碼:
<map id="map4select" longitude="{{longitude}}" latitude="{{latitude}}" markers="{{markers}}" scale="20" style="width:{{map_width}}px;height:{{map_height}}px" bindregionchange="regionchange" controls="{{controls}}"> </map>WXML文件的代碼寫好之后,就要來進行第三步了。
第三步:寫 index.js 文件的代碼
var app = getApp()Page({ data: { map_width: 380 , map_height: 380 } //show current position , onLoad: function (options) { console.log(options.schedule_id); var that = this; // 獲取定位,并把位置標示出來 that.setData({ longitude: 113.324520 , latitude: 23.099994 , markers: [ { id: 0 , iconPath: "../imgs/ic_position.png" , longitude: 113.324520 , latitude: 23.099994 , width: 30 , height: 30 } ] }) //set the width and height // 動態設置map的寬和高 wx.getSystemInfo({ success: function (res) { console.log(res.windowWidth); that.setData({ map_width: res.windowWidth , map_height: res.windowWidth , controls: [{ id: 1, iconPath: '../imgs/ic_location.png', position: { left: res.windowWidth / 2 - 8 , top: res.windowWidth / 2 - 16 , width: 30, height: 30 }, clickable: true }] }) } }) } //獲取中間點的經緯度,并mark出來 , getLngLat: function () { var that = this; this.mapCtx = wx.createMapContext("map4select"); this.mapCtx.getCenterLocation({ success: function (res) { that.setData({ longitude: 113.324520 , latitude: 23.099994 , markers: [ { id: 0 , iconPath: "../imgs/ic_position.png" , longitude: 113.324520 , latitude: 23.099994 , width: 30 , height: 30 } ] }) } }) } , regionchange(e) { // 地圖發生變化的時候,獲取中間點,也就是用戶選擇的位置 if (e.type == 'end') { this.getLngLat() } } , markertap(e) { console.log(e) }})index.js 和 index.wxml 兩個文件的代碼已經寫好,那么我們就來頁面上看看效果。
PS:“../imgs/ic_position.png” 和 “../imgs/ic_location.png” 是我在項目里創建的一個名叫imgs文件夾里面的兩個定位小圖標,各位小伙伴們可以根據自己的需求改換小圖標,只需要把小圖標放進imgs文件夾里面,小圖標的路徑引用正確就可以顯示出來。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答