微信小程序开发:腾讯地图集成(旧题新说)
前言
在腾讯生态开发过程中,包括微信小程序开发在内,避免不了使用腾讯送的腾讯大礼包,从微信支付到腾讯地图,一条龙式的腾讯大礼包无微不至的关怀着每一位开发者,不得不说鹅厂的实力是其他公司无可比拟的。 但是话又说回来了,鹅厂的官方API真是不敢恭维,尤其是微信小程序的开发文档,如果不熟悉的话,真的是大坑不断,连环坑不断,无力吐槽。
一、map组件的实现
首先来对map组件进行封装操作,通过结合微信地图的官方API可以直接把腾讯地图的核心内容封装到该组件里面。封装map组件分为四个部分,即四个文件,这也是基于微信小程序的独特风格。
1、homeMap.js文件
homeMap.js文件主要是封装处理关于地图的逻辑处理。
const app = getApp()
Component({
properties: {
position: {
type: Array,
value: [],
},
markers: {
type: Array,
value: [],
},
markerList: {
type: Array,
value: []
},
getCurrentElement: {
type: Function,
value: function () { }
}
},
data: {
position: [],
markerList: {},
markers: []
},
ready: function () {
const mapContext = wx.createMapContext('map')
const {
position,
markers,
markerList
} = this.properties;
this.setData({
position,
markers,
markerList,
});
mapContext.moveToLocation({
longitude: 114.54286,
latitude: 22.05956,
complete(e) {
console.log('moveToLocation', e)
}
})
},
methods: {
markertap({
markerId
}) {
let {
markerList
} = this.properties;
markerList && markerList.map((item, idx) => {
if (item.id === markerId) {
item.num = markerList.length;
this.triggerEvent('onMarker', item) //通过triggerEvent将参数传给父组件
}
})
}
},
})
2、homeMap.json文件
homeMap.json文件只用来设置component的。
{
"component": true
}
3、homeMap.wxml文件
homeMap.wxml文件主要是来做地图的显示处理的。
4、homeMap.wxss文件
二、调用map组件的实现
1、home.js文件
Page({
data: {
markerPorts: [], // 定位点
position: [], // 地图中心点位置
parkMark: {}
},
onReady: function () {
//网络请求,这里可以忽略
let url = 'ec/me/pag-space/list'
const params = {
pageNum: 1,
}
homeParkList(url, params).then(({
code,
data,
msg
}) => {
if (code === "200") {
const {
records,
list
} = data
this.setData({
records: records
})
const markers = []; // 定位点集合
const marker = {
'0': "/images/green_marker.png",
'1': "/images/red_marker.png",
'2': "/images/yellow_marker.png",
'def': "/images/yellow_marker.png"
}
// 拼装定位点集合
list.forEach(res => {
const {
id,
latitude,
longitude,
parkingStatus,
} = res
markers.push({
id,
latitude,
longitude,
iconPath: marker[parkingStatus],
width: 30,
height: 30
})
})
wx.chooseLocation({
complete: e => {
markers.push({
id: 9999,
latitude: this.data.position[0],
longitude: this.data.position[1],
iconPath: marker['def'],
width: 30,
height: 30
})
this.setData({
position: [e.longitude, e.latitude],
markerPorts: markers,
markerList: list
})
}
})
}
})
},
getMarkerInfo(e) {
if (e.toString() === '[object Object]') {
this.setData({
parkInfo: e.detail
})
}
},
})
2、home.json文件
{
"component": true,
"usingComponents": {
"component":"../../components/Map/homeMap" //引用map组件
}
}
3、home.wxml文件
具体实现的效果图如下所示:

最后
