chrisstump
1/18/18 at 10:18 am
PHP
api, google, geo
Convert Lat / Long to City / State with Google Geocode API
Use the Google Maps Geocoding API to pass lat / long coordinates to this function and return the city and state. Get a Google Maps API Key
here
.
// you will need a Google Maps API key - you can get one for free here: // https://developers.google.com/maps/documentation/geocoding/get-api-key $googleMapsApiKey = 'xyz'; // get the city and state associated with provided geo coordinates function getCityState($lat, $long) { $details_url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . ',' . $long . "&key=" . $googleMapsApiKey . "&sensor=false"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $details_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $loc = json_decode(curl_exec($ch), true); $location = ''; if(count($loc['results']) != 0) { $city = ''; $state = ''; foreach($loc['results'][0]['address_components'] as $addressComponent) { if(in_array('locality', $addressComponent['types'])) { $city = $addressComponent['short_name']; } if(in_array('administrative_area_level_1', $addressComponent['types'])) { $state = $addressComponent['short_name']; } } $location = $city . ', ' . $state; } return $location; }
Copy Snippet to Clipboard
Don't Have an Account?
Stop digging through old code examples. Get organized. Get Code Snipper.
Learn More
Start Free 14 Day Trial