jQuery 和 Google map json 响应

标签 jquery ajax json api maps

我在从 Google map 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");
}

我总是收到错误消息。 我也直接尝试过(我在某处读到回调应该设置在最后......

$.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 格式正确:

http://maps.googleapis.com/maps/api/geocode/json?address=Ljubljana%20Slovenia&sensor=false&callback=json_response

它给了我正确的 json

请多多指教!

您可以在 http://jsfiddle.net/PNad9/ 上“玩”它

最佳答案

如果它对某人有帮助......我放弃了,我完全改变了逻辑本身,现在它按预期工作:

首先我将谷歌地图js附加到正文中

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...

所以我定义了这个函数并使用了谷歌的地理编码对象

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命名空间

希望对大家有帮助

关于jQuery 和 Google map json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659663/

相关文章:

php - 使用ajax将表中的数据插入数据库

c# - 如何仅对某些属性应用缩进序列化?

java - 如何使用 Binary Builder 动态地将 JSON 插入 Apache Ignite Cache(没有 Java 类)?

javascript - HTML 使元素无效放置目标

php - 如何保存jquery动态生成的数据

javascript - 突出显示重复字符串

jquery - laravel中如何从ajax请求中获取数据

json - 如何将数据框转换为自定义 json 格式

javascript - 如果 div 文本等于某些文本会做什么?

javascript - 动态加载时如何检测jquery是否已加载