You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用URL Scheme调用Google Maps:起点显示正常,终点显示异常

排查Google Maps URL Scheme终点显示异常的问题

看起来你的Google Maps URL Scheme调用出了问题,我帮你梳理几个关键的排查点,尤其是最可能导致终点异常的核心原因:

1. URL中的HTML转义字符是核心问题

你在拼接URL时用了&,这是HTML里的转义字符,但直接用于URL Scheme调用时,Google Maps会把它识别为地址参数的一部分,导致daddr(终点)参数无法被正确解析!这大概率是终点显示异常的罪魁祸首。

错误写法:

let urlString = "comgooglemaps://?saddr=" + "\(srcLat),\(strLong)" + "&daddr=" + "\(destLat),\(destLong)" + "&directionsmode=driving"

修正为直接使用&:

let urlString = "comgooglemaps://?saddr=\(srcLat),\(srcLong)&daddr=\(destLat),\(destLong)&directionsmode=driving"

2. 变量名拼写错误(潜在坑)

你把起点经度的变量命名为strLong,明显是srcLong的笔误——虽然这个不会直接导致当前的终点问题,但后续维护时容易引发其他bug,建议修正:

let srcLong:Float = ((longitude as NSString?)?.floatValue)!

3. 强制解包的风险

代码里大量使用!强制解包,如果dictionry(这里还有个拼写错误,应该是dictionary)里的经纬度字段为nil,或者传入的latitude/longitude为空,不仅会崩溃,还可能导致数值异常。建议用可选绑定做安全处理:

guard let destLatStr = dictionary["Latitude"] as? NSString,
      let destLat = destLatStr.floatValue,
      let destLongStr = dictionary["Longitude"] as? NSString,
      let destLong = destLongStr.floatValue,
      let srcLatStr = latitude as? NSString,
      let srcLat = srcLatStr.floatValue,
      let srcLongStr = longitude as? NSString,
      let srcLong = srcLongStr.floatValue else {
    // 这里可以加个提示,比如告诉用户位置信息无效
    return
}

4. Float精度不足的问题

Float的精度有限,当经纬度数值精度较高时,转字符串可能会丢失精度,导致Google Maps定位偏差。建议改用Double类型存储经纬度,更符合GPS数据的精度需求:

let destLat: Double = (dictionary["Latitude"] as? NSString)?.doubleValue ?? 0.0
let destLong: Double = (dictionary["Longitude"] as? NSString)?.doubleValue ?? 0.0
let srcLat: Double = (latitude as? NSString)?.doubleValue ?? 0.0
let srcLong: Double = (longitude as? NSString)?.doubleValue ?? 0.0

完整修正后的代码示例

// 先修正字典拼写错误,确保是dictionary
guard let destLatStr = dictionary["Latitude"] as? NSString,
      let destLat = destLatStr.doubleValue,
      let destLongStr = dictionary["Longitude"] as? NSString,
      let destLong = destLongStr.doubleValue,
      let srcLatStr = latitude as? NSString,
      let srcLat = srcLatStr.doubleValue,
      let srcLongStr = longitude as? NSString,
      let srcLong = srcLongStr.doubleValue else {
    print("位置参数无效,请检查输入")
    return
}

let urlString = "comgooglemaps://?saddr=\(srcLat),\(srcLong)&daddr=\(destLat),\(destLong)&directionsmode=driving"

guard let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) else {
    print("无法打开Google Maps,请检查是否已安装应用")
    return
}

UIApplication.shared.open(url)

优先修正URL里的&为&,应该就能解决终点显示异常的问题了,其他的点是帮你优化代码的稳定性和准确性。

内容的提问来源于stack exchange,提问作者Vandana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:27:21