Populate a Map at The Same Time as showing Posts via AJAX

Question

I have a map search page on my site. I’m able to display all the locations in a list in HTML but I am struggling to pass the locations to JavaScript at the same time in order to populate the pins on my Google map.

I only seem to be able to get wp_localize_script to work on the initial page load and during the AJAX call.

This is my javascript:

jQuery(document).on( 'submit', '#locationsearch', function() {
    var form = jQuery(this);
    var input = form.find('input[name="postcode"]');
    var query = input.val();
    var map=jQuery('#map');
    var content = jQuery('#results');

    jQuery.ajax({
        type : 'post',
        url : myAjax.ajaxurl,
        data : {
            action : 'getStockistLocations',
            query : query
        },
        beforeSend: function() {
            console.log('fetching');
            input.prop('disabled', true);
            content.addClass('loading');
        },
        success : function( response ) {
            console.log(myAjax.locations);
            input.prop('disabled', false);
            content.removeClass('loading');
            map.removeClass('hide-map');
            content.html( response );
        }
    });

    return false;
});

My console.log(myAjax.locations) keeps returning “undefined”.

Here is my PHP function:

public function getStockistLocations(){
        $postcode = $_POST['query'];

        $geocode=new Geocoder();
        $lnglat = $geocode->geocodePostcode($postcode);

        $results=$this->getStockists($lnglat);
        if( !empty($results) ) {
            wp_localize_script( 'main', 'myAjax.locations', $results );
            ob_start();
            foreach ($results as $result){
                global $locationresult;
                $locationresult=$result;

                get_template_part('template_parts/cards/card','location');
            }
            $content = ob_get_clean();

            echo $content;
        }

        die();
    }

I’m localizing my script in another class:

protected function localizeScripts(){
        global $post;

        $mappages=[
            'contact',
            'where-to-buy',
            'find-an-installer'
        ];

            if(in_array($post->post_name,$mappages)){
                $payload=array(
                    'url'   =>  get_stylesheet_directory_uri(),
                    'ajaxurl'  =>  admin_url('admin-ajax.php'),
                );

                wp_localize_script( 'main', 'myAjax', $payload );
                $key=$this->getAPIKeys('google');
                wp_enqueue_script('gmap','https://maps.googleapis.com/maps/api/js?key='.$key.'&callback=initMap',null,false,true);
        }
    }

What am I missing?

0
, Burgi 2 years 2019-10-21T09:23:48-05:00 0 Answers 82 views 0

Leave an answer

Browse
Browse