2017-06-06 73 views
1

我正在GoogleMap中製作GMSPolyline。當我想通過編碼polyline.map = nil刪除GMSPolyline,但它不能爲我工作。我在下面複製一些編碼。我如何刪除Swift 3中的GMSPolyline

(前要加上標記,我需要刪除折線只)

謝謝您的幫助!

我的編碼:

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { 
    //MARK: create the GMSPolyline 
    let polyline = GMSPolyline() 
    //MARK: remove the old polyline from the GoogleMap 
    polyline.map = nil 

    let origin = "\(mapView.myLocation!.coordinate.latitude),\(mapView.myLocation!.coordinate.longitude)" 
    let destination = "\(marker.position.latitude),\(marker.position.longitude)" 

    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving" 

    Alamofire.request(url).responseJSON { response in 

     let json = JSON(data: response.data!) 
     let routes = json["routes"].arrayValue 

     //MARK: print route using Polyline 
     for route in routes 
     { 
      let routeOverviewPolyline = route["overview_polyline"].dictionary 
      let points = routeOverviewPolyline?["points"]?.stringValue 
      let path = GMSPath(fromEncodedPath: points!) 
      polyline = GMSPolyline(path: path) 
      polyline.strokeWidth = 4 
      polyline.strokeColor = UIColor.yellow 
      polyline.isTappable = true 
      polyline.map = self.mapView 
     } 
    } 
    return false 
} 

回答

0

你應該在地圖上添加新的折線之前清除地圖。 GMSMapView中

/** 

Clears all markup that has been added to the map, including markers, polylines and ground overlays. 
This will not clear the visible location dot or reset the current mapType. 

*/ 

clear()函數試試這個

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { 
    //MARK: create the GMSPolyline 
    let polyline = GMSPolyline() 
    //MARK: remove the old polyline from the GoogleMap 
    mapView.clear() 
    //TODO:- Redraw all marker here. 
    let origin = "\(mapView.myLocation!.coordinate.latitude),\(mapView.myLocation!.coordinate.longitude)" 
    let destination = "\(marker.position.latitude),\(marker.position.longitude)" 

    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving" 

    Alamofire.request(url).responseJSON { response in 

     let json = JSON(data: response.data!) 
     let routes = json["routes"].arrayValue 

     //MARK: print route using Polyline 
     for route in routes 
     { 
      let routeOverviewPolyline = route["overview_polyline"].dictionary 
      let points = routeOverviewPolyline?["points"]?.stringValue 
      let path = GMSPath(fromEncodedPath: points!) 
      polyline = GMSPolyline(path: path) 
      polyline.strokeWidth = 4 
      polyline.strokeColor = UIColor.yellow 
      polyline.isTappable = true 
      polyline.map = self.mapView 
     } 
    } 
    return false 
} 
+1

我添加了標記到地圖上,如果我使用mapView.clear()巫婆將被刪除分數? – ShingHung

+0

@ShingHung在清除mapView之後,您必須重新繪製所有標記。然後它將以您期望的方式工作。還編輯了答案。請看看這個。 – SuryaKantSharma

+0

從JSON獲取標記的滯後和緯度,如果我重繪標記,則使用更多數據。 – ShingHung