Why Google Distance Matrix Api returning invalid request status? (using Flutter)

Issue

I am trying to call Distance Matrix API and every time I call it, it returns an invalid request, this is my code for calling request and parsing it

output:

{destination_addresses: [], origin_addresses: [], rows: [], status: INVALID_REQUEST}

the function of requesting from the api:

  Future<String> getDuration(LatLng l1, List<LatLng> l2) async {

    var destinations = await _getwaypoints(l2);
    String url =
         "https://maps.googleapis.com/maps/api/distancematrix/json? 
     origin=${l1.latitude},${l1.longitude}&destination=$destinations&departure_time=now&key=$apiKey";
    http.Response response = await http.get(url);
    Map values = jsonDecode(response.body);

    return values.toString();

_getwaypoints function which i use to format the list to be suitable for the request:

  Future<String> _getwaypoints(List<LatLng> way) async {
String waypointcoords = '';
// Future<String> finalwaypoints;
if (way == null) {
  return null;
} else {
  for (int i = 0; i <= (way.length - 1); i++) {
    var lat = way[i].latitude.toString();
    var lon = way[i].longitude.toString();
    if (i == 0) {
      waypointcoords += '$lat%2C$lon';
    } else {
      waypointcoords += '%7C$lat%2C$lon ';
    }
  }

  waypointcoords.trim();

  return waypointcoords;
}

}

also, I tried to pass one origin location and one destination location and it was the same output,

why the return is invalid request statues while it still recognizes that its distance matrix API and returning empty destination_addresses, origin_addresses, and rows,

is there something I am doing wrong?

Solution

In the request URL, instead of origin and destination it must be origins and destinations

Answered By – dm_tr

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.