H5 唤起高德/百度地图APP

6,796 阅读1分钟

h5 唤起地图应用主要是通过跳转 scheme 来打开手机中已安装的 APP,需要区分平台和手机系统对应的 scheme。

1、获取地点的经纬度

跳转地图app大都需要地点的经纬度,所以我们这里直接通过高德地理编码 API 查询点所在的经纬度。

首先需要申请一个 Web 服务 API 类型 Key ,申请地址链接

调用方式示例如下:

request({
  type: 'get',
  url: `https://restapi.amap.com/v3/geocode/geo?key=上面申请的key&address=地点&output=JSON`,
}).then(data => {
  if (data.status === '1' && data.geocodes[0] && data.geocodes[0].location) {
    console.log('经纬度', data.geocodes[0].location)
  }else{
    console.log('无法获取位置信息,请确认填写的地点是否有误')
  }
});

2、区分平台和系统找到对应的 scheme

// 获取地图scheme, 经纬度坐标类型要求为gcj02不然位置会有偏差from 从哪里
const getMapScheme = (from, to, mapType = "gaode") => {
  const u = navigator.userAgent;
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端

  const andriodBaidu = (to) => {
    return `bdapp://map/direction?destination=name:${to.name}|latlng:${to.latitude},${to.longitude}&coord_type=gcj02&mode=driving&src=andr.jianghu.jianhao`
  }

  const iOSBaidu = (to) => {
    return `baidumap://map/direction?destination=name:${to.name}|latlng:${to.latitude},${to.longitude}&coord_type=gcj02&mode=driving&src=ios.jianghu.jianhao`
  }

  const andriodGaode = (to) => {
    return `amapuri://route/plan/?sourceApplication=mhc&dlat=${to.latitude}&dlon=${to.longitude}&dname=${to.name}&dev=0&t=0`
  }

  const iOSGaode = (to) => {
    return `iosamap://path?sourceApplication=mhc&dlat=${to.latitude}&dlon=${to.longitude}&dname=${to.name}&dev=0&t=0`
  }
  if(mapType == "baidu") {
    if(isAndroid) {
      return andriodBaidu(to)
    } else {
      return iOSBaidu(to)
    }
  } else if(mapType == "gaode") {
    if (isAndroid) {
      return andriodGaode(to)
    } else {
      return iOSGaode(to)
    }
  }
}

3、跳转 scheme 唤起地图 app

我尝试的结果是似乎只支持通过 a 标签的方式跳转,如果大家通过 js 方法跳转成功的话记得留言给我。

js 部分:
const position = data.geocodes[0].location // 上面拿到的经纬度
const latitude = position.split(',')[1]
const longitude = position.split(',')[0]
const from = {}  // 出发地,不传则默认当前位置
const to = { name: address, longitude, latitude }; // address:目的地
const gaodeUrl = getMapScheme(from, to, "gaode")
const baiduUrl = getMapScheme(from, to, "baidu")

html 部分:
<a href={gaodeUrl}> 高德路线规划 <a/>
<a href={baiduUrl}> 百度路线规划 <a/>

参考文档: