在UniApp中使用高德地图可以通过以下几种方式实现:
1. 使用WebView嵌入高德地图网页版
<template>
<view>
<web-view src="https://uri.amap.com/marker?position=经度,纬度&name=位置名称"></web-view>
</view>
</template>
2. 使用高德地图小程序SDK(适用于微信小程序平台)
- 首先在
manifest.json
中配置小程序权限:
{
"mp-weixin": {
"appid": "你的小程序AppID",
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
},
"requiredPrivateInfos": ["getLocation", "chooseLocation"]
}
}
- 在页面中使用:
<template>
<view>
<map
id="myMap"
style="width: 100%; height: 300px;"
latitude="{{latitude}}"
longitude="{{longitude}}"
markers="{{markers}}"
show-location
></map>
</view>
</template>
<script>
export default {
data() {
return {
latitude: 39.908823,
longitude: 116.39747,
markers: [{
id: 1,
latitude: 39.908823,
longitude: 116.39747,
title: '北京市'
}]
}
},
onLoad() {
// 获取当前位置
uni.getLocation({
type: 'gcj02',
success: (res) => {
this.latitude = res.latitude
this.longitude = res.longitude
this.markers[0] = {
id: 1,
latitude: res.latitude,
longitude: res.longitude,
title: '当前位置'
}
}
})
}
}
</script>
3. 使用第三方插件(如uni-app-map)
- 安装插件:
npm install @dcloudio/uni-ui
- 在页面中使用:
<template>
<view>
<uni-map
:latitude="latitude"
:longitude="longitude"
:markers="markers"
@markertap="onMarkerTap"
></uni-map>
</view>
</template>
<script>
import uniMap from '@dcloudio/uni-ui/lib/uni-map/uni-map.vue'
export default {
components: { uniMap },
data() {
return {
latitude: 39.908823,
longitude: 116.39747,
markers: [{
id: 1,
latitude: 39.908823,
longitude: 116.39747,
title: '北京市'
}]
}
},
methods: {
onMarkerTap(e) {
console.log('标记点被点击', e)
}
}
}
</script>
注意事项
- 不同平台的地图实现方式可能不同,需要进行条件编译
- 使用地图功能需要申请相关API密钥
- 在H5端可能需要直接使用高德地图JavaScript API
- 获取用户位置需要权限声明和用户授权
H5端使用高德地图JavaScript API
- 在index.html中引入高德地图JS API:
<script src="https://webapi.amap.com/maps?v=2.0&key=你的高德地图Key"></script>
- 创建地图组件:
<template>
<view>
<view id="mapContainer" style="width: 100%; height: 300px;"></view>
</view>
</template>
<script>
export default {
mounted() {
// #ifdef H5
this.initAMap()
// #endif
},
methods: {
initAMap() {
const map = new AMap.Map('mapContainer', {
zoom: 11,
center: [116.397428, 39.90923]
})
// 添加标记
const marker = new AMap.Marker({
position: [116.397428, 39.90923],
title: '北京市'
})
map.add(marker)
}
}
}
</script>
以上是在UniApp中使用高德地图的几种常见方法,具体实现需要根据你的项目需求和目标平台进行调整。