Tips for creating a visual map using a URL

Here is a code snippet that I found:

https://openlayers.org/workshop/en/vector/geojson.html

The code requires a URL to a countries.json file, like this:

url: './data/countries.json'

When I run the code, only zoom in and zoom out buttons appear on a dark blue background, but no map is displayed. Could someone please help me locate the countries.json file?

Code:

const map = new Map({
  target: 'map-container',
  layers: [
    new VectorLayer({
      source: new VectorSource({
        format: new GeoJSON(),
        url: './data/countries.json'
      })
    })
  ],
  view: new View({
    projection: 'EPSG:4326',
    center: [13.063561,52.391842],
    zoom: 2
  })
});

Attempts:

I also modified the code like this:

const vectorLayer = new VectorLayer({
  source: new VectorSource({
    url: './data/countries.geojson',
    format: new GeoJSON(),
    defaultProjection :'EPSG:4326', projection: 'EPSG:3857'
  })
})

const map = new Map({
  target: 'map-container',
  layers: [vectorLayer],
  view: new View({
    projection: 'EPSG:4326',
    center: [0,0],
    zoom: 2
  })
});
sync(map)

I also tried variations like:

countries.json
         .geojson 
         .geo.json
         

but unfortunately, nothing seems to work and the map is not displayed.

Answer №1

Following the steps below made this code work for me:

I am currently using Ubuntu and I carefully followed the instructions provided on .

I obtained the necessary files by downloading the folder from https://github.com/openlayers/workshop/releases/download/v6.0.0-beta.en.4/openlayers-workshop-en.zip and extracting its contents.

Once extracted, I navigated to the folder and executed 'npm install'.

I then made modifications to the index.html file:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>OpenLayers</title>
    <style>
      html, body, #map-container {
        margin: 0;
        height: 100%;
        width: 100%;
        font-family: sans-serif;
        background-color: #04041b;
      }
    </style>
  </head>
  <body>
    <div id="map-container"></div>
  </body>
</html>

main.js

import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';

