Whenever I interact with the code below, it initially displays locationsgohere
as empty. However, upon a second click, the data appears as expected.
For example, if I input London, UK
in the textarea
with the ID #id
, the corresponding output
should be
var locations = [['London,51.511214,-0.119824]],
. Strangely, this only happens after two clicks; on the first click, it just shows var locations = [],
.
If I click three times, an unexpected output is generated:
var locations = [['London,51.511214,-0.119824]['London,51.511214,-0.119824]],
I wonder if there's an issue with my implementation of the for
loop?
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
});
Updated snippet
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++){
(function(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;
});
if (--todo===0) {
output = 'var locations = ['+(locationsgohere||'')+'],';
}
console.log(locationsgohere);
})(i);
}