Extracting Address from Custom Post via Javascript for Google Maps API

Well, this is kind of easy..

The google-map API needs a format like Your Street 123, 54321 Your City

Assuming you have your data like this:

<div id="street">Your Street 123</div>
<div id="zip">54321</div>
<div id="city">Your City</div>

Assuming you are using jQuery:

(function($){
    $.fn.create_gmap_address = function() {

        var street = $('#street').html();
        var zip = $('#zip').html();
        var city = $('#city').html();

        return street + ',' + zip + ' ' + city;
    }
})(jQuery);

And then in your maps API code:

geocoder.geocode( { 'address': $.create_gmap_address() }, function(results, status) {
    // your maps code

Solution 2

Or you could, of course, get all this data via php and then store into a global JS variable (maybe the better way).

function set_address_js_var() {
    if ( 'your_post_type' == get_post_type() ) {
        // Assuming you are using meta fields to store the address
        $postMeta = get_post_meta(get_the_ID());
        return $postMeta['sreet'] . ',' . $postMeta['zip'] . ' ' . $postMeta['city'];
    }
}
function load_fe_scripts() {
    wp_enqueue_script( 'global-js-var', get_template_directory_uri() . '/js/my_file.js' );
    $localize_array = array(
        'google_maps_address' => set_address_js_var()
    );
    wp_localize_script( 'global-js-var', 'my_global', $localize_array );
}
add_action('wp_enqueue_scripts', 'load_fe_scripts');

You can now acces the var in your JS File by my_global.google_maps_address