0

I want to get only the value of the kilometres to save it in a new variable.

I also tried to access the array with index.

My code:

/**
 * @Route("/routesetting", name="api_routeset_set", methods={"GET"})
 */
public function getRouteAction(Request $request) {
    $distanceMatrix = new GoogleDistanceMatrix('AIzaSyBdAHFe4MsbIr417NlPioNhYW7as-adBa8');
    $distance = $distanceMatrix
        ->addOrigin('Van Bronckhorststraat 94, 5961SM Horst, The Netherlands')
        ->addDestination('Maistraße 10, 80337 München, Deutschland')
        ->setMode(GoogleDistanceMatrix::MODE_DRIVING)
        ->setLanguage('en-EN')
        ->setUnits(GoogleDistanceMatrix::UNITS_METRIC)
        ->setAvoid(GoogleDistanceMatrix::AVOID_FERRIES)
        ->sendRequest();


    return $this->json([
        'message' => $distance
    ]);
}

Result:

{
    "message": {
        "status": "OK",
        "responseObject": [],
        "originAddresses": [
            []
        ],
        "destinationAddresses": [
            []
        ],
        "rows": [
            {
                "elements": [
                    {
                        "status": "OK",
                        "duration": {
                            "text": "6 hours 48 mins",
                            "value": 24461
                        },
                        "distance": {
                            "text": "695 km",
                            "value": 695380
                        }
                    }
                ]
            }
        ]
    }
}

Expected result:

695380

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
Gallab
  • 1

1 Answers1

0

$distance here seems to be a PHP array (I've never worked with this Google API).

So just before calling return $this->json(['message' => $distance]); you should just get the value you want from the $distance variable.

Which seems to be $distance['rows']['elements']['distance']['value'].

So returning $this->json(['message' => $distance['rows']['elements']['distance']['value']]); seems to be your trick. ;)

Be careful I haven't done any content verification here (isset()).

hunomina
  • 332
  • 3
  • 13