绘制 MKPolyline 更准确

Drawing MKPolyline to be more accurate

所以我正在创建一个应用程序来跟踪用户的 运行宁路线。我要显示一条折线,表示用户在 运行 的位置,位于用户开始时删除的开始注释和用户单击完成按钮时删除的结束注释之间。看到有人可以 运行 几乎在任何地方,有没有办法绘制一条不限于主要道路和街道的折线?例如,如果某个人 运行 在没有主要 roads/streets 的地方,我将如何在地图上显示穿过该区域的折线? (见图片)或者在 swift 中甚至不可能吗?

此外,是否有可能弥补这些差距?

这是我渲染折线的代码:

func drawPolyline() {
   guard let startingCoordinate = self.startingCoordinate, let endingCoordinate = self.endingCoordinate else { return }
   let request = MKDirections.Request()
   request.source = MKMapItem(placemark: MKPlacemark(coordinate: startingCoordinate))
   request.destination = MKMapItem(placemark: MKPlacemark(coordinate: endingCoordinate))
   request.transportType = .walking
        
   let directions = MKDirections(request: request)
   directions.calculate { [weak self] (response, error) in
      guard let self = self else { return }
      guard error == nil else { return }
      guard response != nil else { return }
            
      if let route = response?.routes.first {
         self.mapView.addOverlay(route.polyline)
         self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, edgePadding: UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15), animated: true)
      }
    }
  }

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
   let renderer = MKPolylineRenderer(overlay: overlay               
   renderer.strokeColor = .systemBlue
   renderer.lineWidth = 3
   return renderer
}

// code to get coordinate for annotations
guard let coordinate = locationManager.location?.coordinate else { return }
let annotation = MapAnnotation(title: title, coordinate: coordinate) 
mapView.addAnnotation(annotation)

每次更改时您都会获得更新的位置,您可以建立一个位置数组,或将它们存储在数据库中以供以后检索。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    // the last location presented here is the current position of the runner
    self.locations.append(locations.last)
    // store this in a database, or as a class variable
    
}

您可以在初始化位置管理器时设置所需的精度

locationManager.desiredAccuracy = kCLLocationAccuracyBest

然后当您创建地图时,创建一条线显示 运行ner 的路线

let polyline = MKPolyline(coordinates: self.locations, count: self.locations.count)
self.mapView.addOverlay(polyline)

这是一个输出示例 - 终点似乎在 运行 的中间,但那是因为我正准备回家