Last active
October 10, 2025 15:38
-
-
Save elbeicktalat/8d93a30afa7402f3382861ff177d274d to your computer and use it in GitHub Desktop.
Get Netherland address details and Calculate distance between two coordinates via Google Destinations API in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "status": "ok", | |
| "details": [ | |
| { | |
| "street": "Zaagmolenpad", | |
| "city": "Doetinchem", | |
| "municipality": "Doetinchem", | |
| "province": "Gelderland", | |
| "postcode": "7008 AJ", | |
| "pnum": "7008", | |
| "pchar": "AJ", | |
| "rd_x": "215930.96446666666666666667", | |
| "rd_y": "442753.35240000000000000000", | |
| "lat": "51.9698526620957", | |
| "lon": "6.2738995722633" | |
| } | |
| ] | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // --------------------------------------------- | |
| ## Usage Example | ACTION REPLACE WITH YOUR LOGIC | |
| // --------------------------------------------- | |
| // 1. TODO: Replace with your actual Google Maps API Key | |
| $google_api_key = 'YORE_API_KEY_HERE'; // Replace with your actual Google Maps API Key | |
| // 2. Define the origin coordinates (latitude,longitude) Alrady DONE | |
| $origin = '51.97074550279727, 6.271788884654938'; // Albek Witgoed Outlet | |
| // Fill in the postal code and house number you want to look up. | |
| $postcode = "7002TR"; | |
| $number = 54; | |
| // Call the function to get address details. | |
| $address_data = getAddressDetails($postcode, $number); | |
| // Output the results. | |
| if ($address_data == null) { | |
| echo "Failed to retrieve address details."; | |
| exit; | |
| } | |
| // Extract the first address detail (if available) | |
| $address_details = $address_data['details'][0] ?? null; | |
| if ($address_details == null) { | |
| echo "No address details found for the provided postal code and house number."; | |
| exit; | |
| } | |
| // Define the destination coordinates based on the retrieved address details | |
| $destination = $address_details['lat'] . ',' . $address_details['lon']; // Address from postal code lookup | |
| // Calculate the route distance using the retrieved coordinates | |
| $distance_km = get_route_distance_km($origin, $destination, $google_api_key); | |
| if ($distance_km !== null) { | |
| echo "Real route distance: **" . round($distance_km, 2) . " km** <br><br>"; | |
| } else { | |
| echo "Could not calculate route distance."; | |
| } | |
| echo <<<MULTILINE | |
| status: {$address_data['status']} <br> | |
| street: {$address_details['street']} <br> | |
| City: {$address_details['city']} <br> | |
| Municipality: {$address_details['municipality']} <br> | |
| Province: {$address_details['province']} <br> | |
| Postal Code: {$address_details['postcode']} <br> | |
| Latitude: {$address_details['lat']} <br> | |
| Longitude: {$address_details['lon']} <br> | |
| MULTILINE; | |
| ?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Retrieves address details (including coordinates) for a given Dutch postal code and house number. | |
| * | |
| * NOTE: This function is written for a generic public API structure (like PostcodeData.nl's API | |
| * example, which uses an optional 'ref' parameter). You MUST replace the $api_url | |
| * and $ref_key with the actual values for the service you are using. | |
| * | |
| * @param string $postalCode The Dutch postal code (e.g., "7008AJ"). | |
| * @param int $buildingNumber The house number (e.g., 25). | |
| * @return array|null The decoded JSON response as a PHP array, or null on failure. | |
| */ | |
| function getAddressDetails(string $postalCode, int $buildingNumber): ?array | |
| { | |
| // --- Configuration --- | |
| // 1. Set the correct API URL. | |
| // (Example uses the base URL for PostcodeData.nl) | |
| $api_url = 'http://api.postcodedata.nl/v1/postcode/'; | |
| // 2. Set your unique reference key (which you must register for). | |
| // (Example uses the placeholder seen in public documentation) | |
| $ref_key = 'your_registered_domain.nl'; | |
| // ----------------------- | |
| // Build the query parameters. | |
| $query_params = http_build_query([ | |
| 'postcode' => urlencode(strtoupper($postalCode)), | |
| 'streetnumber' => $buildingNumber, | |
| 'ref' => $ref_key, | |
| 'type' => 'json' | |
| ]); | |
| $full_url = $api_url . '?' . $query_params; | |
| // Use file_get_contents to fetch the JSON data. | |
| // For production use, you should use cURL for better error handling and control. | |
| $json_data = @file_get_contents($full_url); | |
| if ($json_data === FALSE) { | |
| // Handle API connection or access error. | |
| error_log("Failed to retrieve data from: " . $full_url); | |
| return null; | |
| } | |
| // Decode the JSON string into a PHP associative array. | |
| $result = json_decode($json_data, true); | |
| if ($result === null && json_last_error() !== JSON_ERROR_NONE) { | |
| // Handle JSON decoding error. | |
| error_log("Failed to decode JSON response. Error: " . json_last_error_msg()); | |
| return null; | |
| } | |
| // The function returns the PHP array, which mirrors your expected JSON structure. | |
| return $result; | |
| } | |
| /** | |
| * Calculates the real-route distance between two coordinates using the Google Maps Directions API. | |
| * | |
| * NOTE: Ensure you have a valid Google Maps API key with the Directions API enabled and billing set up. | |
| * | |
| * @param string $origin_lat_lng The starting latitude and longitude (e.g., '40.712776,-74.005974'). | |
| * @param string $destination_lat_lng The ending latitude and longitude (e.g., '34.052235,-118.243683'). | |
| * @param string $api_key Your Google Maps Platform API Key. | |
| * @return float|null The distance in kilometers, or null on failure. | |
| */ | |
| function get_route_distance_km(string $origin_lat_lng, string $destination_lat_lng, string $api_key): ?float { | |
| // The Directions API URL | |
| $api_url = 'https://maps.googleapis.com/maps/api/directions/json?'; | |
| // Build the request parameters | |
| $params = [ | |
| 'origin' => $origin_lat_lng, | |
| 'destination' => $destination_lat_lng, | |
| 'key' => $api_key, | |
| 'units' => 'metric', // Request distance in meters/kilometers (metric system) | |
| 'mode' => 'driving', // Calculate driving route (you can change this to 'walking', 'bicycling', etc.) | |
| ]; | |
| // Construct the full URL | |
| $full_url = $api_url . http_build_query($params); | |
| // Use cURL to make the API request | |
| $ch = curl_init(); | |
| curl_setopt($ch, CURLOPT_URL, $full_url); | |
| curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
| $response = curl_exec($ch); | |
| $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
| curl_close($ch); | |
| // Check for cURL errors or bad HTTP response | |
| if ($http_code !== 200 || $response === false) { | |
| // Log or handle the error appropriately | |
| error_log("Google Directions API request failed with HTTP code: $http_code"); | |
| return null; | |
| } | |
| // Decode the JSON response | |
| $data = json_decode($response, true); | |
| // Check for API errors or no routes found | |
| if ($data['status'] !== 'OK' || empty($data['routes'])) { | |
| // Log or handle the API status error (e.g., 'ZERO_RESULTS') | |
| error_log("Google Directions API returned status: " . $data['status']); | |
| return null; | |
| } | |
| // Extract the distance from the first route's first leg | |
| // The distance is returned in meters (distance['value']) | |
| // Distance in meters is found in: routes[0]['legs'][0]['distance']['value'] | |
| $distance_meters = $data['routes'][0]['legs'][0]['distance']['value'] ?? null; | |
| if ($distance_meters === null) { | |
| error_log("Could not find distance in Google Directions API response."); | |
| return null; | |
| } | |
| // Convert meters to kilometers and return | |
| $distance_km = $distance_meters / 1000; | |
| return (float) $distance_km; | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment