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

Swift中导航路线Polyline无法删除的问题求助

解决Swift中MKMapView旧Polyline无法删除的问题

嘿,我之前也踩过这个坑!你现在的问题核心出在**rotapoly变量的实例管理**上——每次调用showRoute时,你都把rotapoly直接替换成了新的route.polyline,这就导致之前显示在地图上的旧折线实例被彻底弄丢了。等下次调用mapView.remove(rotapoly)时,你移除的其实是刚创建的新折线(甚至可能是nil,如果第一次调用前没初始化的话),根本碰不到真正要删掉的旧路线。

解决方案:用数组保存所有已添加的折线

最稳妥的方式是用一个数组来记录所有添加到地图上的路线折线,这样每次绘制新路线前,就能一次性清除所有旧的:

第一步:修改变量定义

把原来单个的rotapoly改成一个数组,同时新增一个变量管理当前的路线请求,避免重复请求导致的混乱:

// 替换原来的rotapoly定义
private var routePolylines: [MKPolyline] = []
// 管理当前的路线请求,防止重复发起
private var currentDirections: MKDirections?

第二步:更新showRoute方法

在绘制新路线前,先移除所有旧折线,再添加新的并保存到数组:

func showRoute(_ response: MKDirectionsResponse) {
    // 1. 先移除所有旧的折线实例
    routePolylines.forEach { mapView.remove($0) }
    routePolylines.removeAll()
    
    // 2. 添加新路线的折线并保存到数组
    for route in response.routes {
        let polyline = route.polyline
        mapView.add(polyline, level: MKOverlayLevel.aboveRoads)
        routePolylines.append(polyline)
        
        for step in route.steps {
            print(step.instructions)
        }
    }
}

第三步:优化路线请求逻辑

在发起新的路线请求前,取消之前未完成的请求,避免地图上出现多条意外路线:

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    cizim = 1
    let capital = view.annotation as! Station
    
    guard let locValue = locationManager.location?.coordinate else {
        print("无法获取当前位置")
        return
    }
    
    let neresi = CLLocationCoordinate2D(latitude: capital.latitude, longitude: capital.longitude)
    let nerdeyim = locValue // 简化写法
    
    let request = MKDirectionsRequest()
    request.source = MKMapItem(placemark: MKPlacemark(coordinate: nerdeyim))
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate: neresi))
    request.requestsAlternateRoutes = true
    request.transportType = .walking
    
    // 取消之前未完成的请求
    currentDirections?.cancel()
    let directions = MKDirections(request: request)
    currentDirections = directions
    
    directions.calculate { [unowned self] response, error in
        guard let unwrappedResponse = response else {
            print("路线请求失败:\(error?.localizedDescription ?? "未知错误")")
            return
        }
        
        if !unwrappedResponse.routes.isEmpty {
            self.showRoute(unwrappedResponse)
        }
    }
}

为什么这样有效?

  • 数组routePolylines会完整保存所有添加到地图上的折线实例,不会因为新路线的创建而丢失旧实例。
  • 每次绘制新路线前,先遍历数组移除所有旧折线,确保地图上没有残留的路线。
  • 新增的currentDirections变量可以避免同时发起多个路线请求,防止地图上出现混乱的多条路线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:04:34