J'utilise google maps dans mon iOS Swift. Je veux tracer un chemin entre deux emplacements sur la carte (pas en ligne droite). Une idée de comment faire?
Pour dessiner une polyligne entre deux emplacements sur Google Map dans Swift.
// Passez vos coordonnées source et destination dans cette méthode.
func fetchRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) {
let session = URLSession.shared
let url = URL(string: "http://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=driving")!
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
guard error == nil else {
print(error!.localizedDescription)
return
}
guard let jsonResult = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any], let jsonResponse = jsonResult else {
print("error in JSONSerialization")
return
}
guard let routes = jsonResponse["routes"] as? [Any] else {
return
}
guard let route = routes[0] as? [String: Any] else {
return
}
guard let overview_polyline = route["overview_polyline"] as? [String: Any] else {
return
}
guard let polyLineString = overview_polyline["points"] as? String else {
return
}
//Call this method to draw path on map
self.drawPath(from: polyLineString)
})
task.resume()
}
Pour dessiner une polyligne sur la carte.
func drawPath(from polyStr: String){
let path = GMSPath(fromEncodedPath: polyStr)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 3.0
polyline.map = mapView // Google MapView
}
Affichage itinéraires multiples entre deux emplacements dans google maps dans Swift 3.0 avec zoom de la caméra:
let Origin = "\(startLocation.coordinate.latitude),\(startLocation.coordinate.longitude)"
let destination = "\(destinationLocation.coordinate.latitude),\(destinationLocation.coordinate.longitude)"
let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(Origin)&destination=\(destination)&mode=driving&key=API_KEY"
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!, completionHandler: {
(data, response, error) in
if(error != nil){
print("error")
}else{
do{
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]
let routes = json["routes"] as! NSArray
self.mapView.clear()
OperationQueue.main.addOperation({
for route in routes
{
let routeOverviewPolyline:NSDictionary = (route as! NSDictionary).value(forKey: "overview_polyline") as! NSDictionary
let points = routeOverviewPolyline.object(forKey: "points")
let path = GMSPath.init(fromEncodedPath: points! as! String)
let polyline = GMSPolyline.init(path: path)
polyline.strokeWidth = 3
let bounds = GMSCoordinateBounds(path: path!)
self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 30.0))
polyline.map = self.mapView
}
})
}catch let error as NSError{
print("error:\(error)")
}
}
}).resume()
Ce morceau de code fonctionnera pour vous. N'oubliez pas de changer votre clé API et votre mode (marche, conduite).
func draw(src: CLLocationCoordinate2D, dst: CLLocationCoordinate2D){
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(src.latitude),\(src.longitude)&destination=\(dst.latitude),\(dst.longitude)&sensor=false&mode=walking&key=**YOUR_KEY**")!
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
if error != nil {
print(error!.localizedDescription)
} else {
do {
if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
let preRoutes = json["routes"] as! NSArray
let routes = preRoutes[0] as! NSDictionary
let routeOverviewPolyline:NSDictionary = routes.value(forKey: "overview_polyline") as! NSDictionary
let polyString = routeOverviewPolyline.object(forKey: "points") as! String
DispatchQueue.main.async(execute: {
let path = GMSPath(fromEncodedPath: polyString)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 5.0
polyline.strokeColor = UIColor.green
polyline.map = mapView
})
}
} catch {
print("parsing error")
}
}
})
task.resume()
}
Créez un nouveau fichier Swift copiez ce code, c'est-à-dire appelez la méthode drawPolygon () depuis la vue de carte pour la ligne du polygone.
import GoogleMaps
private struct MapPath : Decodable{
var routes : [Route]?
}
private struct Route : Decodable{
var overview_polyline : OverView?
}
private struct OverView : Decodable {
var points : String?
}
extension GMSMapView {
//MARK:- Call API for polygon points
func drawPolygon(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
guard let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=driving") else {
return
}
DispatchQueue.main.async {
session.dataTask(with: url) { (data, response, error) in
guard data != nil else {
return
}
do {
let route = try JSONDecoder().decode(MapPath.self, from: data!)
if let points = route.routes?.first?.overview_polyline?.points {
self.drawPath(with: points)
}
print(route.routes?.first?.overview_polyline?.points)
} catch let error {
print("Failed to draw ",error.localizedDescription)
}
}.resume()
}
}
//MARK:- Draw polygon
private func drawPath(with points : String){
DispatchQueue.main.async {
let path = GMSPath(fromEncodedPath: points)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 3.0
polyline.strokeColor = .red
polyline.map = self
}
}
}