uniapp接入BMapGL百度地图
下面代码兼容安卓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 = reject
document.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>
效果图