【发布时间】:2010-03-26 10:59:59
【问题描述】:
我正在尝试通过 Google Maps API 为地址地理编码构建一个小的 javascript 类。我正在学习 Javascript 和 AJAX,但我仍然不知道如何通过回调初始化类变量:
// 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);
谢谢你帮助我!
编辑
感谢TJ 的回复。我读了你的例子和你的帖子——事情变得更清楚了。但我还有一个问题。看看:
function bind(context, func) {
return function() {
return func.apply(context, arguments);
}
}
function Location(address) {
this.geo = new GClientGeocoder();
this.address = address;
this.coord = [];
}
Location.prototype.geoCode = function(callback) {
this.geo.getLocations(this.address, callback);
}
Location.prototype.geoCallback = function(result) {
this.coord[0] = result.Placemark[0].Point.coordinates[1];
this.coord[1] = result.Placemark[0].Point.coordinates[0];
// This alert is working properly, printing the right coordinates
window.alert("I am in geoCallback() lat: " + this.coord[0] + "; lon: " + this.coord[1]);
}
function initialize() {
var Place = new Location("Tokyo, Japan");
Place.geoCode(bind(Place, Place.geoCallback));
window.alert("I am in initialize() lat: " + Place.coord[0] + "; lon: " + Place.coord[1]);
}
为什么 initialize() 中的警报在 geoCallback() 中的警报之前弹出,打印一个未定义/未定义?
【问题讨论】:
-
initialize()中的警报在geoCallback()中的警报之前弹出,因为getLocations是异步的(AJAX 代表异步 Javascript...)。
标签: javascript ajax callback geocoding google-maps