DS_web_developer DS_web_developer - 7 months ago 49
Javascript Question

jQuery and Google Maps json response

I am having troubles getting geo location info from google maps api

the code is pretty straight forward

$.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.");
}
});


the request url is correctly formed:

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

and it gives me the correct json

please advise!

You can 'play' with it at http://jsfiddle.net/PNad9/

Answer

if it helps somebody... I gave up and I completely change the logic itself and now it works as expected:

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 );

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);
        }
    });
}

}

The US variables inside is our own namespace for USER SETTINGS

hope it helps somebody