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.909longitude舆图中心经度116.397scale缩放级别(默认16)14markers标记点数组见上方示例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 简化了多端舆图开发,但需注意平台差异设置。发起优先测试核心功能在各端的表现,再渐渐完满高级功能。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |