Vue 使用高德地图,添加点标记 + 点击地图获取坐标 + 带搜索(即地理编码 + 逆地理编码) - 附完整示例
高德地图:
与真实世界联通 - 高德开放平台为开发者赋能,将地图精致地呈现在您的应用中
无论基于哪种平台,都可以通过高德开放平台API和SDK,轻松地完成地图的构建工作
官方文档:地图 | 高德地图API
效果
一、准备工作
1、注册/登录账号
2、点击控制台
3、创建应用
4、获取key和密钥,如上图所示
注:使用web服务API,如下图所示
二、安装依赖包
1、安装命令
npm i @amap/amap-jsapi-loader --save
2、这是我的版本
"@amap/amap-jsapi-loader": "^1.0.1",
三、使用步骤
1、在index.html文件中引入密钥
代码如下(示例):
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode: '', // 你的密钥
}
</script>
2、在vue文件中引入依赖包
代码如下(示例):
import AMapLoader from "@amap/amap-jsapi-loader"
3、申明变量并初始化调用
代码如下(示例):
import { shallowRef, defineEmits, ref, onBeforeUnmount } from 'vue';
const map = shallowRef(null);
let AMapObj, placeSearch, marker, geocoder;
function initMap(){
AMapLoader.load({
key:'', //设置您的key
version:"2.0",
plugins:['AMap.ToolBar','AMap.Driving'],
AMapUI:{
version:"1.1",
plugins:[],
},
Loca:{
version:"2.0.0"
},
}).then((AMap)=>{
// console.log(AMap);
AMapObj = AMap;
map.value = new AMap.Map("map-box",{
viewMode:"3D",
zoom:10,
zooms:[2,22],
center: [105.602725,37.076636],
});
map.value.on('click', onMapClick);
AMap.plugin(
['AMap.ToolBar','AMap.Scale','AMap.Geolocation','AMap.PlaceSearch',
'AMap.Geocoder','AMap.AutoComplete'],
() => {
// 缩放条
const toolbar = new AMap.ToolBar();
// 比例尺
const scale = new AMap.Scale();
// 定位
const geolocation = new AMap.Geolocation({
enableHighAccuracy: true, //是否使用高精度定位,默认:true
timeout: 10000, //超过10秒后停止定位,默认:5s
position: 'RT', //定位按钮的停靠位置
buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
});
geocoder = new AMap.Geocoder({
city: '全国',
});
map.value.addControl(geolocation);
map.value.addControl(toolbar);
map.value.addControl(scale);
placeSearch = new AMap.PlaceSearch({
// map: map.value,
city: '全国',
pageSize: 10, // 单页显示结果条数
pageIndex: 1, // 页码
citylimit: false, // 是否强制限制在设置的城市内搜索
autoFitView: true,
});
});
}).catch(e=>{
console.log(e);
})
}
initMap();
四、完整示例
Index.html
<!DOCTYPE html>
<html lang="zh_CN" id="htmlRoot">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="renderer" content="webkit" />
<meta name="viewport"
content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0" />
<title>
<%= title %>
</title>
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode: '', // 你的密钥
}
</script>
</head>
<body>
<div id="app">
</div>
</body>
</html>
Map.vue
<template>
<div class="home">
<div id="map-box"></div>
<div class="info-box">
<a-select
v-model:value="keyword"
show-search
placeholder="输入关键字搜索"
style="width: 300px"
:default-active-first-option="false"
:show-arrow="false"
:filter-option="false"
:not-found-content="null"
@search="handleSearch"
>
<a-select-option v-for="item in data" :key="item.id" :value="item.id" @click="handleSelect(item)">
<div class="d-flex flex-column">
<span>{{item.name}}</span>
<span style="font-size: '10px'; color: #999999">{{item.address}}</span>
</div>
</a-select-option>
</a-select>
<a-tooltip>
<template #title v-if="coord">点击复制</template>
<span style="margin: 5px 8px;">
经纬度:<span class="copy" style="cursor: pointer;" :data-clipboard-text="coord">{{coord}}</span>
</span>
</a-tooltip>
</div>
</div>
</template>
<script lang="ts" setup>
import { shallowRef, ref, onBeforeUnmount } from 'vue';
import AMapLoader from "@amap/amap-jsapi-loader";
import { message } from 'ant-design-vue';
import ClipboardJS from 'clipboard';
const clipboard = new ClipboardJS('.copy');
clipboard.on('success', function(e) {
console.log(e);
console.info('Text:', e.text);
message.info('复制成功');
e.clearSelection();
});
clipboard.on('error', function(e) {
if(!e.text) message.error('暂无可复制的内容')
});
onBeforeUnmount(() => {
clipboard.destroy();
})
const map = shallowRef(null);
const keyword = ref(null);
const data = ref([]);
const coord = ref('');
let AMapObj, placeSearch, marker, geocoder;
function initMap(){
AMapLoader.load({
key: '', //设置您的key
version: "2.0",
plugins: ['AMap.ToolBar','AMap.Driving'],
AMapUI: {
version: "1.1",
plugins: [],
},
Loca:{
version: "2.0.0"
},
}).then((AMap)=>{
// console.log(AMap);
AMapObj = AMap;
map.value = new AMap.Map("map-box",{
viewMode:"3D",
zoom:10,
zooms:[2,22],
center: [105.602725,37.076636],
});
map.value.on('click', onMapClick);
AMap.plugin(
['AMap.ToolBar','AMap.Scale','AMap.Geolocation','AMap.PlaceSearch',
'AMap.Geocoder','AMap.AutoComplete'],
() => {
// 缩放条
const toolbar = new AMap.ToolBar();
// 比例尺
const scale = new AMap.Scale();
// 定位
const geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默认:true
timeout: 10000, // 超过10秒后停止定位,默认:5s
position: 'RT', // 定位按钮的停靠位置
buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
});
geocoder = new AMap.Geocoder({
city: '全国',
});
map.value.addControl(geolocation);
map.value.addControl(toolbar);
map.value.addControl(scale);
placeSearch = new AMap.PlaceSearch({
city: '全国',
pageSize: 10, // 单页显示结果条数
pageIndex: 1, // 页码
citylimit: false, // 是否强制限制在设置的城市内搜索
autoFitView: true,
});
});
}).catch(e=>{
console.log(e);
})
}
// 搜索地图
function handleSearch(str) {
placeSearch.search(str, (status, result) => {
console.log(result);
if (result && typeof result === 'object' && result.poiList) {
const list = result.poiList.pois;
list.forEach(item => {
item.value = item.name;
item.label = item.name;
});
data.value = list
}
});
}
// 点击地图
function onMapClick(e) {
coord.value = e.lnglat.lng + ',' + e.lnglat.lat
geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function(status, result) {
if (status === 'complete' && result.info === 'OK') {
// result为对应的地理位置详细信息
keyword.value = result.regeocode.formattedAddress
}
})
drawMarker(e.lnglat)
}
// 点击搜索项
function handleSelect(item) {
console.log(item);
drawMarker(item.location)
if (item.location != null) {
coord.value = item.location.lng + ',' + item.location.lat
}
}
// 绘制地点marker
function drawMarker(location) {
if (location == null) return
let longitude = location.lng, latitude = location.lat
if (marker) {
marker.setMap(null);
}
marker = new AMapObj.Marker({
position: new AMapObj.LngLat(longitude, latitude),
anchor: 'bottom-center',
});
marker.on('click', () => {
coord.value = location;
})
map.value.add(marker);
map.value.setZoomAndCenter(16, [longitude, latitude]);
}
initMap();
</script>
<style lang="less" scoped>
.home{
height: 500px;
width: 100%;
padding: 0px;
margin: 0px;
position: relative;
.info-box {
position: absolute;
top: 8px;
right: 8px;
width: 300px;
background-color: #1f1f1f;
display: flex;
flex-direction: column;
}
}
#map-box{
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
</style>
<style scoped>
:deep() .amap-logo {
display: none !important;
}
:deep() .amap-copyright {
display: none !important;
}
</style>
注:clipboard一键复制的详细使用方法参考地址