需求:在地图上标注用户当前位置,并显示位置信息。
设计图:
思路:
uniapp 地图组件mapAPI地址:
https://uniapp.dcloud.io/component/map
注意官方的话,很重要:
地图组件用于展示地图,而定位API只是获取坐标,请勿混淆两者。
地图组件用于展示地图,而定位API只是获取坐标,请勿混淆两者。
地图组件用于展示地图,而定位API只是获取坐标,请勿混淆两者。
啥意思呢 ?就是地图组件只是负责展示地图,不负责获取坐标,要额外去获取坐标和地理位置。当时没看懂,百度了很久很久很久很久,才知道地图和定位,是分开的两个功能。
1.首先,展示地图 (官方代码)
<template>
<view>
<view class="page-body">
<view class="page-section page-section-gap">
<map style="width: 100%; height: 300px;"
:latitude="latitude"
:longitude="longitude"
:markers="covers"
>
</map>
</view>
</view>
</view>
</template>
export default {
data() {
return {
id:0, // 使用 marker点击事件 需要填写id
title: 'map',
latitude: 39.909,
longitude: 116.39742,
covers: [{
latitude: 39.909,
longitude: 116.39742,
iconPath: '../../../static/location.png'
}]
}
},
methods: {}
}
2. markers 标记点数据covers 、中心经度longitude 、中心纬度latitude都是写死的,需要动态获取当前用户的定位。
获取定位的方法:
https://uniapp.dcloud.io/api/location/location?id=getlocation
uni.getLocation({
/*
map组件默认为国测局坐标gcj02,
调用 uni.getLocation返回结果传递给组件时,需指定 type 为 gcj02
*/
type: "gcj02",
altitude: true,
geocode: true,
success: (e) => {
// 定位得到的经纬度
let longitude = e.longitude
let latitude = e.latitude
// 设置中心经纬度
this.longitude = longitude
this.latitude = latitude
// 画出定位位置
this.covers[0] = {
longitude,
latitude,
iconPath: "../../static/baseIcon/dingwei.png",
}
/* 抛出获取到地址的省市区数据 */
let address = e.province + e.city + e.street + e.streetNum + e.poiName
}
})
所有代码:
<!-- 地图组件,不是定位组件 -->
<template>
<view class="general-map-contain">
<map
style="width: 100%; height: 400rpx"
:latitude="latitude"
:longitude="longitude"
:markers="covers"
/>
</view>
</template>
<script>
export default {
data() {
return {
// 中心纬度
latitude: '',
// 中心经度
longitude: '',
// 标记点
covers: [],
}
},
mounted() {
this.$nextTick(() => {
// 进入页面,获取用户经纬度地址
this.getMyLocation();
});
},
methods: {
getMyLocation() {
uni.getLocation({
/*
map组件默认为国测局坐标gcj02,
调用 uni.getLocation返回结果传递给组件时,需指定 type 为 gcj02
*/
type: "gcj02",
altitude: true,
geocode: true, {
success: (e) => {
// 中心经纬度
this.longitude = longitude
this.latitude = latitude
console.log('定位所有数据:',e)
let longitude = e.longitude
let latitude = e.latitude
// 标注定位位置
this.covers[0] = {
longitude,
latitude,
iconPath: "../../static/baseIcon/dingwei.png",
}
/* 地址的省市区具体信息 */
let address = e.province + e.city + e.street + e.streetNum + e.poiName
}
})
}
}
}
</script>