实现效果
- 可搜索位置
- 可移动标记点
- 点击地图进行标记
效果图
效果图
下载vue-amap
npm run vue-amap --save
或
cnpm run vue-amap --save
高德地图申请key
请自行搜索申请方法
https://console.amap.com/dev/index
在src的main.js文件中引入
import VueAMap from 'vue-amap';
Vue.use(VueAMap);
// 初始化vue-amap
VueAMap.initAMapApiLoader({
key: '高德地图key',
plugin: [ // 插件集合 (插件按需引入)
"AMap.Autocomplete", //输入提示插件
"AMap.PlaceSearch", //POI搜索插件
"AMap.Scale", //右下角缩略图插件 比例尺
"AMap.OverView", //地图鹰眼插件
"AMap.ToolBar", //地图工具条
"AMap.MapType", //类别切换控件,实现默认图层与卫星图、实施交通图层之间切换的控制
"AMap.PolyEditor", //编辑 折线多,边形
"AMap.CircleEditor", //圆形编辑器插件
"AMap.Geolocation" //定位控件,用来获取和展示用户主机所在的经纬度位置
]
});
组件代码
<template>
<div class="amap-page-container">
<!-- 搜索框 -->
<el-amap-search-box
ref="searchbox"
class="search-box"
:search-option="searchOption"
:on-search-result="onSearchResult"
></el-amap-search-box>
<!-- 高德地图组件 -->
<el-amap vid="amapDemo" :zoom="zoom" :center="center" :events="events" class="amap-demo">
<!-- 标记点,可以使用v-for循环设置多个 -->
<el-amap-marker
vid="component-marker"
:position="marker.position"
:events="marker.events"
:draggable="true"
></el-amap-marker>
</el-amap>
</div>
</template>
<script>
const defaultPosition = [113.681423, 34.729528]
export default {
name: "myAmap",
props: {
value: {
type: Array,
default: () => defaultPosition
},
searchText: {
type: String,
default: ''
}
},
data() {
return {
zoom: 14, // 视角高度,越小视角越高
center: defaultPosition, // 地图中心点位置
events: {
click: (e) => { // 鼠标点击地图事件
this.marker.position = [e.lnglat.lng, e.lnglat.lat];
this.positionChange()
},
},
searchOption: { // 搜索框信息
city: "北京", // 设置你要搜索的城市。默认全国
citylimit: false, // 是否限制城市内搜索
},
marker: { // 坐标点信息
position: defaultPosition, // 坐标的位置
events: {
dragend: (e) => { // 移动坐标点
this.marker.position = [e.lnglat.lng, e.lnglat.lat];
this.positionChange()
},
},
},
};
},
model: {
prop: 'value',
event: 'valueChange'
},
watch: {
value(newVal) {
if (newVal.length == 2) {
this.marker.position = newVal
this.center = newVal
} else {
this.marker.position = defaultPosition
this.center = defaultPosition
}
},
// 监听父组件传入的关键字进行搜索
searchText(newVal) {
// 将关键字赋值到输入框内
this.$refs.searchbox._data.keyword = newVal
// 调用搜索实例
if (this.$refs.searchbox._data.keyword) {
this.$refs.searchbox.search()
}
}
},
methods: {
// 搜索获取到的位置信息,只取了第一条数据,需要的话可以设置多个标记点
onSearchResult(pois) {
if (pois.length > 0) {
let { lng, lat } = pois[0];
this.marker.position = [lng, lat];
this.center = [lng, lat];
this.positionChange()
}
},
// 当标记点发生变化时,将数据传给父组件
positionChange() {
this.$emit('valueChange', this.marker.position)
}
},
};
</script>
<style scoped>
.amap-page-container {
position: relative;
width: 100%;
height: 100%;
}
.amap-demo {
width: 100%;
height: 100%;
}
.search-box {
position: absolute;
top: 25px;
left: 20px;
width: 300px;
}
.amap-page-container {
position: relative;
}
</style>
父组件调用方法
<my-amap v-model="position" :searchText="searchText"></my-amap>