Support

Account

Home Forums Feature Requests Google Map & City Name Reply To: Google Map & City Name

  • Thank you John, it eventually worked, here is my working code :

    
    <?php
    function reverse_geocoding($form_data) {
    	
    	
    	$latlng = $latlng = $_POST['fields']['field_123abcd-this-is-my-map-field']['lat'].','.$_POST['fields']['field_123abcd-this-is-my-map-field']['lng'];
    	
    	// set your API key here
    	$server_key = '*****';
    	
    	// format this string with the appropriate latitude longitude
    	$url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='.$latlng.'&key='.$server_key.'&sensor=true&language=fr';
    	
    	// make the HTTP request
    	$data = @file_get_contents($url);
    	// parse the json response
    	
    	$jsondata = json_decode($data,true);
    	
    
    	if(is_array($jsondata )&& $jsondata ['status']=='OK') // this piece of code is looping through each component in ['address_components']
    	{
    		foreach ($jsondata['results'][0]['address_components'] as $comp) {
    			foreach ($comp['types'] as $currType){
    				// Here I get all the information I need and store it into vars
    				if($currType == 'administrative_area_level_2'){
    					$area_level_2 = $comp['long_name'];
    				}
    				if($currType == 'locality'){
    					$locality = $comp['long_name'];
    				}
    			}
    		}
    		
    	$coord = explode(",", $latlng);
    	
    	$loc_data = array('city' => $locality,
    					'area_level_2' => $area_level_2,
    					'lat' => $coord[0],
    					'lng' => $coord[1],
    					'zoom' => $zoom,
    					'address' => $form_data['field_556355e41efef']['address']);
    	}
    	
    	return $loc_data;
    	
    	
    }
    
    function acf_location_data( $post_id ) {
     
    		
    		$loc_data = reverse_geocoding($_POST['fields']); // I send all the
    
    		$_POST['fields']['field_123abcd-this-is-my-map-field'] = array(); // not sure if necessary, just to clean the data...
    		$_POST['fields']['field_123abcd-this-is-my-map-field'] = $loc_data; // insert all the data calculated in the funciton above
    		$_POST['fields']['field_456efgh-empty_hidden_field'] = $loc_data['area_level_2']; // here I insert just area_level_2 in order to filter / Order my SQL request later
    		
    }
    
    // run before ACF saves the $_POST['acf'] data
    add_action('acf/save_post', 'acf_location_data', 1);
    
    

    The update_field function wasn’t working, but step by step I’ve managed to do exactly want I was looking for. I hope this may be useful for someone out there.

    Thanks a lot John 🙂

    edit : it’s not very clean, but it works…. if I have time i will simplify it to give you a “generic” code 😉