Home › Forums › Backend Issues (wp-admin) › Extend Google Maps field with Places › Reply To: Extend Google Maps field with Places
Thanks @jonasvorwerk – that looks like it would run on every page load because it isn’t saving that info to the DB right?
I think I have this working. I am using the originally posted code to grab Place ID (as well as the other needed elements like lat/lng) and then using an AJAX call to run update_field()
to essentially override what the map field is doing.
This assumes that your map field id is map
.
<?php
add_action('acf/input/admin_footer', 'my_acf_input_admin_footer');
function my_acf_input_admin_footer()
{
global $post;
?>
<script type="text/javascript">
(function($) {
acf.add_action('google_map_init', function( map, marker, $field ){
//get the place from textfield
thisplace = $field.find('.search').val();
//get place from Google
getPlace(thisplace);
//if input has changed, retrieve the place again
$($field).change(function(){
thisplace = $field.find('.search').val();
getPlace(thisplace);
});
function getPlace(place){
var request = {
query: place
};
var service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
console.log(results);
if (status == google.maps.places.PlacesServiceStatus.OK) {
var place_id = results[0].place_id;
var formatted_address = results[0].formatted_address;
var lat = results[0].geometry.location.lat;
var lng = results[0].geometry.location.lng;
$field.find('.search').val(formatted_address);
var data = {
'action': 'get_place_id',
'place_id': place_id,
'lat' : lat,
'lng' : lng,
'address' : formatted_address,
'post_id' : <?php echo $post->ID; ?>
};
jQuery.post(ajaxurl, data, function(response) {
console.log('Got this from the server: ' + response);
});
}
}
});
})(jQuery);
</script>
<?php
}
add_action('wp_ajax_get_place_id', 'get_place_id');
function get_place_id() {
$post_id = $post->ID;
$place_id = $_POST['place_id'];
$post_id = $_POST['post_id'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$address = $_POST['address'];
$value = array(
'address' => $address,
'lat' => $lat,
'lng' => $lng,
'place_id' => $place_id
);
update_field('map', $value, $post_id);
echo $place_id;
wp_die();
}
This seems a little hacky though. It would be great if the ACF Map field pulled in more info from the API and let devs decide what is needed.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.