scopeak
scopeak

Reputation: 545

Sending AJAX response to Google Maps location markers with JSON

Upon clicking a button, an AJAX response is called to output JSON based on a search query. I would like to use the variable all_locations from the AJAX response, to output into the Google map markers. Not too sure how this can be done. I researched into using async as false but to no success.

Form

<form id="filter">
    <span class="ek-search-address col-xs-8">
      <label for="address">Location</label>
      <input id="address" name="property_location" value="New York" placeholder="Input Address" type="text"/>
    </span>

    <span class="ek-search-radius live-search col-xs">
     <select id="radius_km">
         <option value=1>1km</option>
         <option value=2>2km</option>
         <option value=5>5km</option>
         <option value=30>30km</option>
     </select>
    </span>
    <button onClick="showCloseLocations()">Search</button>
    <input type="hidden" name="action" value="ek_search">
</form>

<div id="map_canvas">

AJAX call

jQuery(function($){
    $('#filter').submit(function(){
        var filter = $('#filter');
        var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
        data = { action: "ek_search"};
        var all_locations = $.ajax({
            url: ajaxurl,
            data:data,
            async:false,
            type: 'POST', // POST
            dataType: 'json',
            success: function(response) {
            console.log(response);  
            }
        });
        return false;
    });
});

map.js

jQuery(function($) {
var map = null;
var radius_circle;
var markers_on_map = [];
var geocoder;
var infowindow;


new google.maps.places.Autocomplete(
    (document.getElementById('address')), {
        types: ['geocode']
    });

//initialize map on document ready
$(document).ready(function() {
    var latlng = new google.maps.LatLng(50.927978, -5.408908);
    var myOptions = {
        zoom: 17,
        center: latlng,
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        },
        navigationControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    geocoder = new google.maps.Geocoder();
    google.maps.event.addListener(map, 'click', function() {
        if (infowindow) {
            infowindow.setMap(null);
            infowindow = null;
        }
    });
});

function showCloseLocations() {
    var i;
    var radius_km = $('#radius_km').val();
    var address = $('#address').val();

    //remove all radii and markers from map before displaying new ones
    if (radius_circle) {
        radius_circle.setMap(null);
        radius_circle = null;
    }
    for (i = 0; i < markers_on_map.length; i++) {
        if (markers_on_map[i]) {
            markers_on_map[i].setMap(null);
            markers_on_map[i] = null;
        }
    }

    if (geocoder) {
        geocoder.geocode({
            'address': address
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                    var address_lat_lng = results[0].geometry.location;
                    radius_circle = new google.maps.Circle({
                        center: address_lat_lng,
                        radius: radius_km * 1000,
                        clickable: false,
                        map: map
                    });
                    if (radius_circle) map.fitBounds(radius_circle.getBounds());
                    for (var j = 0; j < all_locations.length; j++) {
                        (function(location) {
                            var marker_lat_lng = new google.maps.LatLng(location.lat, location.lng);
                            var distance_from_location = google.maps.geometry.spherical.computeDistanceBetween(address_lat_lng, marker_lat_lng); //distance in meters between your location and the marker
                            if (distance_from_location <= radius_km * 1000) {
                                var new_marker = new google.maps.Marker({
                                    position: marker_lat_lng,
                                    map: map,
                                    title: location.name
                                });
                                google.maps.event.addListener(new_marker, 'click', function() {
                                    if (infowindow) {
                                        infowindow.setMap(null);
                                        infowindow = null;
                                    }
                                    infowindow = new google.maps.InfoWindow({
                                        content: '<div style="color:red">' + location.name + '</div>' + " is " + distance_from_location + " meters from my location",
                                        size: new google.maps.Size(150, 50),
                                        pixelOffset: new google.maps.Size(0, -30),
                                        position: marker_lat_lng,
                                        map: map
                                    });
                                });
                                markers_on_map.push(new_marker);
                            }
                        })(all_locations[j]);
                    }
                } else {
                    alert("No results found while geocoding!");
                }
            } else {
                alert("Geocode was not successful: " + status);
            }
        });
    }
}

});

Upvotes: 0

Views: 1956

Answers (1)

Mahesh Singh Chouhan
Mahesh Singh Chouhan

Reputation: 2588

Ajax is an asynchronous process, so you need to send all locations as an parameter inside success callback function

Try this:

Ajax:

jQuery(function($){
    $('#filter').submit(function(e){
        e.preventDefault();//preventing form to submit with page reload
        var filter = $('#filter');
        var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
        data = { action: "ek_search"};
        $.ajax({
            url: ajaxurl,
            data:data,
            async:false,
            type: 'POST', // POST
            dataType: 'json',
            success: function(response) {
                console.log(response);  
                showCloseLocations(response.all_locations);
            }
        });
        return false;
    });
});

Update function showCloseLocations to accept all_locations as parameter

function showCloseLocations(all_locations) {
    //show location function code here
}

Question: I would like to know how you are submitting your form with #filter? because there is no submit type button in your html, make sure to change type of search button to submit instead of button so that first form can submit with search input to get all locations

<button type="submit">Search</button>

Upvotes: 2

Related Questions