Support

Account

Home Forums ACF PRO Default marker for maps

Solving

Default marker for maps

  • Is there any way to set a default marker address in a map?

    Use case:
    We have a recurring event that is almost always at same location. When I create a new event (via a custom post type), I’d like the map marker to default to the usual location. And of course, be able to relocate it if necessary.

    Honestly, I could get by without the map UI in admin, and just have a field for the default address.

    Any thoughts?

    Thanks,
    Doug

  • Hi Doug,

    You can achieve it by using the acf/save_post hook and the update_field() function like this:

    function my_acf_default_map( $post_id ) {
        
        $selector = 'google_map_field_name';
        // get new value
        $value = get_field($selector, $post_id);
        
        if( !$value ){
            $value = array(
                "address" => "218 Abeckett St, Melbourne VIC 3000, Australia",
                "lat" => "-37.81025862543725",
                "lng" => "144.95670318603516"
            );
            
            update_field($selector, $value, $post_id);
        }
        
    }
    
    // run after ACF saves the $_POST['acf'] data
    add_action('acf/save_post', 'my_acf_default_map', 20);

    But if you only need the address, which is basically a text, then you can always use the text field and set the default value on the backend instead.

    I hope this helps 🙂

  • Thanks, James. Although this method centers the map, it doesn’t pre-populate the address field or set a marker. And without setting a marker, get_field returns nothing, defeating the purpose of the default value.

    And if the default were ever to change, a future person would have to know to edit our functions.php file, including lat and lng values.

    The alternative, using the text field, requires first geocoding the text and then integrating those values into Google’s js embed code. I’d hoped to avoid that sort of mucking around.

  • Hi @dougfitz

    Please keep in mind that the code I gave you will set the default address and position after you saved the post. You also need to empty the Google Map field if you have set a marker before.

    Could you please test it again by saving your post?

    Regarding changing the address in the future, you can always create an options page or add custom settings so that you can set them.

    Thanks 🙂

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Default marker for maps’ is closed to new replies.