2017-07-03 46 views
0

單擊某個按鈕後,會根據搜索查詢調用AJAX響應以輸出JSON。我想使用AJAX響應中的變量all_locations來輸出到Google地圖標記中。不太確定如何做到這一點。我研究了使用async作爲false,但沒有成功。使用JSON發送對Google地圖位置標記的AJAX響應

<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調用

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); 
      } 
     }); 
    } 
} 

});

回答

1

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; 
    }); 
}); 

更新功能showCloseLocations接受all_locations作爲參數

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

問題:我想知道你是如何提交你的表格與#filter?因爲有你的HTML沒有提交類型的按鈕,請確保更改搜索按鈕的類型submit而不是button,使第一種形式可以與搜索輸入提交獲得的所有位置

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

謝謝!我會給你一個鏡頭。我提交時使用了'#filter'格式化了原始代碼:) – scopeak

+1

@scopeak酷!讓我知道如果你有任何問題,如果它的工作也標記這個答案有幫助,以便它可以幫助別人:) –

+0

會做!所以我設法讓JSON數據通過成功,但現在收到這個錯誤'TypeError:undefined不是一個對象(評估'all_locations.length')'我在'showCloseLocations'函數後調用Ajax。 – scopeak