高德地圖
https://lbs.amap.com/api/javascript-api/guide/abc/prepare
封裝為共用組件,由於每個地圖都必須命名一個Id,當項目中多次調用地圖子組件時,需要動態改變id
<template>
<!-- 高德地圖組件 -->
<div :id="id" :style="{width:width+'px',height:height+'px',margin:'34px auto'}" class="m-map"/>
</template>
<script> export default { props: { // 寬度
width: { type:Number, default:300 }, // 高度
height: { type:Number, default:300 }, // 經緯度,默認設為北京
point: { type:Array, default(){ return [ 116.46 , 39.92 ] } } }, data() { return { //地圖id,多次調用該地圖組件時,id必須動態生成
id: `map`, //高德地圖開發者秘鑰,調用接口時使用
key: '0dbc0dfd7c775f2a927174493eab8220' } }, watch: { //經緯度
point: function (val, old) { this.map.setCenter(val) this.marker.setPosition(val) } }, mounted() { let self = this
//地圖id,多次調用該地圖組件時,id必須動態生成
self.id = `map${Math.random().toString().slice(4, 6)}` // 封裝回調函數,為了防止與其他地方定義的load沖突,最好重命名,如onmaploaded
window.onmaploaded = () => { //地圖基礎控件添加,傳遞的第一個參數是DOM元素的id
let map = new window.AMap.Map(self.id, { // resizeEnable: true, //是否監控地圖容器尺寸變化
// zoom:11, //初始化地圖層級
// center: [116.397428, 39.90923] //初始化地圖中心點
resizeEnable: true, zoom: 11, center: self.point }) //地圖圖面
self.map = map // 同時引入工具條插件
window.AMap.plugin('AMap.ToolBar', () => { // 在圖面添加工具條控件,工具條控件集成了縮放、平移、定位等功能按鈕在內的組合控件
let toolbar = new window.AMap.ToolBar() map.addControl(toolbar) //創建地圖點標記:
let marker = new window.AMap.Marker({ icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png', position: self.point }) self.marker = marker //將創建好的地圖點標記控件 添加到地圖map
marker.setMap(map) }) } //注意,此處url中傳遞的回調函數名,必須與上面一致
const url = `https://webapi.amap.com/maps?v=1.4.10&key=${self.key}&callback=onmaploaded`
let jsapi = document.createElement('script') jsapi.charset = 'utf-8' jsapi.src = url document.head.appendChild(jsapi) }, } </script>