Swift 3:如何删除Google地图中的跟踪折线

Swift 3: How to remove the tracked polyline in Google map

我已经绘制了多段线,但我不知道什么编码可以删除 google 地图中的跟踪多段线。 我正在尝试在下面进行一些编码。


这是行不通的。

var polyline = GMSPolyline()
   polyline.map = nil 

这正在努力删除跟踪的多段线,但是当我制作标记并点击它时,标记无法传播信息 window。

mapView.clear()

谢谢

解决方案:

  1. 创建折线:teaching polyline by GoogleMapsAPIs
  2. 创建变量oldPolylineArr/oldPolyline类型GMSPolyline/GMSPolyline_Array
  3. 将折线存储到旧折线
  4. 删除折线

示例编码:

//Step 1:
var mapView = GMSMapView()
let path = GMSMutablePath()
path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
path.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
path.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))
path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
let rectangle = GMSPolyline(path: path)

//Step 2:
var oldPolylineArr = [GMSPolyline]()

Array

//Step 3:
oldPolyline.append(rectangle)

//Step 4:
for p in (0 ..< oldPolylineArr.count) {
    oldPolylineArr[p].map = nil
}

is NOT Array

//Step 3:
oldPolyline = polyline

//Step 4:
oldPolyline.map = nil

也许更好的解决方案: 将你的 routePolyline 定义为一个可选变量,然后每次你想给它分配一个路径时,用 if let... 检查它并将 map 设置为 nil

if let routePolyline = routePolyline {
        routePolyline.map = nil
    }

// create new polyline
let path: GMSPath = GMSPath(fromEncodedPath: p)!
routePolyline = GMSPolyline(path: path)
routePolyline?.map = mapView

下面是从 google 地图 iOS Swift 中移除移动折线的方法:

var oldPolyLines = [GMSPolyline]() /* Global Array Variable of your Class */

在下面的代码中解析路线并从 API 方向获取新折线。

if self.oldPolyLines.count > 0 {
    for polyline in self.oldPolyLines {
        polyline.map = nil
    }
}
self.oldPolyLines.append(yourNewPolyline)
yourNewPolyLine.map = self.mapView

这是我的示例代码 我正在使用 GoogleMapDirectionLib pod 导航

https://github.com/ngominhtrint/GoogleMapDirectionLib

import UIKit
import GoogleMaps
import GoogleMapDirectionLib
class MapVC: UIViewController, GMSMapViewDelegate{


//MARK:- outlets
@IBOutlet weak var map : GMSMapView!
var flag : Bool = false
//MARK:-Maps Variables
public var locationManager: CLLocationManager!
var path = GMSMutablePath()
var myGMSPolyline : GMSPolyline!
var polyline : GMSPolyline!
var pathIndex = 0
var ponits : String?
let marker = GMSMarker()
let destinationLocationLat = 31.584478
let destinationLocationLong = 74.388419
var moveCamera : Bool = true

//MARK:-Lifecycles

override func viewDidLoad() {
    super.viewDidLoad()
    intlizeLocationManager()
    map.isMyLocationEnabled = true
    if CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways{
        let fromLoc = CLLocationCoordinate2DMake((locationManager.location?.coordinate.latitude)!, (locationManager.location?.coordinate.longitude)!)
        let toLoc = CLLocationCoordinate2DMake(destinationLocationLat,destinationLocationLong)
        
        Direction(from: fromLoc , to: toLoc)
    }
    
}
func intlizeLocationManager(){
    locationManager = CLLocationManager()
    map.delegate = self
    map.settings.myLocationButton = true
    locationManager?.delegate = self
    locationManager?.requestAlwaysAuthorization()
    locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation
    locationManager?.requestWhenInUseAuthorization()
    locationManager?.allowsBackgroundLocationUpdates = true
    locationManager?.startUpdatingLocation()
    locationManager.startMonitoringSignificantLocationChanges()
}

}

//MARK:- 方向API调用

extension MapVC : DirectionCallback{

func Direction(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) {
    
    GoogleDirection.withServerKey(apiKey: "Your google Map API Key")
        .from(origin: CLLocationCoordinate2D(latitude: source.latitude, longitude: source.longitude))
        .to(destination: CLLocationCoordinate2D(latitude: destination.latitude, longitude: destination.longitude))
        .optimizeWaypoints(optimize: true)
        .avoid(avoid: AvoidType.FERRIES)
        .avoid(avoid: AvoidType.HIGHWAYS)
        .avoid(avoid: AvoidType.TOLLS)
        .avoid(avoid: AvoidType.INDOOR)
        .optimizeWaypoints(optimize: true)
        .language(language: Language.kLanguage_en.rawValue)
        .transportMode(transportMode: TransportMode.DRIVING)
        .execute(callback: self)
}

func onDirectionSuccess(direction: DirectionMap) {
    if(direction.isOK()) {
        //here start out Work
        addMarker()
        // Draw polyline
        let routes = direction.routes
        var legs = [Leg]()
        OperationQueue.main.addOperation({
            for route in routes{
                let routeOverviewPolyline =   route.overviewPolyline
                legs = route.legs
                self.ponits = routeOverviewPolyline?.rawPoints
                self.path = GMSMutablePath.init(fromEncodedPath: self.ponits!)!
                self.myGMSPolyline = GMSPolyline(path: self.path)
            }
            
            var steps = [Step]()
            for leg in legs{
                
                print(leg.distance?.text as Any)
                print(leg.duration?.text)
                for steps in steps {
                    print(steps.distance)
                    print(steps.duration)
                    print(steps.htmlInstrution)
                    print(steps.maneuver)
                }
                
            }
            
            
            self.updateTravelledPath(currentLoc: CLLocationCoordinate2DMake ((self.locationManager.location?.coordinate.latitude)! , (self.locationManager.location?.coordinate.longitude)!))
            
            
            
            
        })
    } else {
        // Do something
    }
}

func onDirectionFailure(error: Error) {
    print("fail")
}

}

