问题来源
项目需要是使用到地图,并不是所有页面都用到,所以采用异步加载当时引入地图
在vue项目目录下创建plugins文件夹,并在里面创建amap.js 文件
/*
* 异步创建script标签
*/
export default function MapLoader (key) {
return new Promise((resolve, reject) => {
if (window.AMap) {
resolve(window.AMap)
} else {
var script = document.createElement('script')
script.type = 'text/javascript'
script.async = true
script.src = 'http://webapi.amap.com/maps?v=1.3&callback=initAMap&key=' + key
script.onerror = reject
document.head.appendChild(script)
}
window.initAMap = () => {
resolve(window.AMap)
}
})
}
<template>
<div class="test">
<div id="container" style="height:300px;width:300px;"></div>
</div>
</template>
<script>
import MapLoader from '@/plugins/amap.js'
export default {
name: 'test',
data () {
return {
map: null
}
},
mounted () {
let that = this
MapLoader().then(AMap => {
console.log('地图加载成功')
that.map = new AMap.Map("container", {
resizeEnable: true
});
}, e => {
console.log('地图加载失败' ,e)
})
}
}
</script>
在项目中使用
- 还是使用我们上一个项目,那个MintUI的,不是有一个附近的板块么,我们就用这个
- cd到项目目录
- 安装Vue-amap
# cnpm install vue-amap --save
安装成功
- 在main.js引入
import AMap from 'vue-amap';
Vue.use(AMap);
AMap.initAMapApiLoader({
key: 'XXXXX',//刚刚开发者申请哪里的key
plugin: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType']
});
- 在Near.vue中调用
<template>
<div id="near">
<div id="amap-main">
</div>
</div>
</template>
<script type="text/ecmascript-6">
import { lazyAMapApiLoaderInstance } from 'vue-amap';
export default{
name:'near',
mounted() {
lazyAMapApiLoaderInstance.load().then(() => {
this.map = new AMap.Map('amap-main', {center: new AMap.LngLat(121.59996, 31.197646)});
});
}
}
</script>
<style lang="stylus">
#near
#amap-main
height 300px
</style>