PHP to get the latitude and longitude from an address
Code Solution:
<?php
function getLatLongFromAddress($address) {
$address = str_replace(" ", "+", $address);
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false");
$json = json_decode($json);
$lat = $json->results[0]->geometry->location->lat;
$long = $json->results[0]->geometry->location->lng;
return array($lat, $long);
}
$address = "1600 Amphitheatre Parkway, Mountain View, CA";
$latLong = getLatLongFromAddress($address);
echo "Latitude: $latLong[0]<br>";
echo "Longitude: $latLong[1]";
?>
Explanation:
This PHP function takes a street address as a string and returns an array containing the latitude and longitude of the address.
- Prepare the Address for API Request: We replace spaces in the address with "+" to create a valid URL query string.
- Make a Web Request to Google Maps API: We use the
file_get_contents()function to send an HTTP GET request to the Google Maps API with the address as a parameter. Thesensor=falseparameter indicates that we don’t need sensor data. - Parse the JSON Response: The API returns a JSON response containing information about the address, including the latitude and longitude. We use
json_decode()to parse the JSON response into a PHP object. - Extract Latitude and Longitude: We access the latitude and longitude values from the API response object.
- Return Coordinates: Finally, we return an array containing the latitude and longitude.
Implementation:
To use this function, pass in a street address as a string and store the returned array in a variable. The lat and long keys in the array contain the latitude and longitude coordinates, respectively.
You can use these coordinates to display the location on a map, calculate distances, or perform other geospatial operations.