Home > Software design >  Extracting distance from Google Maps DistanceMatrix API
Extracting distance from Google Maps DistanceMatrix API

Time:12-24

I need to calculate the distance between coordinates.

I am using the Google Maps DistanceMatrix API:

 getDistanceMatrix() async {
      try {
        var response = await Dio().get('https://maps.googleapis.com/maps/api/distancematrix/json?destinations=${widget.miLatitud},${widget.miLongitud}&origins=${location.latitude},${location.longitude}&key=...');
        print("distancia es ${response}");
      
      } catch (e) {
        print(e);
      }
    }

Which is the proper way to extract the distance from the response?

Here you have the response output:

distancia es {"destination_addresses":["Carrer de Sant Ramon, 62, 08140 Caldes de Montbui, Barcelona, Spain"],"origin_addresses":["Plaça de la Porxada, 32, 08401 Granollers, Barcelona, Spain"],"rows":[{"elements":[{"distance":{"text":"13.0 km","value":13012},"duration":{"text":"21 mins","value":1234},"status":"OK"}]}],"status":"OK"}

CodePudding user response:

This is the beautified JSON file:

{
   "destination_addresses":[
      "Carrer de Sant Ramon, 62, 08140 Caldes de Montbui, Barcelona, Spain"
   ],
   "origin_addresses":[
      "Plaça de la Porxada, 32, 08401 Granollers, Barcelona, Spain"
   ],
   "rows":[
      {
         "elements":[
            {
               "distance":{
                  "text":"13.0 km",
                  "value":13012
               },
               "duration":{
                  "text":"21 mins",
                  "value":1234
               },
               "status":"OK"
            }
         ]
      }
   ],
   "status":"OK"
}

As you can see, you can get the distance if you go to rows-elements-distance-value, where you would get the result in meters.

  • Related