当我单击下面的代码时,它显示locationsgohere
为空白,当我再次单击它时,它会locationsgohere
显示应有的数据。
比如说我London, UK
在textarea
#id
这应该显示output
为var locations = [['London,51.511214,-0.119824]],
但只有当我点击两次。我第一次点击它只显示var locations = [],
如果我单击它三遍,它只会显示以下内容var locations = [['London,51.511214,-0.119824]['London,51.511214,-0.119824]],
for
我在这个循环中做错了什么吗?
var locationsgohere,output;
$('.generate').click(function(){
var temp_addresses = document.getElementById("gps").value.split("\n");
for(var i=0;i<temp_addresses.length;i++){
addresses.push(temp_addresses[i]);
geocoder.geocode( { 'address': temp_addresses[i]}, function(response, status) {
geocode_results[i] = new Array();
geocode_results[i]['status'] = status;
var top_location = response[0];
var lat = Math.round(top_location.geometry.location.lat() * 1000000)/1000000;
var lng = Math.round(top_location.geometry.location.lng() * 1000000)/1000000;
geocode_results[i]['lat'] = lat;
geocode_results[i]['lng'] = lng;
geocode_results[i]['l_type'] = top_location.geometry.location_type;
locationsgohere += "['"+top_location.address_components[0].long_name+","+lat+","+lng+"]";
});
}
if (!locationsgohere){
locationsgohere = '';
}
output = 'var locations = ['+locationsgohere+'],';// JavaScript Document
});
更新代码
var temp_addresses = document.getElementById("gps").value.split("\n");
var todo = temp_addresses.length; // count the remaining requests
// for(var i=0;i<temp_addresses.length;i++){
for(var i=0;i<temp_addresses.length;i++){
(function(i){ // protect i in an immediately called function
addresses.push(temp_addresses[i]);
geocoder.geocode( { 'address': temp_addresses[i]}, function(response, status) {
geocode_results[i] = new Array();
geocode_results[i]['status'] = status;
var top_location = response[0];
var lat = Math.round(top_location.geometry.location.lat() * 1000000)/1000000;
var lng = Math.round(top_location.geometry.location.lng() * 1000000)/1000000;
geocode_results[i]['lat'] = lat;
geocode_results[i]['lng'] = lng;
geocode_results[i]['l_type'] = top_location.geometry.location_type;
// locationsgohere += "['"+top_location.address_components[0].long_name+","+lat+","+lng+"]";
});
if (--todo===0) { // finished
output = 'var locations = ['+(locationsgohere||'')+'],';
}
console.log(locationsgohere);
})(i);
// var output = 'var locations = ['+locationsgohere+'],';
}