方法1、配置map,使组件可以正常使用
manifest.json中进行勾选配置,并且去对应的地图官网申请一个key
很不幸的事,我们pc端选型用的百度地图,这个方法就不行了
方法2、使用renderjs调用原生api
<template> <view> <!-- #ifdef H5 --> <view id="map" class="mapv" style="width:100%;" :latitude="mapData.lat" :longitude="mapData.lng"></view> <!-- #endif --> <!-- #ifndef H5 --> <map id="map" class="mapv" style="width:100%;" :latitude="mapData.lat" :longitude="mapData.lng" :markers="markers" :scale="mapOption.scaleSize" :enable-scroll="mapOption.scroll" :enable-zoom="mapOption.zoom"> </map> <!-- #endif --> </view> </template> <script> export default { data() { return { mapData:{lat:xxxx, lang:xxx,}, markers:null, } } } </script> <script module="bmap" lang="renderjs"> export default { data() { return { map: null, ownerInstanceObj: null //service层对象 }, mounted() { let that = this; let timer = setInterval(function() { const mapElement = document.getElementById('map'); if (mapElement) { clearTimeout(timer); that.init(); } }, 1000); }, methods: { init(){ if (typeof window.BMap === 'function') { this.initAmap() } else { // 百度地图异步加载回调处理 window.onBMapCallback = () => { this.initAmap() } const script = document.createElement('script') script.src = 'https://api.map.baidu.com/api?v=2.0&ak=' + xxx + '&s=1&callback=onBMapCallback' document.head.appendChild(script) } }, initAmap() { let mapElement = document.getElementById('map'); let lat = 0; let lng = 0; if (mapElement) { lat = mapElement.getAttribute('latitude'); lng = mapElement.getAttribute('longitude'); } this.map = new BMap.Map("map") let point = new BMap.Point(lng, lat) this.map.centerAndZoom(point, 16) //创建标注点 let marker = new BMap.Marker(new BMap.Point(lng, lat)); let lightMyIcon = new BMap.Icon( m0, new BMap.Size(25, 25), { imageSize: new BMap.Size(25, 25) }) marker.setIcon(lightMyIcon) //将标注点添加到地图上 this.map.addOverlay(marker) this.initMarkers() }, //初始化标记点 initMarkers:function(){ if(this.map){ this.map.clearOverlays() } if(!this.map || !this.markerList || !this.markerList.length){ return } let prevMarker = null this.markerList.forEach((item, index) => { let marker = new BMap.Marker(new BMap.Point(item.lng, item.lat))
let lightMyIcon = new BMap.Icon( m1, new BMap.Size(25, 25), { imageSize: new BMap.Size(25, 25) }) marker.setIcon(lightMyIcon) marker.addEventListener('click', (e) => { if(prevMarker){ let prevIconObj = new BMap.Icon( m1, new BMap.Size(25, 25), { imageSize: new BMap.Size(25, 25) }) prevMarker.setIcon(prevIconObj) } prevMarker = marker let selectedIcon = new BMap.Icon( m2, new BMap.Size(25, 25), { imageSize: new BMap.Size(25, 25) }) marker.setIcon(selectedIcon) this.dataIndex = index this.onClick(null,this.ownerInstanceObj) }) //将标注点添加到地图上 this.map.addOverlay(marker) }) }, updateEcharts(newValue, oldValue, ownerInstance, instance) { this.initMarkers() // 监听 service 层数据变更 this.ownerInstanceObj = ownerInstance }, onClick(event, ownerInstance) { // 调用 service 层的方法 ownerInstance.callMethod('onViewClick', { dataIndex: this.dataIndex }) } } } </script>