微信小程序大熱,在小程序過程中,我們很多時候都會用到地圖。不管是企業的地址,還是商家的配送都會用到地圖;
我在剛寫地圖這一塊時,在網上也參考了很多網友的方法,始終有Bug(類似於地圖拖拽是畫面抖動,無法點擊跳轉到導航頁面等等)
下面的代碼是后台動態添加坐標(經度緯度的方法)
我這里有這么一個方法,希望對你有用:
wxml:
<map bindtap="toMap" showLocation id="map" latitude="{{latitude}}" longitude="{{longitude}}" markers="{{markers}}" scale="14"> </map>
js:
var requetNet = require('../../common/js/request.js'); var app = getApp() Page({ data: { companyMessage: [], latitude: 0, longitude: 0, markers: [{ iconPath: "../../images/consult/ic_position.png", latitude: 0, longitude: 0, width: 17, height: 35 }], form_info:[] }, onLoad: function(t) { var that = this; requetNet.send({ url: '/enterprise/info/getRelationInfo.json', opt: { loading: true }, success: function(res) { var companyMessage = res.data; that.setData({ companyMessage: companyMessage, latitude: res.data.addressLatitude, longitude: res.data.addressLongitude, }); var markers = that.data.markers; markers[0].latitude = res.data.addressLatitude; markers[0].longitude = res.data.addressLongitude; that.setData({ markers: markers }); } }); }, toMap: function() { var companyMessage = this.data.companyMessage; wx.openLocation({ latitude: Number(companyMessage.addressLatitude), longitude: Number(companyMessage.addressLongitude), name: companyMessage.addressInfo, scale: 15 }); } })
request.js
var app; function requestNet(par) { if (!app) app = getApp(); wx.getStorage({ key: 'openId', success: function(res) { var openId = ""; if (res.data && res.data.openId) openId = res.data.openId; startReq(par, openId); }, fail: function() { startReq(par, ""); } }); } function startReq(par, openId) { var data = par.data || {}; try { data.openId = openId; } catch (e) {} var opt = par.opt; if (opt && opt.loading === true) { wx.showLoading({ title: '加載中', mask: true }); } wx.request({ url: app.globalData.url + par.url, data: data, header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 'applicationType': app.globalData.applicationType || "" }, method: 'POST', success: function(res) { wx.hideLoading(); if (res.statusCode != 200) { wx.showToast({ title: "網絡連接失敗", icon: 'none', duration: 2000 }); return; } res = res.data; var success = par.success; var code = res.code; if (opt && opt.mustOK === false) { success && success(res); return; } if (code == 200) { success && success(res); return; } wx.showToast({ title: res.msg || "提示", icon: 'none', duration: 2000 }); }, fail: function() { wx.hideLoading(); var fail = par.fail; if (fail) { fail && fail(); } else { wx.showToast({ title: "網絡連接錯誤,請檢查網絡", icon: 'none', duration: 2000 }); } }, complete: function() { } }); } module.exports = { send: requestNet }
wxss
#map { width: 100%; height: 350rpx; }
有不妥的地方,請指出!
未經作者同意,不得轉載或者復制!