2015-07-10 82 views
3

我有一個jQuery腳本,使Ajax調用的郵政編碼緯度& longitude.The郵編從隱藏的輸入字段檢索轉換。這部分工作正常。 ajax結果給我正確的緯度/經度。通緯度LNG VAR初始化函數谷歌地圖

HTML的一塊

<input id="zipcode" type="hidden" value="1010AK">

Ajax調用jQuery中:

jQuery(document).ready(function($){  
     var zipcode = jQuery('input#zipcode').val();  
     $.ajax({ 
     url: "http://maps.googleapis.com/maps/api/geocode/json?address=netherlands&components=postal_code:"+zipcode+"&sensor=false", 
     method: "POST", 
     success:function(data){ 
      latitude = data.results[0].geometry.location.lat; 
      longitude= data.results[0].geometry.location.lng; 
      coords = latitude+','+longitude; 
      //console.log(coords); 
      }  
     }); 
}); 

外(見下文)的文件準備功能,我有一個initialize()函數,我想能夠爲我coords VAR給該函數所以我正確的經度和緯度。

初始化函數(AJAX調用後):

function init() { 
     var mapOptions = { 
      zoom: 11,    
      center: new google.maps.LatLng(/* COORDS VAR */) 
     }; 

     var mapElement = document.getElementById('my_map'); 
     var map = new google.maps.Map(mapElement, mapOptions); 

     var image = '/wp-content/themes/example/img/foo.png'; 
     var myLatLng = new google.maps.LatLng(/* COORDS VAR */); 
     var customMarker = new google.maps.Marker({ 
      position: myLatLng, 
      map: map, 
      icon: image 
     }); 
    } 
    google.maps.event.addDomListener(window, 'load', init); 

我已經試過許多東西但我摔跤太長。基本上,我想我可以在COORDS VAR傳遞到初始化函數是這樣的:

  • function init(coords){}
  • google.maps.event.addDomListener(window, 'load', function(){initialize(coords);});

我也試着設置AJAX async: false,並補充dataType: 'json'但沒有讓我有機會傳遞給init函數。

回答

1

您的問題是init()已經在您的AJAX請求返回之前運行(感謝您添加了掛鉤window.load)。您需要刪除鉤,和success處理程序中手動調用init。試試這個:

jQuery(document).ready(function($){  
    var zipcode = jQuery('input#zipcode').val();  
    $.ajax({ 
     url: "http://maps.googleapis.com/maps/api/geocode/json", 
     data: { 
      address: 'netherlands', 
      components: 'postal_code:' + zipcode, 
      sensor: false 
     }, 
     method: "POST", 
     success: function(data){ 
      var lat = data.results[0].geometry.location.lat; 
      var lng = data.results[0].geometry.location.lng; 
      init(lat, lng); 
     }  
    }); 
}); 

function init(lat, lng) { 
    var latlng = new google.maps.LatLng(lat, lng); 
    var mapOptions = { 
     zoom: 11,    
     center: latlng 
    }; 

    var map = new google.maps.Map($('#my_map')[0], mapOptions); 
    var customMarker = new google.maps.Marker({ 
     position: latlng, 
     map: map, 
     icon: '/wp-content/themes/decevents/img/marker_darkblue.png' 
    }); 
} 
+0

你太了不起了。它工作正確!非常感謝。 – Paul

+0

謝謝:)很高興幫助 –