uniapp使用高德地图和百度地图导航功能

文章描述了一个使用uni框架开发的应用,展示了如何在页面中集成地图组件,获取用户位置,添加标记,并在点击事件中调用不同地图应用进行导航,包括百度地图、高德地图和腾讯地图.

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
  <view class="map-container">
    <u-navbar :title="title" :autoBack="true"> </u-navbar>
    <view class="content" style="margin-top: 150rpx">
      <map
        id="map"
        class="map"
        :show-location="true"
        :latitude="mlat"
        :longitude="mlng"
        :markers="markers"
      ></map>
    </view>
    <u-button
      class="button"
      type="primary"
      text="到这里"
      @click="gomapApp"
    ></u-button>
    <view class="loading" v-if="loading">
      <u-loading-icon text="加载中" :vertical="true"></u-loading-icon>
    </view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>
<script>
// const img = '/static/marken.png';
export default {
  data() {
    return {
      lng: "",
      lat: "",
      mlng: "",
      mlat: "",
      markers: [],
      loading: false,
      _mapContext: "",
      title: "",
      deptId: "",
    };
  },
  onReady() {},
  onLoad(params) {
    if (params.deptId) {
      this.deptId = params.deptId;
      this.title = params.title;
      this.loading = true;
      this.getdata();
      this.getlat();
    }
  },
  methods: {
    getdata() {
      this.$http("/jmis-riskassess/mine/getXYByDeptId", "GET", {
        deptId: this.deptId,
      })
        .then((res) => {
          if (res.statusCode == 200) {
            this.mlat = res.data.x;
            this.mlng = res.data.y;
            this.$nextTick(() => {
              this._mapContext = uni.createMapContext("map", this);
              // 仅调用初始化,才会触发 on.("markerClusterCreate", (e) => {})
              this._mapContext.initMarkerCluster({
                enableDefaultStyle: false,
                zoomOnClick: true,
                gridSize: 60,
                complete(res) {
                  console.log("initMarkerCluster", res);
                },
              });
              this._mapContext.on("markerClusterCreate", (e) => {
                console.log("markerClusterCreate", e);
              });
              this.addMarkers();
            });
          }
        })
        .catch(() => {
          this.$refs.uToast.show({
            type: "error",
            icon: false,
            message: "服务器异常!",
          });
        });
    },
    getlat() {
      let that = this;
      uni.getLocation({
        type: "wgs84", //返回可以用于uni.openLocation的经纬度
        success: function (res) {
          that.lat = res.latitude;
          that.lng = res.longitude;
        },
      });
    },
    addMarkers() {
      this.$nextTick(() => {
        // const positions = [
        //   {
        //     latitude: this.mlat,
        //     longitude: this.mlng,
        //   },
        // ];
        const markers = [
          {
            id: 0,
            iconPath: "/static/map2.png",
            width: 150,
            height: 150,
            latitude: this.mlat,
            longitude: this.mlng,

            joinCluster: true, // 指定了该参数才会参与聚合
            label: {
              width: 50,
              height: 30,
              borderWidth: 1,
              borderRadius: 10,
              bgColor: "#000",
              content: this.title ? this.title : "",
            },
          },
        ];
        // positions.forEach((p, i) => {
        //   markers.push(
        //     Object.assign(
        //       {},

        //       p
        //     )
        //   );
        // });
        this.markers = markers;
        this._mapContext.addMarkers({
          markers,
          clear: false,
          complete(res) {
            console.log("addMarkers", res);
          },
        });
        this.loading = false;
      });
    },
    // 打开的点击事件,传经纬度和地点名
    gomapApp() {
      let latitude = this.lat;
      let longitude = this.lng;
      let mlat = this.mlat;
      let mlng = this.mlng;
      let name = this.title;
      let url = "";
      let webUrl = "";
      if (plus.os.name == "Android") {
        //判断是安卓端
        plus.nativeUI.actionSheet(
          {
            //选择菜单
            title: "选择地图应用",
            cancel: "取消",
            buttons: [
              // { title: "腾讯地图" },
              { title: "百度地图" },
              { title: "高德地图" },
            ],
          },
          function (e) {
            switch (e.index) {
              //下面是拼接url,不同系统以及不同地图都有不同的拼接字段
              // case 1:
              //   //注意referer=xxx的xxx替换成你在腾讯地图开发平台申请的key
              //   url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=xxx`;
              //   webUrl = `https://apis.map.qq.com/uri/v1/marker?marker=coord:${latitude},${longitude}&title=${name}&addr=${name}&referer=xxx`;
              //   break;
              case 1:
                // url = `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`;
                url = `baidumap://map/direction?destination=${mlat},${mlng}&mode=driving&src=yourAppName|yourAppName&coord_type=bd09ll&name=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`;
                webUrl = `http://api.map.baidu.com/marker?location=${mlat},${mlng}&title=${name}&content=${name}&output=html&src=webapp.baidu.openAPIdemo`;
                break;
              case 2:
                url = `amapuri://route/plan?sourceApplication=maxuslife&sid=A&slat=${latitude}&slon=${longitude}&sname=起始地点&did=B&dlat=${mlat}&dlon=${mlng}&dname=${name}&dev=0&t=0`;
                // url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
                webUrl = `https://uri.amap.com/marker?position=${mlat},${mlng}&name=${name}&src=mypage&coordinate=gaode`;
                break;
              default:
                break;
            }
            if (url != "") {
              url = encodeURI(url);
              // console.log(url, '地址')
              // 打开 app 导航
              plus.runtime.openURL(url, (err) => {
                // 失败回到
                // 毕竟用户可能没有安装app但一定安装的有浏览器
                // 如果失败则说明未安装 直接 打开网页版进行导航
                let chooseMap = "";
                if (e.index == 1) {
                  chooseMap = "百度地图";
                } else if (e.index == 2) {
                  chooseMap = "高德地图";
                } else {
                  chooseMap = "腾讯地图";
                }
                uni.showModal({
                  title: "提示",
                  content:
                    "检测到您本机暂未安装" +
                    chooseMap +
                    "应用,是否要选择使用浏览器打开?",
                  confirmText: "确定", //确定文本的文字
                  cancelText: "取消", //确定文本的文字
                  showCancel: true, //没有取消按钮的弹框
                  success: function (res) {
                    if (res.confirm) {
                      plus.runtime.openURL(webUrl);
                    } else if (res.cancel) {
                      // plus.nativeUI.alert("本机未安装指定的地图应用");
                    }
                  },
                });
              });
            }
          }
        );
      } else {
        // iOS上获取本机是否安装了百度高德地图,需要在manifest里配置
        // 在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加
        //(如urlschemewhitelist:["iosamap","baidumap"])
        plus.nativeUI.actionSheet(
          {
            title: "选择地图应用",
            cancel: "取消",
            buttons: [
              // { title: "腾讯地图" },
              { title: "百度地图" },
              { title: "高德地图" },
            ],
          },
          function (e) {
            switch (e.index) {
              // case 1:
              //   url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=xxx`;
              //   break;
              case 1:
                url = `baidumap://map/marker?location=${mlat},${mlng}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
                webUrl = `http://api.map.baidu.com/marker?location=${mlat},${mlng}&title=${name}&content=${name}&output=html&src=webapp.baidu.openAPIdemo`;

                break;
              case 2:
                url = `iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${mlat}&lon=${mlng}&dev=0`;
                webUrl = `https://uri.amap.com/marker?position=${mlng},${mlat}&name=${name}&src=mypage&coordinate=gaode`;

                break;
              default:
                break;
            }
            if (url != "") {
              url = encodeURI(url);
              // console.log(url, '地址')
              // 打开 app 导航
              plus.runtime.openURL(url, (err) => {
                // 失败回到
                // 毕竟用户可能没有安装app但一定安装的有浏览器
                // 如果失败则说明未安装 直接 打开网页版进行导航
                let chooseMap = "";
                if (e.index == 1) {
                  chooseMap = "百度地图";
                } else if (e.index == 2) {
                  chooseMap = "高德地图";
                } else {
                  chooseMap = "腾讯地图";
                }
                uni.showModal({
                  title: "提示",
                  content:
                    "检测到您本机暂未安装" +
                    chooseMap +
                    "应用,是否要选择使用浏览器打开?",
                  confirmText: "确定", //确定文本的文字
                  cancelText: "取消", //确定文本的文字
                  showCancel: true, //没有取消按钮的弹框
                  success: function (res) {
                    if (res.confirm) {
                      plus.runtime.openURL(webUrl);
                    } else if (res.cancel) {
                      // plus.nativeUI.alert("本机未安装指定的地图应用");
                    }
                  },
                });
              });
            }
          }
        );
      }
    },
  },
};
</script>
<style scoped>
.content {
  width: 100%;
}

