Map data stored offline with the use of indexeddb and JSON documents

Looking to create an offline map using topoJSON and openlayers for map generation.

I stored the JSON data in indexeddb as a blob and tried converting it back to JSON. Everything was going smoothly until I encountered an error while converting the blob back, resulting in: [object%20Promise] Failed to load resource: the server responded with a status of 404 (Not Found).

(Just a quick note that Dexie is an indexeddb wrapper)

    var db = new Dexie("json_db");
db.version(1).stores({
    jsons: '++id'
});

getBlobAndPutInDB("https://openlayers.org/en/v4.6.5/examples/data/topojson/world-110m.json");

function initMap() {

    var style = new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.6)'
        }),
        stroke: new ol.style.Stroke({
            color: '#319FD3',
            width: 1
        })
    });

    var vector = new ol.layer.Vector({
        source: new ol.source.Vector({

            url: blobToJSON(),
            format: new ol.format.TopoJSON({
                layers: ['countries']
            }),
            overlaps: false
        }),
        style: style
    });

    var map = new ol.Map({
        layers: [vector],
        target: 'map',
        view: new ol.View({
            center: [0, 0],
            zoom: 1
        })
    });

}

async function blobToJSON() {

    let blob = await db.jsons.get(2);
    var file = new File([blob], "map.json", { type: "application/json", lastModified: Date.now() });
    return file;
}

function getBlobAndPutInDB(url) {

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function (e) {
        if (this.status === 200) {
            var myBlob = this.response;
            db.jsons.put(myBlob);
        }
    };
    xhr.send();
}
<!DOCTYPE html>
<html>
<head>
    <title>Map</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
    <script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
    <script src="https://unpkg.com/dexie@latest/dist/dexie.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="OfflineMap.js"></script>
</head>
<body>
    <div id="map" class="map"></div>
    <script>initMap();</script>
</body>
</html>

If anyone has suggestions or solutions, I'd greatly appreciate it :)

Answer №1

When setting the URL to blobToJSON(), a promise is being assigned. It's important to ensure that the promise is resolved before attempting to utilize the result.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a static image on an HTML5 canvas without any movement

As a novice in canvas game development, I must apologize for my lack of knowledge. I have an image with dimensions 2048px width and 1536px height that needs to be placed within a canvas (the width and height vary on different devices). While I am able to ...

The slider class in the div is not showing the image, but it is visible in the elements

Is the sequence of loading .css and .js files in the head section important for displaying images with the .slider class on MaterializeCSS? <!DOCTYPE html> <html> <head> <!--Import Google Icon Font--> <link href="htt ...

Is your website's Google analytics event tracking not giving you the feedback you need

Here's what I'm trying to achieve in the code below: Set up Google Analytics on the page Add a jQuery click event based on specific query strings and domain characters Trigger a Google Analytics tracking event with the click event Implement cod ...

TypeScript's type assertions do not result in errors when provided with an incorrect value

We are currently using the msal library and are in the process of converting our javaScript code to TypeScript. In the screenshot below, TypeScript correctly identifies the expected type for cacheLocation, which can be either the string localStorage, the ...

Jquery Position behaving unexpectedly during initial invocation

My goal is to have the autocomplete menu open above the input box if there is not enough space below it. The code functions properly, except for the initial render. It consistently displays at the bottom in the following scenarios: 1. When starting a searc ...

The array is remaining empty

When I need to loop through a JSON file, I typically use the following code snippet: var list = new Array(); $.getJSON("json.js", function (data) { $.each(data, function () { $.each(this, function (k, v) { var list = new Array(); ...

Is there a way to determine if a submit button has been clicked in order to prevent my function from executing?

I'm currently developing a platform for uploading images. Once a user uploads an image successfully, it gets saved in 4 different sizes within separate folders. They are then redirected to the same page with new content, where they can proceed to crop ...

What could be the reason behind encountering the UnhandledPromiseRejectionWarning error while executing npm build in my serverless application?

I am encountering an issue while attempting to execute npm build on my serverless aws-nodejs-typescript project. I am unsure of how to resolve it. Can someone provide guidance on how to troubleshoot this problem? npm build (node:44390) UnhandledPromiseRej ...

Anticipating the conclusion of a pending GET request

Currently, I am developing a system to create user accounts. There is a function in place that checks for the existence of a username and returns false if it doesn't exist. However, when another function calls this username checker, it automatically ...

Verify the attribute of the child element

In my child component, I have a property named files, which is an input type=file. This property allows me to determine if the user has selected a file for upload so that I can disable the submit button if no files are present in the input field. The issue ...

React JS high-performance asynchronous computations

I'm currently facing a challenge with JavaScript while trying to perform complex calculations. I am using React together with Redux. Although making fetch or server requests using libraries like fetch or jQuery ajax works asynchronously as expected, ...

Store image selection in state

I am currently working on building an imagePicker in ReactNative, but I am running into an issue when trying to select the image. The error message I am receiving is: TypeError: this.setState is not a function. (In 'this.setState ({ avatar: data}) &a ...

The image fails to load after I moved the routers from the server file (entry point file) to the controller file

I recently made the decision to transition two routers from my server file to my controller file in order to adhere to the MVC format. However, after making this change, I realized that the logo image is no longer visible on those routers. It seems like al ...

What steps should be taken once the idToken in Firebase has expired?

My code is utilizing the onAuthStateChanged function: this.unregisterAuthObserver = firebase.auth().onAuthStateChanged(user => { if (user) { user.getIdToken(true).then((idToken) => { console.log(user) ... }); } After the idT ...

`What is the best way to employ the Return statement in programming?`

Trying to grasp the concepts of functions and methods has been a challenge for me. I often find myself confused about when, where, and how to use return statements in different situations. To illustrate this confusion, let's take a look at two code sn ...

The OnTextChanged Event of ASP.NET TextBox fails to trigger

I am currently working on implementing a search functionality on the website where a request is sent to the server every time the user enters text, letter by letter. I've attempted to use the OnTextChanged event, but unfortunately, it does not seem to ...

Struggling with css margins and div image constraints, seeking guidance and tips for resolution

Struggling with creating a dynamic gallery that works smoothly in jsfiddle but encounters multiple issues when integrated into WordPress. The main problem is the excessive stretching of margins between image titles and meta-data, leading to misalignment an ...

generate an array composed of promises to be used with Promise.all

Currently, I am working with an array of file paths and my goal is to read all the files inside a Promise.all function, followed by carrying out several tasks. var files = ["./file1.txt", "./file2.txt"] Promise.all(files.forEach(file=>{ /* read file ...

Scrolling with animation

While exploring the Snapwiz website, I came across a captivating scroll effect that I would love to implement on my own site. The background picture changes seamlessly as you scroll, with the front image sliding elegantly into view. A similar type of scro ...

Reverse the order of images in jQuery image slider

Hey there, I have created a simple image slider using jQuery with previous and next buttons. The slider moves automatically and the next button works fine, but I am facing some issues with the previous button. To take a look at the code and test it out you ...