new Map({
  target: 'map-container',
  layers: [
    new VectorLayer({
      source: new VectorSource({
        format: new GeoJSON(),
        url: './data/countries.json'
      })
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

You can easily get it up and running by executing 'npm start' from the root directory.

For a more comprehensive guide, I ran 'npm install ol-hashed' at the root directory.

I then updated the code in main.js

import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';

import sync from 'ol-hashed';


const map = new Map({
  target: 'map-container',
  layers: [
    new VectorLayer({
      source: new VectorSource({
        format: new GeoJSON(),
        url: './data/countries.json'
      })
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});
sync(map);

Running 'npm start' will now display the map accordingly.

To use a URL for the geojson data, ensure you have the direct link to the raw data.

In my case, I used https://raw.githubusercontent.com/openlayers/workshop/master/src/en/data/countries.json

and updated my code in main.js to:

import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';

import sync from 'ol-hashed';


const map = new Map({
  target: 'map-container',
  layers: [
    new VectorLayer({
      source: new VectorSource({
        format: new GeoJSON(),
        url: 'https://raw.githubusercontent.com/openlayers/workshop/master/src/en/data/countries.json'
      })
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});
sync(map);

If the map fails to display, check the 'url' argument in main.js. You can inspect the browser console for any error messages.

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

Transfer text from one form to a text field on a different website

I've created a form that allows users to input numbers in a field and then directs the page to a specific URL. Here's the code snippet: <html> <head> <meta charset="utf-8"> <title>Tracking</title> </head& ...

Creating input fields in Vue 3: Best practices

I am looking to create an input field that automatically removes entered characters if they do not match a specific pattern. Here is the template: <input type="text" :value="val" @input="input" /> And here is the ...

Using an id as the attribute value for a React ref

I have a question about referencing DOM nodes in a component. Currently, I am able to get the nodes and children using the following code: export class AutoScrollTarget extends React.Component { constructor(props) { super(props); this ...

Create a search feature based on names utilizing Node Express in conjunction with SQL database

After deciding to create an API with a search feature using SQL queries in node express, this is how I structured my code: app.get('/search/:query', (req, res) => { pool.getConnection((err, connection) => { if(err) throw err ...

Identifying the relationship between child and parent components in Vue.js

I am new to Vue.js and I am practicing some simple exercises on communication between Vue components. However, I am struggling with understanding who is a child component and who is a parent component. For example, consider the following code snippet: HTM ...

It is impossible to remove or trim line endings with regex in Node.JS

I'm having trouble with using process and util in a NodeJS script. Even after trimming, line breaks persist in the resulting string (as seen in the console.log() output below). I'm unsure why this is happening. var util = require("util"); proces ...

Choosing the right jQuery selector to target a section that contains div elements

Whenever the h2 element within a section is clicked, I want all the fields in that section to be displayed. For example, if the user clicks on 'Contact Information', the three form inputs (fields) below the Contact Information heading should appe ...

The condition is not established by the Firestore where clause

I'm working on a function that includes two where clauses. My objective is to verify the existence of a document based on the presence of two specific IDs. However, when I execute the function, it retrieves all the records in the collection instead. C ...

Why do I need to double-click? (JavaScript onclick event handler)

As a beginner in JavaScript and web development, I encountered a peculiar issue for the first time. In a simple example, I have two divs - left and right. The left div contains five images, while the right div is empty. There are two buttons - copy and del ...

How can I modify the base color of a cone in Three.js?

My cone in the jsfiddle link is currently all blue, but I want to change the color of the square base to red. To do that, I need to alter the color of the two faces that make up the square base. How can this be achieved? View my cone on JsFiddle: http://j ...

What is the best way to call another "put" action method within the same controller file?

My project revolves around the interaction of two models - User and Request. A User can create a food delivery Request, attaching tokens as rewards. Another User can then help deliver the request and claim the tokens. Within the same controller.js file, I ...

Error message: Can't find Highcharts in (React JS) environment

I have been encountering an error ReferenceError: Highcharts is not defined, and I've been struggling with this issue for a few days now. Can you provide assistance? In my project, I have Dashboard and Chart files where I import the Chart components ...

What is the best way to merge an array of objects into a single object?

Is there a way to dynamically convert object1 into object2, considering that the keys like 'apple' and 'water' inside the objects are not static? const object1 = { apple:[ {a:''}, {b:'&apos ...

Adding a Timepicker to a Datepicker on a jsp webpage with javascript

I am working on a JSP page that includes a date picker. I want to enhance this datepicker by adding a start time and end time within the calendar itself. How can I achieve this? Additionally, I need to implement validation ensuring that the start time is a ...

Obtain a collection of information from a web API by utilizing jQuery

Click on the following link to access live data from a web API: This is my first attempt at retrieving data from an API, so I may have missed some settings. To test the connection with the API, I included the following code in the HTML page: <div id= ...

The functionality of Bootstrap's JavaScript is dependent on the presence of jQuery - Reactjs framework

When attempting to combine bootstrap with reactjs, I encountered an issue with importing Bootstrap.js It seems that Bootstrap's JavaScript requires jQuery Below are some of the import statements I have tried: import $ from 'jquery'; imp ...

Tips for integrating the connect-orientdb module with the Express framework

My objective is to establish a connection between my server code, written in nodejs using the expressjs framework, and my database which is built on orientdb. Initially, I aimed to store sessions in the database but encountered difficulties when trying to ...

Function not currently in operation

There seems to be an issue with the script not running or returning any answers. The console is blank. I am attempting to retrieve an answer from the Yandex Translate site (https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/) Code: http: ...

Why is it that only one of these functions can be operational at any given moment?

Even without the if statements, only one of the following will work at a time. To make the first one work, I have to comment out the second. <? if(isset($_POST['region'])){ echo "<script> showRecords('".$_POST['region']." ...

Creating Location-Specific Customer Data using AngularJS similar to Google Analytics

Looking to create a user registration map similar to Google Analytics without actually using Google Analytics. Can anyone provide assistance with this task? I am utilizing MVC, C#, Sql Server-2014, AngularJS, and jQuery for this project. Despite my efforts ...