You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

iOS模拟器自定义位置下,iPhone自带Apple Map无法显示路线问题

解决Apple Maps无法显示自定义位置到目的地路线的问题

我来帮你排查这个问题!你在iOS 10.0和11.2的iPhone 6模拟器中设置了自定义位置,但调用Apple Maps显示路线失败,主要原因是你当前的代码方向不对——直接构造MKCoordinateRegion只能设置地图显示区域,无法触发导航路线请求。下面给你两种可行的解决方案:

方案一:使用MKMapItem发起导航请求(推荐)

这是Apple官方推荐的方式,适配性更好,能直接传递起点和终点信息:

// 1. 设置你的自定义起点位置(也就是模拟器里设置的当前位置)
let startCoordinate = CLLocationCoordinate2D(latitude: 你的自定义纬度, longitude: 你的自定义经度)
let startMapItem = MKMapItem(placemark: MKPlacemark(coordinate: startCoordinate, addressDictionary: nil))
startMapItem.name = "自定义起点"

// 2. 设置目的地位置
let endCoordinate = CLLocationCoordinate2D(latitude: 26.025861, longitude: 56.089239)
let endMapItem = MKMapItem(placemark: MKPlacemark(coordinate: endCoordinate, addressDictionary: nil))
endMapItem.name = "目的地"

// 3. 发起导航请求,选择驾车路线(也可以选步行、公交等)
let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
MKMapItem.openMaps(with: [startMapItem, endMapItem], launchOptions: launchOptions)

方案二:使用Apple Maps URL Scheme

如果更倾向于用URL方式调用,也可以构造标准的Maps URL:

// 构造URL,saddr是起点坐标,daddr是终点坐标
let urlString = "http://maps.apple.com/?saddr=你的自定义纬度,你的自定义经度&daddr=26.025861,56.089239&dirflg=d"
if let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) {
    if UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
}
  • dirflg=d代表驾车路线,换成w是步行,r是公交。

模拟器注意事项

  • 确认模拟器的自定义位置已生效:打开模拟器自带的Maps应用,检查是否显示你设置的自定义位置,如果没显示,建议重启模拟器或重新设置位置。
  • iOS 10及以上的权限:确保你的App已经申请了位置权限(NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription),即使是模拟器也需要在info.plist中配置。
  • 避免依赖MKMapItem.forCurrentLocation():模拟器的“当前位置”有时候不会即时更新,手动传入自定义起点坐标更可靠。

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

火山引擎 最新活动