vue中实现高德 地图定位功能
index.html
<template>
<div id="app">
<div id="container"></div>
<div>
<p>经度:{{ location.lng }}</p>
<p>纬度:{{ location.lat }}</p>
<p>地址:{{ location.address }}</p>
</div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
location: {
lng: '', // 经度
lat: '', // 纬度
address: '',
},
// geoCoder: ''
}
},
mounted() {
this.getLocation()
// this.getLngLatLocation()
},
methods: {
getLocation() {
const _this = this
AMap.plugin(['AMap.Geolocation', 'AMap.Geocoder'], function () {
var geolocation = new AMap.Geolocation({
// 是否使用高精度定位,默认:true
enableHighAccuracy: true,
// 设置定位超时时间,默认:无穷大
timeout: 10000,
// 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)
buttonOffset: new AMap.Pixel(10, 20),
// 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
zoomToAccuracy: true,
// 定位按钮的排放位置, RB表示右下
buttonPosition: 'RB',
})
// var map = new AMap.Map("container", {
// resizeEnable: true
// })
// 地址逆解析
var geocoder = new AMap.Geocoder({
city: '010', //城市设为北京,默认:“全国”
radius: 1000, //范围,默认:500
})
// var marker = new AMap.Marker();
function regeoCode() {
var lnglat = [_this.location.lng, _this.location.lat]
// map.add(marker)
// marker.setPosition(lnglat)
geocoder.getAddress(lnglat, function (status, result) {
if (status === 'complete' && result.regeocode) {
console.log('查询地址成功', result)
_this.location.address = result.regeocode.formattedAddress
} else {
console.log('根据经纬度查询地址失败', result)
}
})
}
geolocation.getCurrentPosition(function (status, result) {
console.log('定位状态和结果', status, result)
if (status == 'complete') {
console.log('定位成功', result)
// _this.signAddress = result.formattedAddress
_this.location.lat = result.position.lat
_this.location.lng = result.position.lng
// _this.getAddress()
regeoCode()
} else {
console.log('定位失败:' + result.message)
_this.getLngLatLocation()
}
})
})
},
// // IP定位获取当前城市信息
// getLngLatLocation() {
// AMap.plugin("AMap.CitySearch", function () {
// console.log('进入获取城市信息')
// var citySearch = new AMap.CitySearch()
// citySearch.getLocalCity(function (status, result) {
// console.log('获取城市信息', status, result)
// if (status === "complete" && result.info === "OK") {
// // 查询成功,result即为当前所在城市信息
// console.log('当前城市信息', result)
// }
// })
// })
// },
},
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了