在PHP中使用Nominatim实现反向地理编码时遇到报错问题
Hey there! Let's walk through fixing your reverse geocoding code and tackle those errors you're seeing. First, let's spot the obvious gaps in your current code, then add proper error handling and follow Nominatim's rules to avoid getting blocked.
First, Fix the Obvious Code Issues
Your code cuts off at return $RG_... — you meant to return the $RG_address variable you defined. Also, the URL uses & (HTML entities) instead of plain &, which will break the request since PHP is building a raw URL, not HTML.
Add Proper Error Handling & Follow Nominatim's Rules
Nominatim requires all requests to include a User-Agent header (to identify your app/script), otherwise it might block your requests. We also need to handle cases where file_get_contents fails (like if allow_url_fopen is disabled in your PHP config) or the API returns invalid data.
Here's the corrected, robust version of your code:
$lon = 100.753; $lat = 13.69362; function getAddress($RG_Lat, $RG_Lon) { // Build the correct URL (use & instead of &) $url = "http://nominatim.openstreetmap.org/reverse?format=json&lat=" . urlencode($RG_Lat) . "&lon=" . urlencode($RG_Lon) . "&zoom=27&addressdetails=1"; // Set a valid User-Agent (required by Nominatim) $context = stream_context_create([ 'http' => [ 'header' => 'User-Agent: YourAppName/1.0 (your@email.com)' ] ]); // Fetch the JSON data with error checking $jsonfile = file_get_contents($url, false, $context); if (!$jsonfile) { return "Failed to fetch geocoding data"; } // Decode JSON and check for errors $RG_array = json_decode($jsonfile, true); if (json_last_error() !== JSON_ERROR_NONE) { return "Invalid JSON response"; } // Check if display_name exists in the response if (isset($RG_array['display_name'])) { return $RG_array['display_name']; } else { return "No address found for the given coordinates"; } } // Test the function echo getAddress($lat, $lon);
Key Fixes & Improvements:
- Replaced
&with&in the URL to ensure request parameters are parsed correctly - Added
urlencode()for latitude/longitude (a good practice to handle any special characters) - Added a required User-Agent header to comply with Nominatim's usage policy
- Added checks for
file_get_contentsfailures, invalid JSON, and missingdisplay_nameto avoid fatal errors - Removed the unnecessary
foreachloop — we can directly access$RG_array['display_name']instead of looping through all keys
Common Error Causes to Check:
allow_url_fopenis disabled: Check yourphp.inifile and setallow_url_fopen = On(if you have access to it). If not, use cURL instead offile_get_contents.- Nominatim blocked your request: Always include a clear User-Agent — otherwise, your IP might get temporarily blocked.
- Invalid coordinates: Double-check your latitude/longitude values are in the correct format (latitude between -90 and 90, longitude between -180 and 180).
- Network issues: Ensure your server can connect to
nominatim.openstreetmap.org(check firewall rules or network restrictions).
内容的提问来源于stack exchange,提问作者Roxx

