uni-app中map的使用
一、基本使用步骤
1. 引入 map 组件
在 .vue
文件的 template
中直接使用 <map>
标签:
<template>
<view>
<map
:latitude="latitude"
:longitude="longitude"
:markers="markers"
style="width: 100%; height: 300px;"
></map>
</view>
</template>
2. 定义地图数据(在 script
中)
export default {
data() {
return {
latitude: 39.909, // 中心纬度(示例:北京)
longitude: 116.397, // 中心经度
markers: [{
id: 1,
latitude: 39.909,
longitude: 116.397,
title: "天安门",
iconPath: "/static/location.png" // 本地图标路径
}]
}
}
}
3. 核心属性说明
属性 | 作用 | 示例值 |
---|---|---|
latitude | 地图中心纬度 | 39.909 |
longitude | 地图中心经度 | 116.397 |
scale | 缩放级别(默认16) | 14 |
markers | 标记点数组 | 见上方示例 |
polyline | 路线(折线) | 需定义坐标点数组 |
controls | 地图控件(如缩放按钮) | 可自定义按钮位置/样式 |
二、多端配置与适配
1. 微信小程序
- 必须配置:在
manifest.json
中添加地图权限:
"mp-weixin": {
"appid": "你的小程序ID",
"permission": {
"scope.userLocation": {
"desc": "需要获取您的位置以展示地图"
}
}
}
- 注意:微信小程序使用腾讯地图,需用户授权定位。
2. App端(Android/iOS)
- 配置地图服务商(二选一):
- 高德地图(推荐):
- 申请高德开发者账号,获取
AppKey
。 - 在
manifest.json
中配置:
"app-plus": { "modules": { "Maps": {} }, "distribute": { "android": { "maps": { "amap": { "appkey_android": "你的高德AppKey" } } }, "ios": { "maps": { "amap": { "appkey_ios": "你的高德AppKey" } } } } }
- 申请高德开发者账号,获取
- 百度地图:
- 类似高德,需替换为百度地图的配置。
- 高德地图(推荐):
3. H5 网页端
当在H5端预览map组件的时候,你需要配置地图的key:
否则报错:
- 默认使用浏览器内置的 Geolocation API,可能需用户手动允许定位。
- 注意:H5 地图功能较弱(如不支持个性化样式),建议测试兼容性。
三、多端差异处理
1. 动态判断平台
// 在代码中判断平台,适配不同逻辑
if (uni.getSystemInfoSync().platform === 'android') {
// Android 特定代码
} else if (uni.getSystemInfoSync().platform === 'ios') {
// iOS 特定代码
}
2. 通用适配方案
- 图标路径:建议使用绝对路径(
/static/xxx.png
),避免多端路径问题。 - API 差异:例如
getLocation
方法在各端返回值可能不同,需统一处理:
uni.getLocation({
type: 'gcj02', // 统一坐标系(推荐)
success: (res) => {
this.latitude = res.latitude;
this.longitude = res.longitude;
}
});
四、高级功能示例
1. 绘制折线(路线)
data() {
return {
polyline: [{
points: [
{latitude: 39.909, longitude: 116.397},
{latitude: 39.920, longitude: 116.407}
],
color: "#FF0000", // 线颜色
width: 6
}]
}
}
2. 添加交互控件
<map>
<cover-view class="controls">
<button @click="zoomIn">放大</button>
<button @click="zoomOut">缩小</button>
</cover-view>
</map>
<style>
.controls {
position: absolute;
right: 10px;
top: 10px;
}
</style>
五、常见问题
1. 地图不显示
- 检查
latitude
和longitude
是否赋值。 - App 端确认高德/百度地图 Key 配置正确。
- 微信小程序需用户授权定位。
2. 标记点图标不显示
- 使用绝对路径(如
/static/icon.png
)。 - 图标文件放在
static
目录下。
3. 跨平台样式不一致
- 使用
条件编译
针对不同平台调整样式:
/* #ifdef H5 */
map {
height: 400px; /* H5 可能需要更大高度 */
}
/* #endif */
六、官方文档参考
- uni-app Map 组件:https://uniapp.dcloud.net.cn/component/map.html
- 高德地图申请 Key:https://lbs.amap.com/
总结:uni-app 的 map
组件通过统一 API 简化了多端地图开发,但需注意平台差异配置。建议优先测试核心功能在各端的表现,再逐步完善高级功能。