简体   繁体   中英

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

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

It looks like the files you are importing into your worker depend on a DOM existing. Your web worker doesn't have a DOM, so you will have to use dependencies that don't need a DOM (if it will work in node, it will work without a DOM). Check the documentation for your dependencies to see if there a version that works in node or doesn't need a DOM, and use that version in your web worker. (It might be just the mapsjs-service.js file. see if you can get away with just that).

See also Web Workers API

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM