Skip to content

Instantly share code, notes, and snippets.

@iahmedhendi
Created April 30, 2019 07:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iahmedhendi/1bfae492e1be33aa52f2199e1b0d684e to your computer and use it in GitHub Desktop.
Save iahmedhendi/1bfae492e1be33aa52f2199e1b0d684e to your computer and use it in GitHub Desktop.
get city name by latitude and longitude using google geocode api
<?php
/**
* Function to get City Name by latitude and longitude using google api geocode
* Ahmed Hendi
*
* @param latlong (String) is Latitude and Longitude with , as separator for example "21.3724002,39.8016229"
**/
function getCityNameByLatitudeLongitude($latlong)
{
$APIKEY = "AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Replace this with your google maps api key
$googleMapsUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $latlong . "&language=ar&key=" . $APIKEY;
$response = file_get_contents($googleMapsUrl);
$response = json_decode($response, true);
$results = $response["results"];
$addressComponents = $results[0]["address_components"];
$cityName = "";
foreach ($addressComponents as $component) {
// echo $component;
$types = $component["types"];
if (in_array("locality", $types) && in_array("political", $types)) {
$cityName = $component["long_name"];
}
}
if ($cityName == "") {
echo "Failed to get CityName";
} else {
echo $cityName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment