【发布时间】:2015-09-29 00:07:30
【问题描述】:
我有一个 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 函数。
【问题讨论】:
标签: javascript jquery ajax google-maps