Support

Account

Home Forums General Issues Using the Google Maps field to output segments of an address

Unread

Using the Google Maps field to output segments of an address

  • The documentation for the Google Map field demonstrates a really nice way to render addresses using the address entered into the field.

    <?php 
    $location = get_field('location');
    if( $location ) {
    
        // Loop over segments and construct HTML.
        $address = '';
        foreach( array('street_number', 'street_name', 'city', 'state', 'post_code', 'country') as $i => $k ) {
            if( isset( $location[ $k ] ) ) {
                $address .= sprintf( '<span class="segment-%s">%s</span>, ', $k, $location[ $k ] );
            }
        }
    
        // Trim trailing comma.
        $address = trim( $address, ', ' );
    
        // Display HTML.
        echo '<p>' . $address . '.</p>';
    }

    For my project I am working with small towns in the UK so city, state and country are not relevant. Instead, I would like to use postal_town and administrative_area_level_2 in place of these which should render the town and county respectively. So for the foreach I have

    foreach( array( 'street_number', 'street_name', 'postal_town', 'administrative_area_level_2', 'post_code' ) as $i => $k ) { ... }

    I had assumed that this would return: number, street, town, county, post-code. But the postal_town and administrative_area_level_2 both return nothing.

    Printing the array keys using <?php print_r(array_keys($location)); ?> appears to show only a limited set of options.

    I could as a compromise just use <?php echo $location['address']; ?> but this gives a slightly different version of the address (Business name, street, town, country), but it’s not quite what I’m after.

    Does anyone know how would I go about getting my chosen values to render to the front end without having to resort to a separate address input field?

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.