如何使用H5唤起原生地图APP(百度、高德、腾讯地图等)
要使用 H5 唤起原生地图 App(百度、高德、腾讯地图等),你需要利用 URL Schemes。每个地图 App 都定义了自己的 URL Scheme,通过在 H5 页面中构建特定的 URL 并跳转,即可唤起相应的 App。
以下是一些常用地图 App 的 URL Scheme 和使用方法示例:
1. 百度地图:
-
URL Scheme:
baidumap://
-
示例:
function openBaiduMap(longitude, latitude, name) {
const url = `baidumap://map/marker?location=${latitude},${longitude}&title=${encodeURIComponent(name)}&content=${encodeURIComponent(name)}&src=webapp`;
window.location.href = url;
}
// 例如:打开百度地图,显示名为“目的地”的标记,经度为116.404,纬度为39.915
openBaiduMap(116.404, 39.915, "目的地");
2. 高德地图:
-
URL Scheme:
iosamap://
-
示例:
function openGaodeMap(longitude, latitude, name) {
const url = `iosamap://navi?sourceApplication=webapp&backScheme=myapp://&lat=${latitude}&lon=${longitude}&name=${encodeURIComponent(name)}&dev=0`;
window.location.href = url;
}
// 例如:打开高德地图,导航到名为“目的地”的位置,经度为116.404,纬度为39.915
openGaodeMap(116.404, 39.915, "目的地");
3. 腾讯地图:
-
URL Scheme:
qqmap://
-
示例:
function openTencentMap(longitude, latitude, name) {
const url = `qqmap://map/rgeo?location=${latitude},${longitude}&name=${encodeURIComponent(name)}&coord_type=1&policy=0`;
window.location.href = url;
}
// 例如:打开腾讯地图,显示名为“目的地”的标记,经度为116.404,纬度为39.915
openTencentMap(116.404, 39.915, "目的地");
通用方法及优化:
function openMap(longitude, latitude, name, mapApp) {
let url;
switch (mapApp) {
case 'baidu':
url = `baidumap://map/marker?location=${latitude},${longitude}&title=${encodeURIComponent(name)}&content=${encodeURIComponent(name)}&src=webapp`;
break;
case 'gaode':
url = `iosamap://navi?sourceApplication=webapp&backScheme=myapp://&lat=${latitude}&lon=${longitude}&name=${encodeURIComponent(name)}&dev=0`;
break;
case 'tencent':
url = `qqmap://map/rgeo?location=${latitude},${longitude}&name=${encodeURIComponent(name)}&coord_type=1&policy=0`;
break;
default:
console.error('不支持的地图类型');
return;
}
// 使用iframe打开URL Scheme,避免直接跳转导致页面卡死
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = url;
document.body.appendChild(iframe);
setTimeout(() => {
document.body.removeChild(iframe);
}, 1000);
// 定时器检测是否唤起成功,如果失败则跳转到网页版地图
let timer = setTimeout(() => {
window.location.href = `https://uri.amap.com/marker?position=${longitude},${latitude}&name=${encodeURIComponent(name)}&src=mypage&coordinate=gaode&callnative=0`; // 默认跳转高德网页版
}, 2000);
window.addEventListener('blur', () => {
clearTimeout(timer)
});
}
openMap(116.404, 39.915, "目的地", "baidu");
关键点:
encodeURIComponent()
: 对名称进行编码,避免特殊字符导致 URL 解析错误。iframe
: 使用 iframe 打开 URL Scheme,避免页面卡死,提升用户
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)