简体   繁体   English

Google Maps的Web Worker线程

[英]Web Worker threads for Google Maps

I am trying to use web worker threads to grab directions between multiple pairs of locations parallelly and store the text in a file in the end. 我正在尝试使用网络工作者线程来并行捕获多对位置之间的方向并将文本最终存储在文件中。 Everything had gone well in the sequential approach. 在顺序方法中一切进展顺利。 I am using npm live-server to display the page. 我正在使用npm live-server显示页面。 But the browser just closes the page instantly after it loads and I don't even get to see what rendered or consult the console for errors. 但是浏览器仅在加载页面后立即关闭页面,我什至看不到呈现的内容或向控制台查询错误。 If I use 'async defer' for my script tag with the google Api in index.html, I would get the "UncaughtReferenceError: google is not defined" error. 如果我对index.html中的google Api使用“异步延迟”作为脚本标签,则会收到“ UncaughtReferenceError:未定义google”错误。 Thanks in advance guys! 在此先感谢大家!

Here is my index.html: 这是我的index.html:

<!DOCTYPE html>
<html>
<head>
   <title>Simple Map</title>
   <meta name="viewport" content="initial-scale=1.0">
   <meta charset="utf-8">
   <style>
       #map {
           height: 100%;
           width: 100%;
       }
       html, body {
           height: 100%;
           margin: 0;
           padding: 0;
       }
       panel {
           display: block;
       }
   </style>
   </head>
   <body>
       <panel></panel>
       <div id="map"></div>
       <script src=locations.js></script>
       <script src='main.js'></script>
       <script src='worker.js'></script>
       <script src="https://maps.googleapis.com/maps/api/js?key=<API-KEY>&callback=initMap"></script>
   </body>
</html>

Here is my main.js: 这是我的main.js:

let worker = new Worker('worker.js');
worker.onmessage = function(info) {
    output += info.data;
};

const container = document.querySelector('panel');
let output = ""

function initMap() {
    locations.forEach( spot => {
        worker.postMessage(spot);
    });

    download("data.txt", output, 'text/plain');
    console.log("Output: " + output);
}

function download(name, text, type) {
    const file = new Blob([text], {type: type});
    const atag = '<a href="' + URL.createObjectURL(file) + '" download="' + name + '">Download</a>';
    container.insertAdjacentHTML('afterbegin', atag);
}

And, finally the worker.js: 最后,worker.js:

let directionsService;
let directionsDisplay;
let map;
self.addEventListener('message', (e) => {
    directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
    const mapOptions = {
        center: {lat: 30, lng: -90},
        zoom: 6
    }
    map = new google.maps.Map(document.getElementById('map'), mapOptions);
    directionsDisplay.setMap(map);
    let request = {
        origin: 'New Orleans, LA',
        destination: e.data,
        travelMode: 'DRIVING',
        provideRouteAlternatives: false,
        drivingOptions: {
            departureTime: new Date('September 7, 2018 15:00:00'),
            trafficModel: 'pessimistic'
        },
        unitSystem: google.maps.UnitSystem.IMPERIAL
    };

    directionsService.route(request, (result, status) => {
        if (status == 'OVER_QUERY_LIMIT') {
            console.log('over');
        }
        if (status == 'INVALID_REQUEST'){
            console.log('other status')
        }
        if (status == 'OK') {
            var data = result["routes"][0].legs[0];
            postmessage(e.data + ", " + data["distance"].text + ", " + data["duration"].text + "\n");
            directionsDisplay.setDirections(result);
            console.log(result);
        }  
   });
   self.close();
});

Web workers have their own scope in Javascript. Web worker在Javascript中有自己的作用域。 This means any scripts you loaded in the scope of the web page will not be available in the scope of the web worker. 这意味着您在网页范围内加载的所有脚本在Web Worker范围内将不可用。

Usually you use the importScripts call to load a script. 通常,您使用importScripts调用来加载脚本。 However this won't work in your case because you also try to access the DOM in the web worker. 但是,这不适用于您的情况,因为您还尝试在Web Worker中访问DOM。 This is not possible in a web worker for a number of reason (most important would be concurrent access to a data structure which is not thread save). 由于多种原因,这在Web worker中是不可能的(最重要的是并发访问不是线程节省的数据结构)。

Looking at your code I don't think you need a web worker to calculate the routes. 查看您的代码,我认为您不需要网络工作者来计算路由。 Most likely the actual routing is done on one of Googles servers anyway. 无论如何,实际路由很可能是在Google的一台服务器上完成的。 Since this would be async anyway you do not need to worry about blocking the UI of your web page. 由于无论如何这都是异步的,因此您无需担心阻止网页的UI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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