Latitude and longitude are used in the geographic coordinate system helps to measure position on the earth. In web applications, the latitude and longitude are used to mark the exact location on Google Maps. When we are using Google Maps to display location on the website, it’s always a good idea to set latitude and longitude in the Google Maps API code. Latitude & Longitude are very useful for pointing accurate locations and placing markers at the correct position on Google Maps.
The latitude and longitude coordinates can be retrieved from the address with Geocoding API using PHP. In this tutorial, we will show you how to get latitude and longitude from address in PHP using Google Maps Geocoding API.
The Google Maps API Key is required to post request to Geocoding API and get response. Before getting started create an API key on Google Cloud console.
Copy this API key for later use in the script on the Google Maps Geocoding API request.
The following example code shows steps to find latitude and longitude from a given address using Google Geocoding API and PHP.
$GOOGLE_API_KEY
– Specify the Google API Key.$address
– Specify the address from which you want to get latitude and longitude coordinates.https://maps.googleapis.com/maps/api/geocode/json
) using the file_get_contents() method in PHP.geometry
object of API response.<?php
// Google Maps API Key
$GOOGLE_API_KEY = 'YOUR_API_KEY';
// Address from which the latitude and longitude will be retrieved
$address = 'White House, Pennsylvania Avenue Northwest, Washington, DC, United States';
// Formatted address
$formatted_address = str_replace(' ', '+', $address);
// Get geo data from Google Maps API by address
$geocodeFromAddr = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address={$formatted_address}&key={$GOOGLE_API_KEY}");
// Decode JSON data returned by API
$apiResponse = json_decode($geocodeFromAddr);
// Retrieve latitude and longitude from API data
$latitude = $apiResponse->results[0]->geometry->location->lat;
$longitude = $apiResponse->results[0]->geometry->location->lng;
?>
Additionally, you can get the formatted address using the following code.
$formatted_address = $apiResponse->results[0]->formatted_address;
Display latitude and longitude on the web page.
// Render the latitude and longitude of the given address
echo 'Latitude: '.$latitude;
echo '<br/>Longitude: '.$longitude;
Get Geolocation from IP Address using PHP
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Thanks 🙂 a simple and great article (y)
Great code Thanks
please give me the same example of demo…
please send me this code in the CodeIgniter php
Great