I am using Web Workers for the first time, and need some help making my function work.
Here is my code:
var myWorker = new Worker('./js/worker.js');
...
for(i = 0; i < passaggi.length; i++) {
lat = passaggi[i].lat;
lon = passaggi[i].lon;
timestamp = passaggi[i].timestamp;
myWorker.postMessage([lat, lon]);
myWorker.onmessage = function(e) {
console.log('Message received from worker');
nome = e.data
tmp = "<table border='1'><tr><td>" + i + "</td><td>" + nome + "</td><td>" + timestamp + "</td></tr></table>";
tabella.innerHTML += tmp;
}
}
Passaggi is an array; I want the worker to parse 'lat' and 'lon' of each item of the array using the Google Geocoding API, return the name of the town.
When the main function receives the message, a table is added containing the name and a timestamp. Tabella is the div that will contain it.
Problem is, the function creates the correct number of tables but each contains the data for the last element in passaggi! Output example:
| 4 | Rome | 2015-09-14 23:44:38 |
| 4 | Rome | 2015-09-14 23:44:38 |
| 4 | Rome | 2015-09-14 23:44:38 |
| 4 | Rome | 2015-09-14 23:44:38 |
This is the content of worker.js, but the code seems to be fine:
onmessage = function(data){
var mapAPI = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + data.data[0] + "," + data.data[1] + "&sensor=true";
var req = new XMLHttpRequest();
req.open('GET', mapAPI, true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4){
if(req.status == 200){
result = JSON.parse(req.responseText);
console.log(result);
message = result.results[0].address_components[2].long_name;
postMessage(message);
}
else
console.log("Error loading page\n");
}
}
req.send(null);
}
As I understand, Web Workers are useful for executing functions in background without blocking the rest of the page; parsing coordinates seemed a good application, for that. What am I doing wrong?
Thanks in advance for your help.