微信小程序如何實現(xiàn)在地圖上多地點標(biāo)識
2020-09-27|HiShop
導(dǎo)讀:如何在微信小程序上實現(xiàn)對地圖上的控件進行多地點標(biāo)識,以下是具體做法:...
如何在微信小程序上實現(xiàn)對地圖上的控件進行多地點標(biāo)識,以下是具體做法:
wxml
- 1 <map id="map" scale="{{scale}}" controls="{{controls}}" bindcontroltap="controltap" markers="{{markers}}" bindmarkertap="markertap" bindregionchange="regionchange" show-location style="width: 100%; height: 580px;"></map>
js
- 1 let hospitalData = require('hospitalData')
- 2 Page({
- 3 data: {
- 4 centerX: 0.0,
- 5 centerY: 0.0,
- 6 //可能我標(biāo)識的地點和你所在區(qū)域比較遠(yuǎn),縮放比例建議5;
- 7 scale:15,
- 8 markers: [],
- 9 controls: [{
- 10 id: 1,
- 11 iconPath: '/image/location-control.png',
- 12 position: {
- 13 left: 0,
- 14 top: 10,
- 15 width: 40,
- 16 height: 40
- 17 },
- 18 clickable: true
- 19 }]
- 20 },
- 21 onReady: function(e) {
- 22 // 使用 wx.createMapContext 獲取 map 上下文
- 23 this.mapCtx = wx.createMapContext('myMap')
- 24 },
- 25
- 26 onLoad: function() {
- 27 console.log('地圖定位!')
- 28 let that = this
- 29 wx.getLocation({
- 30 type: 'gcj02', //返回可以用于wx.openLocation的經(jīng)緯度
- 31 success: (res) => {
- 32 let latitude = res.latitude;
- 33 let longitude = res.longitude;
- 34 let marker = this.createMarker(res);
- 35 this.setData({
- 36 centerX: longitude,
- 37 centerY: latitude,
- 38 markers: this.getHospitalMarkers()
- 39 })
- 40 }
- 41 });
- 42 },
- 43
- 44 /**
- 45 * 標(biāo)示點移動觸發(fā)
- 46 */
- 47 regionchange(e) {
- 48 console.log(e.type)
- 49 },
- 50
- 51 /**
- 52 * 點擊標(biāo)識點觸發(fā)
- 53 */
- 54 markertap(e) {
- 55 console.log(e)
- 56 },
- 57
- 58 /**
- 59 * control控件點擊時間
- 60 */
- 61 controltap(e) {
- 62 console.log(e.controlId)
- 63 this.moveToLocation()
- 64 },
- 65
- 66
- 67 /**
- 68 * 獲取醫(yī)院標(biāo)識
- 69 */
- 70 getHospitalMarkers() {
- 71 let markers = [];
- 72 for (let item of hospitalData) {
- 73 let marker = this.createMarker(item);
- 74 markers.push(marker)
- 75 }
- 76 return markers;
- 77 },
- 78
- 79 /**
- 80 * 移動到自己位置
- 81 */
- 82 moveToLocation: function() {
- 83 let mpCtx = wx.createMapContext("map");
- 84 mpCtx.moveToLocation();
- 85 },
- 86
- 87
- 88 /**
- 89 * 還有地圖標(biāo)識,可以在name上面動手
- 90 */
- 91 createMarker(point) {
- 92 let latitude = point.latitude;
- 93 let longitude = point.longitude;
- 94 let marker = {
- 95 iconPath: "/image/location.png",
- 96 id: point.id || 0,
- 97 name: point.name || '',
- 98 latitude: latitude,
- 99 longitude: longitude,
- 100 width: 25,
- 101 height: 48
- 102 };
- 103 return marker;
- 104 }
- 105 })
hospitalData.js (模擬數(shù)據(jù))
- 1 module.exports = [{
- 2 "id": 1,
- 3 "name": "永州市中心醫(yī)院",
- 4 "longitude": "111.62852107566833",
- 5 "latitude": "26.42142999357519"
- 6 },
- 7 {
- 8 "id": 2,
- 9 "name": "永州市中醫(yī)院",
- 10 "longitude": "111.5972679762268",
- 11 "latitude": "26.44470581245983"
- 12 }
- 13 ]
運行示例時,建議放在同一目錄下.