前提:网站访问需要https

1、引用百度地图的js

<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=rAyx5z"></script>

其中ak需要再百度上进行申请,请自行百度

2、代码

<template>
<view>
<div>
<input v-model="customAddress" />
<a @click="addressToPoint">定位</a>
</div>
<div>
{{address}}
</div>
<div>
{{location}}
</div>
<a @click="getLocation">点击获取位置</a>
<div id="container" style="height: 500px;width: 100%"></div>
</view>
</template>
<script>
import {getToken} from "@/api/user"
import {setOpenId} from '@/utils/auth'

export default {
name: 'home',
data() {
return {
BMap: null,
// 位置信息
location: null,
address: '',
customAddress: ''
}
},
methods: {
// 获取地理定位
getLocation() {
let _this = this
navigator.geolocation.getCurrentPosition(function (position) {
let centerPointer = new BMap.Point(position.coords.longitude, position.coords.latitude)
let convertor = new BMap.Convertor()
let pointArr = []
pointArr.push(centerPointer)
convertor.translate(pointArr, 1, 5, function (data) {
if(data.status==0){
let marker = new BMap.Marker(data.points[0])
_this.BMap.centerAndZoom(data.points[0],17)
_this.BMap.addOverlay(marker)
var myGeo = new BMap.Geocoder({extensions_town: true})
// 根据坐标得到地址描述
myGeo.getLocation(data.points[0], function(result){
if (result){
_this.address = result.addressComponents.city + result.addressComponents.district + result.addressComponents.town
}
})
}
})
}, function(e) {
_this.address = "获取定位位置信息失败:" + e.message
}, {
geocode: true
})
},
addressToPoint(){
//创建地址解析器实例
let myGeo = new BMap.Geocoder()
let _this = this
let address = _this.customAddress
if (!address){
address = '川杨新苑四期'
}
// 将地址解析结果显示在地图上,并调整地图视野
myGeo.getPoint(address, function(point){
if(point){
_this.BMap.centerAndZoom(point, 17)
_this.BMap.addOverlay(new BMap.Marker(point, {title: address}))
var myGeo = new BMap.Geocoder({extensions_town: true})
// 根据坐标得到地址描述
myGeo.getLocation(point, function(result){
if (result){
_this.address = result.addressComponents.city + result.addressComponents.district + result.addressComponents.town
}
})
}else{
alert('您选择的地址没有解析到结果!')
}
}, '上海市')
},
initMap(){
let map = new BMap.Map('container')
map.centerAndZoom('上海', 11)
//开启鼠标滚轮缩放
map.enableScrollWheelZoom(true)
this.BMap = map
this.getLocation()
}
},
mounted() {
this.initMap()
}
}
</script>
<style>
div{
word-break: break-all
}
</style>
posted on 2021-12-17 17:14  田坤坤  阅读(2379)  评论(0编辑  收藏  举报