AJAX Callback and Javascript class variables assignments

Posted by Gianluca on Stack Overflow See other posts from Stack Overflow or by Gianluca
Published on 2010-03-26T10:59:59Z Indexed on 2010/03/26 11:03 UTC
Read the original article Hit count: 497

I am trying to build a little javascript class for geocoding addresses trough Google Maps API.

I am learning Javascript and AJAX and I still can't figure out how can I initialize class variables trough a callback:

    // Here is the Location class, it takes an address and 
    // initialize a GClientGeocoder. this.coord[] is where we'll store lat/lng
    function Location(address) {
        this.geo = new GClientGeocoder();
        this.address = address;
        this.coord = [];                        
    }

    // This is the geoCode function, it geocodes object.address and 
    // need a callback to handle the response from Google
    Location.prototype.geoCode = function(geoCallback) { 
        this.geo.getLocations(this.address, geoCallback); 
    }

    // Here we go: the callback. 
    // I made it a member of the class so it would be able 
    // to handle class variable like coord[]. Obviously it don't work.
    Location.prototype.geoCallback = function(result) {
        this.coord[0] = result.Placemark[0].Point.coordinates[1];
        this.coord[1] = result.Placemark[0].Point.coordinates[0];
        window.alert("Callback lat: " + this.coord[0] + "; lon: " + this.coord[1]);
    }

    // Main
    function initialize() {
        var Place =  new Location("Tokyo, Japan");
        Place.geoCode(Place.geoCallback);
        window.alert("Main lat: " + Place.coord[0] + " lon: " + Place.coord[1]);
    }

    google.setOnLoadCallback(initialize);

Thank you for helping me out!

© Stack Overflow or respective owner

Related posts about AJAX

Related posts about JavaScript