Get latitude and longitude automatically using php, API

Get latitude and longitude automatically using php, API

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Decoding the "Bad Request" Error in PHP Geocoding

When attempting to retrieve latitude and longitude coordinates from a street address using file_get_contents against Google Maps, encountering an HTTP/1.0 400 Bad Request error is a common stumbling block. The error message explicitly indicates that the server rejected the request due to malformed parameters. In the specific case provided, the root cause lies in how the URL is constructed and transmitted from the PHP script.

The original code snippet attempts to concatenate variables directly into the file_get_contents string:

$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");

This approach fails because it does not properly escape special characters within the address string. If $address contains spaces, commas, or other non-alphanumeric characters (like "Trivandrun"), they are interpreted as part of the query syntax rather than literal text. For instance, a comma inside the address value breaks the parameter parsing on the server side, leading to the 400 error. Additionally, the deprecated sensor=false parameter was officially removed by Google Maps Geocoding API in early 2015, so including it is unnecessary and can sometimes contribute to confusion regarding supported parameters.

To resolve this, you must URL-encode the input string before appending it to the base URL. PHP provides the urlencode() function specifically for this purpose. This function replaces spaces with %20 and encodes other special characters like commas or ampersands into their percent-encoded equivalents. Here is the corrected implementation:

$address = urlencode($address);
$region = urlencode($region); // Optional, but good practice if passed as a variable

$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key=YOUR_API_KEY";

$json = file_get_contents($url);
$json = json_decode($json);

if ($json && isset($json->results[0]->geometry->location)) {
    $lat = $json->results[0]->geometry->location->lat;
    $lng = $json->results[0]->geometry->location->lng;
} else {
    // Handle error or empty result
    echo "Geocoding failed or no results found.";
}

There are two critical updates in this refactored code. First, the sensor parameter has been removed as it is obsolete. Second, and most importantly, a valid API key is now required. Google disabled anonymous access to their Geocoding API several years ago. You cannot simply use the public endpoint without authentication; you must sign up for a Google Cloud project, enable the Maps Geocoding API, and generate an API key.

Using file_get_contents is functional for small-scale scripts or testing, but it lacks robustness for production environments. It does not handle SSL verification errors gracefully, offers no retry logic for transient network failures, and exposes your application to rate-limiting issues if not managed carefully via the API key quota settings. Furthermore, direct HTTP requests in PHP can be blocked by firewalls or corporate proxies that restrict outbound connections to third-party mapping services.

If you are working within a Laravel ecosystem, utilizing the built-in Http facade offers a cleaner separation of concerns and better error handling capabilities compared to raw file_get_contents. You can encapsulate the geocoding logic in a service class or a dedicated controller method that returns a standardized response structure containing either the coordinates or an error message.

For high-availability applications, consider implementing a fallback mechanism. If the Google API quota is exceeded or the request times out, having a secondary provider like OpenStreetMap (via Nominatim) configured as a backup ensures your application remains functional during peak usage periods or when primary credentials are exhausted. Always remember to store your API keys securely using environment variables rather than hardcoding them directly into the source files.

Our network