2015-07-10 79 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

谢谢:)很高兴帮助 –