Skip to content

Instantly share code, notes, and snippets.

@LeoValentim
Last active August 13, 2019 12:22
Show Gist options
  • Save LeoValentim/1c639e0991746a3c80840f610e0fb066 to your computer and use it in GitHub Desktop.
Save LeoValentim/1c639e0991746a3c80840f610e0fb066 to your computer and use it in GitHub Desktop.
Google Maps Route For Swift
//MARK:- Draw Route Betweeen two points
/**
To draw a route between to cordinates.
- origin: Source marker cordinate
- destination: destination marker cordinate
- self.googleMapsKey: API Key
*/
let origin = "-23.543293,-46.638592"
let destination = "-23.642446,-46.637669"
let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving&key=\(self.googleMapsKey)"
Webservice.get(urlString, headers: [:]) {
response in
if let data = response {
let json = JSON(data)
do{
let routes = json["routes"].array
self.mapView?.clear()
for route in routes!
{
let points = route.dictionary?["overview_polyline"]?.dictionaryObject?["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)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment