Currently, I am experimenting with web worker threads to retrieve directions between various pairs of locations simultaneously and save the data in a file at the end. The process worked smoothly when attempted sequentially. I am using npm live-server to showcase the webpage. However, the browser abruptly closes the page right after loading, and I am unable to view the rendered content or check the console for any potential errors. When I include 'async defer' in the script tag with the Google API in index.html, it throws an error stating "UncaughtReferenceError: google is not defined." I appreciate any help or insights on this matter!
Let me share my index.html with you:
<!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>
Now, let's take a look at my 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);
}
Finally, let's go through the 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();
});