.map {
  width: 100%;
  height: 80vh;
}
.button {
  width: 95%;
  border-radius: 20rpx;
}
.loading {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  background-color: #cccccc88;
  top: 0;
  left: 0;
  z-index: 1;
}
</style>

### 集成高德地图API到UniApp开发的微信小程序 为了在 UniApp 中集成并使用高德地图 API 进行开发,需遵循特定流程来确保功能正常运作。首先,在项目初始化阶段,应注册成为高德开放平台成员,并创建应用获取对应的 Key 值。 #### 获取高德地图Key 访问 [高德开放平台](https://lbs.amap.com/) 注册账号后登录进入控制台页面,点击“创建新应用”,按照提示完成设置即可获得用于调用接口所需的 Appkey[^1]。 #### 安装依赖包 对于基于 Vue 的框架如 UniApp 来说,推荐通过 npm 或者 yarn 方式安装官方提供的 SDK 库 `amap-js-api`: ```bash npm install amap-js-api --save ``` 或者 ```bash yarn add amap-js-api ``` #### 初始化SDK实例 在 main.js 文件里引入 AMap 并配置全局变量以便后续组件可以直接引用: ```javascript import AMap from 'AMap' Vue.prototype.$AMap = AMap; ``` #### 调用位置服务函数 利用 uni-app 提供的位置相关 api 结合高德的地图能力可以轻松实现定位导航功能。下面是一个简单的例子展示如何打开指定坐标点附近的地图详情页: ```javascript // 打开目标地点 uni.openLocation({ latitude: 39.908754, longitude: 116.39751, name: '天安门广场', address: '北京市东城区东长安街', success(res){ console.log('成功', res); }, fail(err){ console.error('失败', err); } }); ``` 需要注意的是,此方法仅适用于设备已安装支持的应用程序(比如百度地图高德地图),如果未找到匹配项则会尝试默认浏览器加载网页版地图。 另外一种方式则是直接借助于高德自身的 web service 接口查询 POI 数据等信息再做处理显示给用户查看;或者是采用其 H5 页面嵌入方案快速搭建起具备基本地理信息服务的小程序界面[^2]。 #### 地图控件自定义 除了基础的地图操作外,还可以进一步定制化交互体验,例如添加标记、绘制路径规划线路等等复杂场景下的需求满足。具体可查阅文档了解更详细的参数选项说明以及最佳实践案例分析。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值