I'm using google maps in my iOS swift project. I want to draw a path between two locations on the map (Not straight line). Any idea how to do that ?
You can trace a path or highlight an area on your map by drawing lines and shapes.
Add line or shape.Select a layer and click where to start drawing. A layer can have 2,000 lines, shapes or places. Click each corner or bend of your line or shape. To move the map, click and hold the mouse.
To draw polyline between two locations on Google Map in Swift.
//Pass your source and destination coordinates in this method.
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()
}
To draw polyline on map .
func drawPath(from polyStr: String){
let path = GMSPath(fromEncodedPath: polyStr)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 3.0
polyline.map = mapView // Google MapView
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With