注册高德地图:
第一步,注册高德开发者;
第二步,去控制台创建应用;
第三步,获取Key。
vue中使用高德地图:
第一步:安装 npm install vue-amap --save
第二步:修改webpac.base.conf.js文件
externals: {
'AMap': 'AMap'
},此外文件与entry平级
第三步:在assets文件中新建一个js文件AMap.js
export default function MapLoader () { // <-- 原作者这里使用的是module.exports
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" class="h300 w300" style="position: relative;width: 100%;height:500px;"></div>
</div>
</template>
<script>
import MapLoader from '@/assets/js/AMap.js'
var map
export default {
name: "NewMap",
data () {
return {
map: null,
thisPosition: {
location: '',
lng: '',
lat: ''
},
}
},
mounted: function () {
this.init()
},
methods: {
init: function () {
let that = this
MapLoader().then(AMap => {
map = new AMap.Map('container', {
center: [108.952, 34.223],//需求的城市的经度和 纬度
resizeEnable: true,
zoom: 10
})
AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function () {
map.addControl(new AMap.ToolBar())
map.addControl(new AMap.Scale())
})
})
},
}
}
</script>