1、在index.html文件中引入
<!-- 引入高德地图API -->
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode: 'key值',
}
</script>
<script type="text/javascript" src="http://webapi.amap.com/maps?v=2.0&key="></script>
2、在vue.config.js文件中添加
configureWebpack: {
// provide the app's title in webpack's name field, so that
// it can be accessed in index.html to inject the correct title.
name: name,
resolve: {
alias: {
'@': resolve('src')
}
},
externals: {
'AMap': 'AMap',
'AMapUI': 'AMapUI'
}
},
3、map.vue
<template>
<div class="amap-page-container">
<!-- 显示地图的div -->
<div id="mapDiv" ref="mapDiv" style="width:100%;height:600px" class="mapDiv">
loading...
</div>
</div>
</template>
<script>
import AMap from 'AMap'
export default {
props: {
center: { // 坐标
type: Array,
default: () => [100, 30]
}
},
data() {
return {
map: null, // 地图对象
zoom: 17,
marker: null,
mapCenter: [100, 30]
}
},
watch: {
center() {
this.map.remove(this.marker)
this.map.setCenter(this.center)
this.addMarker({ longitude: this.center[0], latitude: this.center[1] })
}
},
mounted() {
this.initMap()
},
methods: {
// 初始化地图
initMap() {
const map = new AMap.Map('mapDiv', {
center: this.center,
resizeEnable: true,
zoom: this.zoom,
zooms: [10, 20],
dataZooms: [10, 22]
// mapStyle: 'amap://styles/099bd238d2de81d66fc23b41480d971e' // 地图样式ID
})
this.map = map
this.addMarker({ longitude: this.center[0], latitude: this.center[1] })
},
addMarker(item) {
const WGS = { lon: item.longitude, lat: item.latitude }
this.marker = new AMap.Marker({
position: [WGS.lon, WGS.lat],
draggable: true,
cursor: 'move'
})
this.marker.on('dragend', (e) => {
this.$emit('changeCenter', { lng: e.lnglat.lng, lat: e.lnglat.lat })
})
this.marker.on('click', (e) => {
this.$emit('click', { lng: e.lnglat.lng, lat: e.lnglat.lat })
})
// 将 markers 添加到地图
this.map.add(this.marker)
}
}
}
</script>
本文详细介绍了如何在Vue项目中集成高德地图,包括在index.html中引入地图脚本,vue.config.js中配置公共路径,以及在组件(map.vue)中实现地图功能的步骤。
5615

被折叠的 条评论
为什么被折叠?



