Search code examples
iosswiftgoogle-mapsgoogle-polylinegoogle-directions-api

iOS) Getting no route from two coordinates from google directions api


I'm trying to get a route between the origin coordinate and the destination coordinate.

I referenced stackoverflow.

So My code is below:

let url = "https://maps.googleapis.com/maps/api/directions/json?origin=37.496375,126.9546903&destination=37.48121,126.9505233&mode=walking&key=MY_KEY"
Alamofire.request(url).responseJSON 
{ response in
print(response.request)  // original URL request
print(response.response) // HTTP URL response
print(response.data)     // server data
print(response.result)   // result of response serialization

let json = JSON(data: response.data!)
let routes = json["routes"].arrayValue

for route in routes
{
    let routeOverviewPolyline = route["overview_polyline"].dictionary
    let points = routeOverviewPolyline?["points"]?.stringValue
    let path = GMSPath.init(fromEncodedPath: points!)
    let polyline = GMSPolyline.init(path: path)
    polyline.map = self.mapView
 }
}

But as a result, response.data is below:

{
 "status" : "ZERO_RESULTS",
 "available_travel_modes" :
 [
 "TRANSIT"
  ],
 "geocoded_waypoints" : [
{},
{}],"routes" : []}

About this issue, I searched it and found that it may be caused when the coordinate can not be converted into the address.

But I did check both coordinates are converted into the right address by 'CLGeocoder'(reverseGeocodeLocation).

Finally, I did check at 'maps.google.com' that the same coordinates are addressed and the route is shown to me.

How can I solve this problem?


Solution

  • available_travel_modes contains an array of available travel modes. This field is returned when a request specifies a travel mode and gets no results. The array contains the available travel modes in the countries of the given set of waypoints.

    Your response returned as

    "available_travel_modes":["TRANSIT"]
    

    So try changing mode=walking to &mode=transit