//标记:- 核心位置

 extension MapVC : CLLocationManagerDelegate{


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if !isInRoute(posLL: manager.location!.coordinate , path: path){
        let fromLoc = CLLocationCoordinate2DMake((manager.location!.coordinate.latitude), (manager.location!.coordinate.longitude))
        let toLoc = CLLocationCoordinate2DMake(destinationLocationLat,destinationLocationLong)
        Direction(from: fromLoc, to: toLoc)
    }
    
    else{
        self.updateTravelledPath(currentLoc: CLLocationCoordinate2DMake ((manager.location?.coordinate.latitude)! , ( manager.location?.coordinate.longitude)!))
    }
    if moveCamera{
        let userLocation = locations.last
        let camera = GMSCameraPosition.camera(withTarget: CLLocationCoordinate2DMake(userLocation!.coordinate.latitude, userLocation!.coordinate.longitude), zoom: 17, bearing: getBearingBetweenTwoPoints(point1: CLLocationCoordinate2DMake(userLocation!.coordinate.latitude, userLocation!.coordinate.longitude), point2:CLLocationCoordinate2DMake(destinationLocationLat,destinationLocationLong)), viewingAngle: 45)
        map.camera = camera
    }
    
}

func degreesToRadians(degrees: Double) -> Double { return degrees * .pi / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / .pi }

func getBearingBetweenTwoPoints(point1 : CLLocationCoordinate2D, point2 : CLLocationCoordinate2D) -> Double {
    
    let lat1 = degreesToRadians(degrees: point1.latitude)
    let lon1 = degreesToRadians(degrees: point1.longitude)
    
    let lat2 = degreesToRadians(degrees: point2.latitude)
    let lon2 = degreesToRadians(degrees: point2.longitude)
    
    let dLon = lon2 - lon1
    
    let y = sin(dLon) * cos(lat2)
    let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
    let radiansBearing = atan2(y, x)
    
    return radiansToDegrees(radians: radiansBearing)
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .restricted:
        print("Location access was restricted.")
    case .denied:
        print("User denied access to location.")
    case .notDetermined:
        print("User denied access to location.")
    case .authorizedAlways:
        print("User denied access to location.")
        locationManager.startUpdatingLocation()
    case .authorizedWhenInUse:
        print("Location status is OK.")
        locationManager.startUpdatingLocation()
    @unknown default:
        fatalError()
    }
}

func addMarker(){
    let customerIcon = self.imageWithImage(image: #imageLiteral(resourceName: "location2"), scaledToSize: CGSize(width: 32.0, height: 32.0))
    let dmarker = GMSMarker()
    dmarker.icon = customerIcon
    dmarker.position = CLLocationCoordinate2DMake(31.584478,74.388419)
    dmarker.map = self.map
    
}
func imageWithImage(image:UIImage, scaledToSize newSize:CGSize) -> UIImage{
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
    image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return newImage
}
func updateTravelledPath(currentLoc: CLLocationCoordinate2D){
    var index = 0
    for i in 0..<self.path.count(){
        let pathLat = Double(self.path.coordinate(at: i).latitude).rounded(toPlaces: 3)
        let pathLong = Double(self.path.coordinate(at: i).longitude).rounded(toPlaces: 3)
        
        let currentLat = Double(currentLoc.latitude).rounded(toPlaces: 3)
        let currentLong = Double(currentLoc.longitude).rounded(toPlaces: 3)
        
        if currentLat == pathLat && currentLong == pathLong{
            index = Int(i)
            break   //Breaking the loop when the index found
        }
    }
    
    //Creating new path from the current location to the destination
    let newPath = GMSMutablePath()
    for i in index..<Int(self.path.count()){
        newPath.add(self.path.coordinate(at: UInt(i)))
    }
    self.path = newPath
    if self.polyline != nil{
        polyline.map = nil
    }
    
    self.polyline = GMSPolyline(path: self.path)
    self.polyline.strokeColor = #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
    self.polyline.strokeWidth = 3.5
    self.polyline.map = self.map!
}

func isInRoute(posLL: CLLocationCoordinate2D, path: GMSPath) -> Bool
{
    let geodesic = true
    let tolerance: CLLocationDistance = 100
    let within100Meters = GMSGeometryIsLocationOnPathTolerance(posLL, path, geodesic, tolerance)
    return within100Meters
}
func mapView(_ mapView: GMSMapView, didTapMyLocation location: CLLocationCoordinate2D) {
    let camera = GMSCameraPosition.camera(withTarget: CLLocationCoordinate2DMake(location.latitude, location.longitude), zoom: 17, bearing: getBearingBetweenTwoPoints(point1: CLLocationCoordinate2DMake(location.latitude, location.longitude), point2:CLLocationCoordinate2DMake(destinationLocationLat,destinationLocationLong)), viewingAngle: 45)
    moveCamera = true
    map.camera = camera
}
func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
    if flag{
        moveCamera = false
        flag = true
    }
}
}

extension Double {
// Rounds the double to decimal places value
func rounded(toPlaces places:Int) -> Double {
    let divisor = pow(10.0, Double(places))
    return (self * divisor).rounded() / divisor
}}