vue2项目中有用到高德地图,以此记录:
需求:搜索可定位地点
过程:在vue2项目运行起地图,在点图实现点标记(mark),搜索功能,切换标记
vue-amap官方文档地址: https://github.com/ElemeFE/vue-amap/
安装 amap:
npm install vue-amap --save
地图搭建:
main.js
import VueAMap from "vue-amap"
Vue.use(VueAMap)
VueAMap.initAMapApiLoader({
key: "xxxxxxxxxxxxxxx",
plugin: [
"AMap.Autocomplete", //输入提示插件
"AMap.PlaceSearch", //POI搜索插件
"AMap.Scale", //右下角缩略图插件 比例尺
"AMap.OverView", //地图鹰眼插件
"AMap.ToolBar", //地图工具条
"AMap.Geolocation", //定位控件,用来获取和展示用户主机所在的经纬度位置
"AMap.Geocoder"// 逆地理编码,通过经纬度获取地址所在位置详细信息
// 根据需求选用
],
uiVersion: "1.0", // 地图ui版本
v : '1.4.4' // amap版本
})
vue文件:
<template>
<div class="contain">
<el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult">
</el-amap-search-box>
<el-amap ref="map" vid="amapDemo" :center="center" :zoom="zoom" class="amap-demo">
<el-amap-marker :position="center" key="100"></el-amap-marker>
</el-amap>
<div v-if="searchResult">
搜索:{{content}},详细地址为:{{searchResult.locationName}},经度:{{searchResult.longitude}},纬度:{{searchResult.latitude}}
</div>
</div>
</template>
<script>
export default {
name: 'AMapDemo',
data() {
return {
zoom: 12,
center: [118.02, 24.48],
searchOption: {
// 限制搜索城市的范围
citylimit: false
},
content: '',
inputValue: '',
searchResult: {
address: '',
latitude: '',
longitude: '',
name: '',
type: '',
country: '',
province: '',
city: '',
area: '',
township: '',
street: '',
neighborhood: '',
locationName: ''
}
}
},
methods: {
onSearchResult(pois) {
//搜索
console.log(pois)
let latSum = 0
let lngSum = 0
let that = this
if (pois && pois.length > 0) {
//如果长度为1则无需转化
let poi = pois[0]
let lng = poi["lng"]
let lat = poi["lat"]
that.center = [lng, lat]
that.zoom = 13
that.content = poi.name
console.log(poi.name)
that.searchResult.address = poi.address
that.searchResult.latitude = poi.lat
that.searchResult.longitude = poi.lng
let geocoder = new AMap.Geocoder({})
geocoder.getAddress(that.center, function(status, result) {
console.log(result)
if (status === 'complete' && result.info === 'OK') {
let obj = result.regeocode.addressComponent
that.searchResult.locationName = obj.province + obj.city + obj.district + obj.township + obj.street +
poi.address
}
});
} else {
that.searchResult = []
}
},
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.amap-demo {
width: 100%;
height: 600px;
position: relative;
}
.search-box {
height: 35px;
margin: 10px auto;
width: calc(100% - 20px);
// border-radius:16px;
box-shadow: none;
background: #ffff;
border: 1px solid #e6e6e6;
.search-box-wrapper {
input {
background: #fff;
padding-left: 20px;
}
.search-btn {
color: #2A67FE;
width: 90px;
height: 20px;
box-sizing: border-box;
border-left: 1px solid #D7D7D7;
}
}
}
</style>
最终效果如下:

自此,高德地图完成部署,同时可搜索地点进行标记并且获取搜索点的经纬度.同时产生了新的功能需求:点击地图上的点,进行标记(mark)并且获取经纬度,下篇进行了记录
