在本文中你可以学到如何在Vue中使用高德地图
1. 前言
最近开发车辆轨迹的一款Web应用,使用到了高德地图
,由于甲方爸爸给不了真实数据,外加Google、Baidu都找不到合适的模拟数据,于是乎,自己根据高德地图 JS API
,做了一款行车路线的工具。
本工具使用了:Vue
、ElementUI
、Vue-amap
、vue-json-viewer
开发。
实例地址: vince-lee92.github.io/example-rep…
源码地址:
- github:github.com/vince-lee92…
- gitee:gitee.com/vince-lee/l…
2. 编码
2.1. 安装对应插件并配置
安装:npm install element-ui vue-amap --save
配置:main.js
中
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import VueAMap from 'vue-amap';
import JsonViewer from 'vue-json-viewer';
Vue.use(ElementUI);
Vue.use(JsonViewer)
Vue.use(VueAMap);
window.mapKey = "你的KEY"
window.mapPlugin = [
"AMap.DragRoute",
]
window.mapVersion = "1.4.4"
VueAMap.initAMapApiLoader({
key: window.mapKey,
plugin: window.mapPlugin,
v: window.mapVersion
});
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
2.2. 编码
<template>
<div class="drag-route">
<el-amap
class="amap-box"
:amap-manager="amapManager"
:vid="'amap-vue'"
:events="mapEvents"
mapStyle="amap://styles/whitesmoke"
>
<div class="action">
<el-button type="primary" @click="visible = true">查看JSON</el-button>
</div>
</el-amap>
<el-dialog
title="查看JSON"
center
:visible.sync="visible"
>
<json-viewer
:value="routerData"
:expand-depth="5"
:copyable="copyable"
sort
/>
</el-dialog>
</div>
</template>
<script>
const amapManager = new window.VueAMap.AMapManager();
export default {
name: 'About',
data() {
const that = this
return {
routerData: [],
visible: true,
copyable: {copyText: '复制JSON', copiedText: '复制成功', timeout: 2000},
amapManager,
mapEvents: {
complete() {
that.DragRoute()
},
click(e) {
const {lng, lat} = e.lnglat
console.log(`你点击点的经纬度为:${lng},${lat}`)
const str = `${lng}|${lat}`
console.log(str)
}
},
};
},
methods: {
DragRoute() {
const map = this.amapManager.getMap();
const path = [];
path.push([116.303843, 39.983412]);
path.push([116.321354, 39.896436]);
map.plugin("AMap.DragRoute", () => {
const route = new AMap.DragRoute(map, path, AMap.DrivingPolicy.LEAST_FEE); //构造拖拽导航类
route.getRoute(function (type, target, data) {
console.log(type, target, data)
}); //查询导航路径并开启拖拽导航
route.search(); //查询导航路径并开启拖拽导航
route.on('complete', (arr) => {
this.routerData = arr.target.La
})
});
}
}
};
</script>
<style>
* {
margin: 0;
padding: 0;
}
.drag-route {
height: 100vh;
position: relative;
}
.drag-route .action {
position: absolute;
bottom: 0;
width: 100%;
height: 100px;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
}
.el-dialog__body {
height: 450px;
overflow: auto;
}
</style>
3. 结束
在本案例中只是以AMap.DragRoute (可拖拽驾车路线规划)
为例,其实官网中还有很多实例可用。
比如一下:
lbs.amap.com/api/javascr…