IT & Programming

Import coordinates from map quest api using PHP Curl

I recently wrote a php script to import coordinates from mapquestapi.com from one of my project. This script will surely help others to use it in their projects.

Acquire Map Quest API Key

First step is to acquire a free map quest api key but simple registration. Please follow the link below to create an account and get your api key that we will be using later.

https://developer.mapquest.com/

Function

This function sends a complete address as parameter to api and returns latitude and longitude.

function getCoordinates($address)
{

        $api_url = 'http://www.mapquestapi.com/geocoding/v1/address?key=YourKey&location=' . urlencode($address);

        $curl = curl_init();

        $options = [
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => [
                "accept: application/json",
                "cache-control: no-cache"
            ]
        ];

        curl_setopt_array($curl, $options);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($curl);
        $errors = curl_error($curl);
        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        $json_response = json_decode($response);

        $latitude = null;
        $longitude = null;

        if (!empty($json_response->results[0]->locations[0]->latLng->lat)) {
            $latitude = $json_response->results[0]->locations[0]->latLng->lat;
        }

        if (!empty($json_response->results[0]->locations[0]->latLng->lng)) {
            $longitude = $json_response->results[0]->locations[0]->latLng->lng;
        }

        return (object) [
                    'latitude' => $latitude,
                    'longitude' => $longitude
        ];
}

Calling The Function

$address = 'Marktplein 9, 8520 Kuurne Belgium';

$coordinates  = getCoordinates($address);

echo $coordinates->latitude . ',' . $coordinates->longitude;

Output

50.85014,3.28614

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *