How to convert address(input) to coordinates using Tom Tom in Laravel 9 and save them in db?

264 Views Asked by At

We are struggling to try to convert an address to coordinates using TomTom (their documentation sucks fr) in Laravel 9. At this point, we need a proper guide; we don't know how to begin.

Model

use GuzzleHttp\Client;

public static function getCoordinatesFromAddress(string $address): array
{
    $client = new Client();
    $response = $client
        ->get('https://api.tomtom.com/search/2/geocode/%27.urlencode($address).%27.json', [
        'query' => [
            'key' => 'my_tomtom_api_key',
            'limit' => 1
        ]
    ]);

    $data = json_decode($response->getBody(), true);
    $latitude = $data['results'][0]['position']['lat'];
    $longitude = $data['results'][0]['position']['lon'];

    return compact('latitude', 'longitude');
}
1

There are 1 best solutions below

0
suxgri On

i just tried with the below code and it worked. Please note i used (hardcoded) the address they suggest at the beginning in the geocoding documentation.

    $client = new Client();
    $address = urlencode('109 Park Row, New York, United States');
    $response = $client->get('https://api.tomtom.com/search/2/geocode/%27.'.$address.'.%27.json', [
        'query' => [
            'key' => 'xxxxxxxxxxxxxx',
            'limit' => 1
        ]
    ]);
    error_log(print_r($response,true));
    $data = json_decode($response->getBody(), true);
    $latitude = $data['results'][0]['position']['lat'];
    $longitude = $data['results'][0]['position']['lon'];
    return compact('latitude', 'longitude');