Getting street,city and country by reverse geocoding using google Getting street,city and country by reverse geocoding using google json json

Getting street,city and country by reverse geocoding using google


You could convert the data to the associative array and work with it like

 $data = array(); foreach($jsondata['results']['0']['address_components'] as $element){     $data[ implode(' ',$element['types']) ] = $element['long_name']; } print_r($data); echo 'route: ' . $data['route'] . "\n"; echo 'country: ' . $data['country political'];


Your code is perfectly good, but wouldn't it be better to use a switch inside 1 foreach instead of repeated foreach loops? Here is how I parse the exact same array :

  $location = array();  foreach ($result['address_components'] as $component) {    switch ($component['types']) {      case in_array('street_number', $component['types']):        $location['street_number'] = $component['long_name'];        break;      case in_array('route', $component['types']):        $location['street'] = $component['long_name'];        break;      case in_array('sublocality', $component['types']):        $location['sublocality'] = $component['long_name'];        break;      case in_array('locality', $component['types']):        $location['locality'] = $component['long_name'];        break;      case in_array('administrative_area_level_2', $component['types']):        $location['admin_2'] = $component['long_name'];        break;      case in_array('administrative_area_level_1', $component['types']):        $location['admin_1'] = $component['long_name'];        break;      case in_array('postal_code', $component['types']):        $location['postal_code'] = $component['long_name'];        break;      case in_array('country', $component['types']):        $location['country'] = $component['long_name'];        break;    }  }


If you use Postal Code to find the address, as i have recently generated street,city, country using Google MAP API the code is:

$search_code = urlencode($postcode);        $url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $search_code . '&sensor=false';        $json = json_decode(file_get_contents($url));        if($json->results == []){            return '';        }        $lat = $json->results[0]->geometry->location->lat;        $lng = $json->results[0]->geometry->location->lng;        //Now build the actual lookup        $address_url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . $lat . ',' . $lng . '&sensor=false';        $address_json = json_decode(file_get_contents($address_url));        $address_data = $address_json->results[0]->address_components;        //return $address_data = $address_json->results[0]->formatted_address;        $street = str_replace('Dr', 'Drive', $address_data[1]->long_name);        $town = $address_data[2]->long_name;        $county = $address_data[3]->long_name;        return $street.', '. $town. ', '.$county;