Search code examples
javascriptweb-workerhere-apigeocode

how to move heavy geocoding to a web-worker?


I have very big list of geo points which I want to translate to coordinates with the geocoder and the best way I think is to move the task to a web worker, otherwise the Firefox times out and never loads the page.

// the main html file:
var myWorker = new Worker('datapointscollection.js');
  myWorker.onmessage = function(e) {
      document.getElementById('loadingStatus').innerHTML = count + " elements from " + all + "are ready.";
      if (count == all) {
        myWorker.terminate();
        myWorker = undefined;
      }
  };

   myWorker.postMessage([geocodingParams]);

// the worker js file:
self.importScripts("http://js.api.here.com/v3/3.0/mapsjs-core.js");
self.importScripts("http://js.api.here.com/v3/3.0/mapsjs-service.js");
self.importScripts("http://js.api.here.com/v3/3.0/mapsjs-ui.js");
self.importScripts("http://js.api.here.com/v3/3.0/mapsjs-mapevents.js");
self.addEventListener(
'message', 
function(e) {
  var count = 0;
  var all = 0;

  // Initialize the platform object:
  var platform = new H.service.Platform({
  'app_id': 'myappID',
  'app_code': 'myappCODE'
  });

  var geocoder = platform.getGeocodingService();

  var onResult = function(result) {};

  var findLocations = function(geocodingParams) {
    var i=0;
    all = geocodingParams.length;
    for (i=0; i<geocodingParams.length; i++) {
      geocoder.geocode(
        geocodingParams[i], 
        onResult, 
        function(e){
            alert(e);
        } );
      count = i;
      self.postMessage(count, all);
    }
  };

  findLocations(e.data[0]);
}, 
false);

I tried different approaches, but executing the worker script fails with different errors. The last problem is ReferenceError: document is not defined in mapsjs-core.js:158:623. and after a while another error: NetworkError: A network error occurred. from datapointscollection.js:1


Solution

  • For huge number of geocodes, you should consider batch geocoding. Check developer’s guide at developer.here.com