下面代码兼容安卓APP和H5
百度地图官网:控制台 | 百度地图开放平台 应用类别选择《浏览器端》
/utils/map.js 需要设置你自己的key
export function myBMapGL1() {return new Promise(function(resolve, reject) {if (typeof window.initMyBMapGL1 === 'function') {resolve(window.initMyBMapGL1)return}window.initMyBMapGL1 = function() {resolve(window.initMyBMapGL1)}var script = document.createElement('script')script.type = 'text/javascript'script.src = `https://api.map.baidu.com/api?v=1.0&type=webgl&ak=你的key&callback=initMyBMapGL1`script.onerror = rejectdocument.head.appendChild(script)})
}
页面代码
<template><view class="baiduMap"><view class="map" v-bind:style="{ height: windowHeight * 2 + 'rpx'}" id="container"></view></view>
</template><script>export default {data() {return {windowHeight: "",}},methods: {},mounted() {uni.getSystemInfo({success: res => {this.windowHeight = res.windowHeight;}});}}
</script><script module="allmap" lang="renderjs">import {myBMapGL1} from "@/utils/map.js";let bmap;export default {data() {return {}},methods: {//获取地图信息initMap() {myBMapGL1().then((res) => {// 创建地图实例bmap = new BMapGL.Map("container");// 设置个性化地图// bmap.setMapStyleV2({// styleId: '',// });// 地图初始化,设置中心点坐标和地图缩放比例bmap.centerAndZoom(new BMapGL.Point(113.88308, 22.55329), 5);// 开启鼠标滚轮缩放bmap.enableScrollWheelZoom(true);// 地图缩放事件bmap.addEventListener('zoomend', (e) => {console.log("zoomend--", e);});// 地图拖拽事件bmap.addEventListener('dragend', (e) => {console.log("dragend--", e);});})},},mounted() {this.initMap()},beforeDestroy() {// 离开页面销毁地图bmap && bmap.destroy();bmap = null}}
</script><style lang="scss" scoped>
</style>
效果图