There are two primary methods for integrating Amap (Gaode Maps) into Vue.js applications:
Method 1: Using vue-amap Component
The vue-amap component provides a convenient way to add maps to Vue applications. However, it may present certain challenges:
- Cross-origin issues may occur during implementation
- Map elements may fail to render after page refresh, despite working on initial load
These challenges led to exploring alternative approaches.
Method 2: Direct SDK Integration
Directly integrating the Amap SDK offers a more reliable solution. Follow these steps:
Step 1: Include Amap SDK
Add the following script tag to your public/index.html file:
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.4&key=YOUR_API_KEY"></script>
Step 2: Configure vue.config.js
Create a vue.config.js file in your project root and add the following configuration:
module.exports = {
devServer: {
port: 57103
},
configureWebpack: {
externals: {
'AMap': 'AMap'
}
}
}
Note: After modifying vue.config.js, restart your development server for changes to take effect.
Step 3: Implement the Map Component
Create a Vue component to display the map:
<template>
<div class="map-container">
<div id="mapElement" style="width: 100%; height: 400px"></div>
</div>
</template>
<script>
export default {
name: 'AmapComponent',
mounted() {
this.initializeMap()
},
methods: {
initializeMap() {
const mapInstance = new AMap.Map('mapElement', {
center: [116.397428, 39.90923],
resizeEnable: true,
zoom: 11
})
// Optional: Add a marker
const marker = new AMap.Marker({
position: [116.397428, 39.90923],
map: mapInstance
})
}
}
}
</script>
<style scoped>
.map-container {
width: 100%;
height: 400px;
}
</style>
Important: The map initialization should be performed in the mounted lifecycle hook rather than created, as the DOM element needs to be available.
Step 4: Additional Features
You can extend the map functionality by adding various services and plugins:
<script>
export default {
name: 'AmapComponent',
mounted() {
this.initializeMap()
},
methods: {
initializeMap() {
const mapInstance = new AMap.Map('mapElement', {
center: [116.397428, 39.90923],
resizeEnable: true,
zoom: 11
})
// Add scale control
mapInstance.addControl(new AMap.Scale())
// Add toolbar
mapInstance.addControl(new AMap.ToolBar())
// Add search functionality
const placeSearch = new AMap.PlaceSearch({
city: '北京'
})
// Add click event
mapInstance.on('click', (e) => {
console.log('Map clicked at:', e.lnglat)
})
}
}
}
</script>