jQuery 和 Google Maps json 响应 [英] jQuery and Google Maps json response
问题描述
我在从 google maps api 获取地理位置信息时遇到问题
I am having troubles getting geo location info from google maps api
代码很简单
$.ajax({
type: "GET",
cache: false,
url: "http://maps.googleapis.com/maps/api/geocode/json",
dataType: "jsonp",
data: {
address: "Ljubljana " + "Slovenia",
sensor: "false"
},
jsonpCallback:'json_response',
success: function(data) {
top.console.debug(data);
$('#location_setter').dialog('close');
},
error: function() {
alert("Error.");
}
});
function json_response(data){
alert("works");
}
我总是收到错误消息.我也直接尝试过(我在某处读到应该在最后设置回调...
I always get an error back. I tried directly too (I read somewhere that the callback should be set at the end...
$.ajax({
type: "GET",
cache: true,
url: "http://maps.googleapis.com/maps/api/geocode/json?address=Ljubljana Slovenia&sensor=false",
dataType: "jsonp",
jsonpCallback:'json_response',
success: function(data) {
top.console.debug(data);
$('#location_setter').dialog('close');
},
error: function() {
alert("Error.");
}
});
请求 url 格式正确:
the request url is correctly formed:
它给了我正确的 json
and it gives me the correct json
请多多指教!
您可以在http://jsfiddle.net/PNad9/
推荐答案
如果它对某人有帮助...我放弃了,我完全改变了逻辑本身,现在它按预期工作:
if it helps somebody... I gave up and I completely change the logic itself and now it works as expected:
首先我将 google maps js 附加到 body 中
first I appended google maps js into the body
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://maps.google.com/maps/api/js?sensor=false&callback=get_longlat';
$("body").append( script );
如你所见,我指定了回调函数 get_longlat...
as you can see I specified the callback function get_longlat...
所以我定义了这个函数并使用了谷歌的地理编码对象
so I defined this function and used google's geocode object
function get_longlat(address){
var geocoder = new google.maps.Geocoder();
if(!address){
var p = US.get("location_postal");
var c = US.get("location_city");
var a = US.get("location_address");
var address = a + ', ' + p + ' ' + c + ', Slovenia';
}
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
US.set("location_lat", results[0].geometry.location.lat(), 60);
US.set("location_lon", results[0].geometry.location.lng(), 60);
$('#location_setter').dialog('close');
}
else {
console.log('No results found: ' + status);
}
});
}
}
里面的 US 变量是我们自己的 USER SETTINGS 命名空间
The US variables inside is our own namespace for USER SETTINGS
希望对大家有所帮助
这篇关于jQuery 和 Google Maps json 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!