Comment dessiner une polyligne appropriée sur google maps

J'ai réussi à dessiner une polyligne du point a au point b, mais pour une raison quelconque, il montre une ligne linéaire et non les points de passage corrects

Voici le code

let path = GMSMutablePath() path.addLatitude(3.1970044, longitude:101.7389365) path.addLatitude(3.2058354, longitude:101.729536) let polyline = GMSPolyline(path: path) polyline.strokeWidth = 5.0 polyline.geodesic = true polyline.map = mapView 

Je m'attendais à ce que ça fasse quelques waypoints, mais ça montre juste des polylignes droites

entrez la description de l'image ici

self.googleMapsView est la vue Google Maps.

Exemple: self.getDirections ("26.9211992,75.8185761", destination: "26.8472496,75.7691909", points de passage: ["26.8686811,75.7568383"], travelMode: nul, completionHandler: nil)

Exemple: google direction lien https://maps.googleapis.com/maps/api/directions/json?origin=26.9211992,75.8185761&destination=26.8472496,75.7691909&waypoints=optimize:true|26.8686811,75.7568383

  let baseURLGeocode = "https://maps.googleapis.com/maps/api/geocode/json?" let baseURLDirections = "https://maps.googleapis.com/maps/api/directions/json?" var selectedRoute: Dictionary<NSObject, AnyObject>! var overviewPolyline: Dictionary<NSObject, AnyObject>! var originCoordinate: CLLocationCoordinate2D! var destinationCoordinate: CLLocationCoordinate2D! func getDirections(origin: Ssortingng!, destination: Ssortingng!, waypoints: Array<Ssortingng>!, travelMode: AnyObject!, completionHandler: ((status: Ssortingng, success: Bool) -> Void)?) { if let originLocation = origin { if let destinationLocation = destination { var directionsURLSsortingng = baseURLDirections + "origin=" + originLocation + "&destination=" + destinationLocation if let routeWaypoints = waypoints { directionsURLSsortingng += "&waypoints=optimize:true" for waypoint in routeWaypoints { directionsURLSsortingng += "|" + waypoint } } print(directionsURLSsortingng) directionsURLSsortingng = directionsURLSsortingng.ssortingngByAddingPercentEscapesUsingEncoding(NSUTF8SsortingngEncoding)! let directionsURL = NSURL(ssortingng: directionsURLSsortingng) dispatch_async(dispatch_get_main_queue(), { () -> Void in let directionsData = NSData(contentsOfURL: directionsURL!) do{ let dictionary: Dictionary<NSObject, AnyObject> = try NSJSONSerialization.JSONObjectWithData(directionsData!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<NSObject, AnyObject> let status = dictionary["status"] as! Ssortingng if status == "OK" { self.selectedRoute = (dictionary["routes"] as! Array<Dictionary<NSObject, AnyObject>>)[0] self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<NSObject, AnyObject> let legs = self.selectedRoute["legs"] as! Array<Dictionary<NSObject, AnyObject>> let startLocationDictionary = legs[0]["start_location"] as! Dictionary<NSObject, AnyObject> self.originCoordinate = CLLocationCoordinate2DMake(startLocationDictionary["lat"] as! Double, startLocationDictionary["lng"] as! Double) let endLocationDictionary = legs[legs.count - 1]["end_location"] as! Dictionary<NSObject, AnyObject> self.destinationCoordinate = CLLocationCoordinate2DMake(endLocationDictionary["lat"] as! Double, endLocationDictionary["lng"] as! Double) let originAddress = legs[0]["start_address"] as! Ssortingng let destinationAddress = legs[legs.count - 1]["end_address"] as! Ssortingng let originMarker = GMSMarker(position: self.originCoordinate) originMarker.map = self.googleMapsView originMarker.icon = GMSMarker.markerImageWithColor(UIColor.greenColor()) originMarker.title = originAddress let destinationMarker = GMSMarker(position: self.destinationCoordinate) destinationMarker.map = self.googleMapsView destinationMarker.icon = GMSMarker.markerImageWithColor(UIColor.redColor()) destinationMarker.title = destinationAddress if waypoints != nil && waypoints.count > 0 { for waypoint in waypoints { let lat: Double = (waypoint.componentsSeparatedBySsortingng(",")[0] as NSSsortingng).doubleValue let lng: Double = (waypoint.componentsSeparatedBySsortingng(",")[1] as NSSsortingng).doubleValue let marker = GMSMarker(position: CLLocationCoordinate2DMake(lat, lng)) marker.map = self.googleMapsView marker.icon = GMSMarker.markerImageWithColor(UIColor.purpleColor()) } } let route = self.overviewPolyline["points"] as! Ssortingng let path: GMSPath = GMSPath(fromEncodedPath: route)! let routePolyline = GMSPolyline(path: path) routePolyline.map = self.googleMapsView } else { print("status") //completionHandler(status: status, success: false) } } catch { print("catch") // completionHandler(status: "", success: false) } }) } else { print("Destination is nil.") //completionHandler(status: "Destination is nil.", success: false) } } else { print("Origin is nil") //completionHandler(status: "Origin is nil", success: false) } } 

Pour Swift 3.0 Veuillez utiliser ce code …

 func getDirections(origin: Ssortingng!, destination: Ssortingng!, waypoints: Array<Ssortingng>!, travelMode: AnyObject!, completionHandler: ((_ status: Ssortingng, _ success: Bool) -> Void)?) { if let originLocation = origin { if let destinationLocation = destination { var directionsURLSsortingng = baseURLDirections + "origin=" + originLocation + "&destination=" + destinationLocation if let routeWaypoints = waypoints { directionsURLSsortingng += "&waypoints=optimize:true" for waypoint in routeWaypoints { directionsURLSsortingng += "|" + waypoint } } print(directionsURLSsortingng) directionsURLSsortingng = directionsURLSsortingng.addingPercentEscapes(using: Ssortingng.Encoding.utf8)! let directionsURL = NSURL(ssortingng: directionsURLSsortingng) DispatchQueue.main.async( execute: { () -> Void in let directionsData = NSData(contentsOf: directionsURL! as URL) do{ let dictionary: Dictionary<Ssortingng, AnyObject> = try JSONSerialization.jsonObject(with: directionsData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<Ssortingng, AnyObject> let status = dictionary["status"] as! Ssortingng if status == "OK" { self.selectedRoute = (dictionary["routes"] as! Array<Dictionary<Ssortingng, AnyObject>>)[0] self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<Ssortingng, AnyObject> let legs = self.selectedRoute["legs"] as! Array<Dictionary<Ssortingng, AnyObject>> let startLocationDictionary = legs[0]["start_location"] as! Dictionary<Ssortingng, AnyObject> self.originCoordinate = CLLocationCoordinate2DMake(startLocationDictionary["lat"] as! Double, startLocationDictionary["lng"] as! Double) let endLocationDictionary = legs[legs.count - 1]["end_location"] as! Dictionary<Ssortingng, AnyObject> self.destinationCoordinate = CLLocationCoordinate2DMake(endLocationDictionary["lat"] as! Double, endLocationDictionary["lng"] as! Double) let originAddress = legs[0]["start_address"] as! Ssortingng let destinationAddress = legs[legs.count - 1]["end_address"] as! Ssortingng let originMarker = GMSMarker(position: self.originCoordinate) originMarker.map = self.mapView originMarker.icon = UIImage(named: "mapIcon") originMarker.title = originAddress let destinationMarker = GMSMarker(position: self.destinationCoordinate) destinationMarker.map = self.mapView destinationMarker.icon = UIImage(named: "mapIcon") destinationMarker.title = destinationAddress if waypoints != nil && waypoints.count > 0 { for waypoint in waypoints { let lat: Double = (waypoint.components(separatedBy: ",")[0] as NSSsortingng).doubleValue let lng: Double = (waypoint.components(separatedBy: ",")[1] as NSSsortingng).doubleValue let marker = GMSMarker(position: CLLocationCoordinate2DMake(lat, lng)) marker.map = self.mapView marker.icon = UIImage(named: "mapIcon") } } let route = self.overviewPolyline["points"] as! Ssortingng let path: GMSPath = GMSPath(fromEncodedPath: route)! let routePolyline = GMSPolyline(path: path) routePolyline.map = self.mapView routePolyline.strokeColor = UIColor(red: 44, green: 134, blue: 200) routePolyline.strokeWidth = 3.0 } else { print("status") //completionHandler(status: status, success: false) } } catch { print("catch") // completionHandler(status: "", success: false) } }) } else { print("Destination is nil.") //completionHandler(status: "Destination is nil.", success: false) } } else { print("Origin is nil") //completionHandler(status: "Origin is nil", success: false) } } 

SWIFT 3

CETTE FONCTION FIRE LA DEMANDE AVEC ALAMOFIRE ET REPRENDRE AVEC UNE RÉPONSE JSON.

SIMPLEMENT SIMPLEMENT LA POLYLINE AVEC LA LATITUDE D'ORIGINE, LONGITUDE ET DESTINATION LATITUDE, LONGITUDE

 func drawMap () { let str = Ssortingng(format:"https://maps.googleapis.com/maps/api/directions/json?origin=\(originLatitude),\(originlongitude)&destination=\(destinationlatitude),\(destinationlongitude)&key=AIzaSyC8HZTqt2wsl14eI_cKxxxxxxxxxxxx") Alamofire.request(str).responseJSON { (responseObject) -> Void in let resJson = JSON(responseObject.result.value!) print(resJson) if(resJson["status"].rawSsortingng()! == "ZERO_RESULTS") { } else if(resJson["status"].rawSsortingng()! == "NOT_FOUND") { } else{ let routes : NSArray = resJson["routes"].rawValue as! NSArray print(routes) let position = CLLocationCoordinate2D(latitude: self.sellerlatitude, longitude: self.sellerlongitude) let marker = GMSMarker(position: position) marker.icon = UIImage(named: "mapCurrent") marker.title = "Customer have selected same location as yours" marker.map = self.Gmap let position2 = CLLocationCoordinate2D(latitude: self.Buyyerlatitude, longitude: self.Buyyerlongitude) let marker1 = GMSMarker(position: position2) marker1.icon = UIImage(named: "makeupmarker") marker1.title = self.locationAddress marker1.map = self.Gmap let pathv : NSArray = routes.value(forKey: "overview_polyline") as! NSArray print(pathv) let paths : NSArray = pathv.value(forKey: "points") as! NSArray print(paths) let newPath = GMSPath.init(fromEncodedPath: paths[0] as! Ssortingng) let polyLine = GMSPolyline(path: newPath) polyLine.strokeWidth = 3 polyLine.strokeColor = UIColor.blue polyLine.map = self.Gmap let bounds = GMSCoordinateBounds(coordinate: position, coordinate: position2) let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsetsMake(170, 30, 30, 30)) self.Gmap!.moveCamera(update) } } } 

Vous devez get tous les points pour l'itinéraire. Pour get l'itinéraire, vous devez utiliser l'API Google Direction https://developers.google.com/maps/documentation/directions/ . Ensuite, utilisez le 1er résultat du tableau qui sera le plus court, utilisez le path encodé pour dessiner une ligne poly utilisant pathFromEncodedPath: method.