Created
April 30, 2019 07:32
-
-
Save iahmedhendi/1bfae492e1be33aa52f2199e1b0d684e to your computer and use it in GitHub Desktop.
get city name by latitude and longitude using google geocode api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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