ibr*_*lah 6 javascript ajax distance google-maps-api-2
目前该程序正在运行,但由于alert()我在getData()功能中使用的功能,界面很烦人!! 当我从getData()函数中删除这一行时整个程序出错!! 我不知道是什么问题?谁有人有更好的想法做这样的过程?
我在这里尝试的程序旨在帮助用户找到离他们当前地址50公里范围内的餐馆,我已经收集了各种位置地址并将其记录在数据库中.
initialize()加载HTML主体时调用的函数,在HTML主体的第一行中,使用PHP从MySQL中提取餐厅数据,将数据打印到JavaScript数组jsres_add,jsres_id,jsres_name和jsnu中,以便我可以在JavaScript代码中使用它们.*请注意,下面的JavaScript代码在.js文件中分隔
var geocoder, location1, location2, gDir, oMap, jsnu, arraynu, address2;
jsres_add = new Array();
jsres_id = new Array();
jsres_name = new Array();
function initialize() {
geocoder = new GClientGeocoder();
gDir = new GDirections();
GEvent.addListener(gDir, "load", function() {
var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
if (drivingDistanceKilometers < 50){
// function to save search result within 50km into database using ajax
saveSearchResult(jsres_id[arraynu],jsres_name[arraynu],drivingDistanceKilometers);
}
});
}
function getData() {
emptytable(); //function to empty search result table using ajax
//jsnu is the number of the restaurants data found in database
for (var ii = 0; ii < jsnu; ii++) {
arraynu = ii;
address2 = jsres_add[ii];
showLocation();
alert("done!");
}
showResults(); //function to print out the search result from database into html body using ajax
}
function showLocation() {
geocoder.getLocations(document.forms[0].address1.value, function (response) {
if (!response || response.Status.code != 200){
alert("Sorry, we were unable to geocode your address");
}else{
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
geocoder.getLocations(address2, function (response) {
if (!response || response.Status.code != 200){
alert("Sorry, we were unable to geocode the second address");
}else{
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
gDir.load('from: ' + location1.address + ' to: ' + location2.address);
}
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
如果函数的存在alert()使代码可以工作,我猜这是与计时相关的问题,特别是address2在收到地理编码器服务的响应之前,您的代码似乎被覆盖了。
[编辑]
设置 jsfiddle 后,我更仔细地检查了您的代码并使其正常工作:
address2确实被覆盖了,但这不是唯一的问题,事实上您使用的所有变量都是全局的。特别是,我必须GDirections为您发出的每个请求创建一个实例(共享一个实例会在显示第一个结果之前覆盖它)。
为了理解为什么你的代码不起作用,我建议你搜索和研究一些关于异步方法调用的材料。
另外,作为一般经验法则(对于 Javascript 和一般编程),尽量避免将变量放在全局范围内,但将它们的生命周期限制在尽可能小的范围内,这将在很多方面有所帮助:它将减少变量名称冲突,同时提高性能(变量仅在必要时才存在)和代码的可读性(更容易跟踪值)。