成为开发者并创建 key
为了正常调用 API ,请先注册成为高德开放平台开发者,并申请 web 平台(JS API)的 key 和安全密钥
高德开放平台控制台
操作步骤链接网址
NPM 安装 Loader
npm i @amap/amap-jsapi-loader --save
配置安全秘钥
注意:这个设置必须是在 JSAPI 的脚本加载之前进行设置,否则设置无效。所以安全密钥在入口的 html 文件中引入,页面中正常使用key值即可。
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
<!-- 高德安全秘钥 -->
<!-- 高德地图秘钥,必须在加载load.js文件之前 -->
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode:'您申请的安全密钥',
}
</script>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
引入JS API Loader
import AMapLoader from '@amap/amap-jsapi-loader';
完整的代码vue
<template>
<div class="home_div">
<div class="map_title">
<h3>JSAPI Vue2地图组件示例</h3>
</div>
<div id="container"></div>
<div id="panel" style='position: absolute; right: 10px;top: 10px;height: 480px;width: 300px;z-index: 100;overflow: auto;'></div>
</div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
name: "Mapview",
data() {
return {
//map:null,
}
},
created() {
},
mounted() {
this.initAMap();
},
methods: {
initAMap() {
AMapLoader.load({
key: '你申请的key', //设置您的key
version: "2.0", //指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins: ['AMap.ToolBar', 'AMap.Driving'],//需要使用的的插件列表,如比例尺'AMap.Scale'等
AMapUI: {
version: "1.1",
plugins: [],
},
Loca: {
version: "2.0" //数据可视化
},
}).then((AMap) => {
this.map = new AMap.Map("container", {
viewMode: '2D', // 默认使用 2D 模式
zoom:5, //初始化地图层级
center: [116.397428, 39.90923] //初始化地图中心点
});
this.driving = new AMap.Driving({
// 驾车路线规划策略,AMap.DrivingPolicy.LEAST_TIME是最快捷模式
policy: AMap.DrivingPolicy.LEAST_TIME,
// map 指定将路线规划方案绘制到对应的AMap.Map对象上
map: this.map,
// panel 指定将结构化的路线详情数据显示的对应的DOM上,传入值需是DOM的ID
panel: 'panel'
})
this.points = [
{ keyword: '北京市地震局(公交站)',city:'北京' },
{ keyword: '陆家嘴',city:'上海' }
]
this.driving.search(this.points, function (status, result) {
console.log(status, result);
})
}).catch(e => {
console.log(e);
})
},
}
}
</script>
<style scoped>
.home_div {
padding: 0px;
margin: 0px;
width: 100%;
height: 100%;
position: relative;
}
#container {
padding: 0px;
margin: 0px;
width: 100%;
height: 100%;
position: absolute;
}
.map_title {
position: absolute;
z-index: 1;
width: 100%;
height: 50px;
background-color: rgba(27, 25, 27, 0.884);
}
h3 {
position: absolute;
left: 10px;
z-index: 2;
color: white;
}
</style>
注意:高德地图在2021.12月以后新申请的key必须要搭配安全密钥一起使用