vue中PC端使用高德地图 -- 实现搜索定位、地址标记、弹窗显示定位详情
<template>
<div class="map-container">
<el-amap class="map" :vid="'amap'" :zoom="10">
<el-amap-marker v-for="(marker, index) in markers" :key="index" :position="marker"></el-amap-marker>
</el-amap>
<div class="search-box">
<input v-model="searchKey" @keyup.enter="searchLocation" type="text" placeholder="请输入搜索文字">
<button @click="searchLocation">搜索</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
searchKey: '',
markers: [],
map: null,
};
},
methods: {
searchLocation() {
const that = this;
this.map.plugin('AMap.Geolocation', function() {
let geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默认:true
timeout: 10000, // 超过10秒后停止定位,默认:5s
});
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete); // 返回定位信息
AMap.event.addListener(geolocation, 'error', onError); // 返回定位出错信息
function onComplete(data) {
// data是一个对象,内含经纬度信息
that.markers.push([data.position.getLng(), data.position.getLat()]);
}
function onError(data) {
// 定位出错
console.log('定位失败', data);
}
});
},
},
mounted() {
this.map = this.$refs.amap.$map;
},
};
</script>
<style>
.map-container {
position: relative;
height: 400px;
}
.map {
height: 100%;
}
.search-box {
position: absolute;
top: 10px;
left: 10px;
}
.search-box input {
padding: 8px;
border-radius: 4px;
border: 1px solid #ccc;
outline: none;
}
.search-box button {
padding: 8px 12px;
border: 1px solid #1a73e8;
background-color: #1a73e8;
color: white;
border-radius: 4px;
cursor: pointer;
}
</style>
这段代码实现了在Vue中使用高德地图的基本功能:搜索位置并在地图上标记点,同时点击标记点可以弹窗显示位置详情。代码中使用了Element UI的<el-input>
和<el-button>
组件来简化表单和按钮的创建过程。
评论已关闭