下面代码兼容安卓APP和H5
高德地图官网:我的应用 | 高德控制台 ,绑定服务选择《Web端(JS API)》
/utils/map.js 需要设置你自己的key和安全密钥
export function myAMap() {
return new Promise(function(resolve, reject) {
if (typeof window.onLoadMyAMap === 'function') {
resolve(window.onLoadMyAMap)
return
}
window.onLoadMyAMap = function() {
resolve(window.onLoadMyAMap)
}
window._AMapSecurityConfig = {
securityJsCode: '你的安全密钥',
};
var script = document.createElement('script')
script.type = 'text/javascript'
script.src =
`https://webapi.amap.com/maps?v=2.0&key=你的key&callback=onLoadMyAMap&plugin=AMap.Geocoder,AMap.AutoComplete,AMap.PlaceSearch`
script.onerror = reject
document.head.appendChild(script)
})
}
页面代码
<template>
<view class="gaodeMap">
<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 {
myAMap
} from "@/utils/map.js";
let amap;
const _window = window;
export default {
data() {
return {
latitude: 22.543648,
longitude: 114.057923,
zoom: 5,
}
},
methods: {
//获取地图信息
initMap() {
myAMap().then(() => {
// 创建地图实例
amap = new AMap.Map('container', {
zoom: 5, // 地图缩放比例
zooms: [4, 20], // 地图缩放区间
center: [114.057923, 22.543648], //设置经纬度为地图中心
resizeEnable: true, // 开启地图缩放
});
// 设置个性化地图
// var styleName = "amap://styles/" + 'darkblue'
// amap.setMapStyle(styleName);
// 地图缩放事件
amap.on('zoomend', (e) => {
});
// 地图拖拽事件
amap.on('dragend', (e) => {
});
})
},
},
mounted() {
this.initMap()
},
beforeDestroy() {
// 离开页面销毁地图
amap && amap.destroy();
amap = null
}
}
</script>
<style lang="scss" scoped>
</style>
效果图