簡體   English   中英

Google Maps的Web Worker線程

[英]Web Worker threads for Google Maps

我正在嘗試使用網絡工作者線程來並行捕獲多對位置之間的方向並將文本最終存儲在文件中。 在順序方法中一切進展順利。 我正在使用npm live-server顯示頁面。 但是瀏覽器僅在加載頁面后立即關閉頁面,我什至看不到呈現的內容或向控制台查詢錯誤。 如果我對index.html中的google Api使用“異步延遲”作為腳本標簽,則會收到“ UncaughtReferenceError:未定義google”錯誤。 在此先感謝大家!

這是我的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>

這是我的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);
}

最后,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 worker在Javascript中有自己的作用域。 這意味着您在網頁范圍內加載的所有腳本在Web Worker范圍內將不可用。

通常,您使用importScripts調用來加載腳本。 但是,這不適用於您的情況,因為您還嘗試在Web Worker中訪問DOM。 由於多種原因,這在Web worker中是不可能的(最重要的是並發訪問不是線程節省的數據結構)。

查看您的代碼,我認為您不需要網絡工作者來計算路由。 無論如何,實際路由很可能是在Google的一台服務器上完成的。 由於無論如何這都是異步的,因此您無需擔心阻止網頁的UI。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM