我有一个 jQuery 脚本,它进行 Ajax 调用以将邮政编码转换为纬度和经度。邮政编码是从隐藏的输入字段中检索的。那部分工作正常。 ajax 结果为我提供了正确的纬度/经度。
一段 HTML
<input id="zipcode" type="hidden" value="1010AK">
jQuery 中的 Ajax 调用:
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 传递给 init 函数:
-
function init(coords){}
-
google.maps.event.addDomListener(window, 'load', function(){initialize(coords);});
我还尝试设置 ajax async: false
, 并添加了 dataType: 'json'
但这并没有给我机会传递给 init 函数。
最佳答案
您遇到的问题是,在您的 AJAX 请求返回之前,init()
已经运行(由于添加了到 window.load
的 Hook )。您需要删除该 Hook ,并在 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'
});
}
关于javascript - 传递 Lat Lng var 来初始化函数 google maps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31337420/