Basically, I have searched a lot but mostly answer are for javaScrip and I want some code example in swift and according to google we can not use more than 25 way points in a single request
I already have seen, the links blow.
StackOverFlow.
Documentation
How to draw polyline using more than hundred waypoints (may be more than 300) swift 5?
I am using GoogleMaps.
My code and api.
func getDotsToDrawRoute(positions: [CLLocationCoordinate2D]) {
if positions.count > 0 {
let origin = positions.first
let destination = positions.last
var wayPoint = ""
var wayPoints: [String] = []
for point in positions {
wayPoint = wayPoint.count == 0 ? "\(point.latitude), \(point.longitude)" : "\(wayPoint)|\(point.latitude), \(point.longitude)"
wayPoints.append(wayPoint)
}
print("exactWayPoint:\(wayPoint)")
print("exactWayPoint:\(wayPoints)")
let stringURL = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin!.latitude),\(origin!.longitude)&destination=\(destination!.latitude),\(destination!.longitude)&wayPoints=\(wayPoints)&key=\(Google_API_Key)&sensor=false&mode=walking&waypoints"
let url = URL(string: stringURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil {
print("error in task: \(error!.localizedDescription)")
} else {
do {
if let dictionary: [String: Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
print("Dictionary: \(dictionary)")
if let routes = dictionary["routes"] as? [[String: Any]] {
if routes.count > 0 {
let first = routes.first
if let legs = first!["legs"] as? [[String: Any]] {
let fullPath: GMSMutablePath = GMSMutablePath()
for leg in legs {
if let steps = leg["steps"] as? [[String: Any]] {
for step in steps {
if let polyline = step["polyline"] as? [String: Any] {
if let points = polyline["points"] as? String {
fullPath.appendPath(path: GMSMutablePath(fromEncodedPath: points))
self.drawRoutes(polyStr: points)
}
}
}
}
}
}
}
}
}
} catch let parseError {
print("JSON Error: \(parseError.localizedDescription)")
}
}
})
task.resume()
} else {
showAlert(title: "OOps!", message: "No data found")
}
}
func drawRoutes(polyStr: String) {
if let path = GMSPath.init(fromEncodedPath: polyStr) {
let polyline = GMSPolyline.init(path: path)
polyline.path = path
polyline.strokeWidth = 4.0
polyline.strokeColor = .blue
polyline.geodesic = true
self.mapView?.isMyLocationEnabled = true
polyline.map = self.mapView
} else {
print("path is nill")
}
}
// MARK - PATHDelegate
extension GMSMutablePath {
func appendPath(path: GMSPath?) {
if let path = path {
for i in 0..<path.count() {
self.add(path.coordinate(at: i))
}
}
}
}