1

I'm attempting to copy this small tutorial to learn Openlayers, but keep running into issues, even when I copy & paste the code directly.

The first issue I came across was with index.html. The browser returned "Uncaught SyntaxError: Cannot use import statement outside a module." So, I added "type='module'" to index.html, which solved that issue.

However, I then got an error stating "Uncaught TypeError: Failed to resolve module specifier 'ol/ol.css'. Relative references must start with either "/'...". I unpacked the OpenLayers files in ./ol, so I simply added that path to the imports, so they looked like import './ol/ol.css', and import './ol/ol/Map'.

Now, I'm getting errors stating "GET http://{myserverip}/Map/ol/ol/Map net::ERR_ABORTED 404 (Not Found)"

How does one correctly import a javascript module when the javascript is being run from an html file? Am I going about this completely the wrong way?

The javascript imports:

import './ol/ol.css';
import Map from './ol/ol/Map';
import OSM from './ol/ol/source/OSM';
import TileLayer from './ol/ol/layer/Tile';
import TileWMS from './ol/ol/source/TileWMS';
import View from './ol/ol/View';

The index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Tiled WMS</title>
    <!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
    <script src="https://unpkg.com/elm-pep"></script>
    <style>
      .map {
        width: 100%;
        height:400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script type="module" src="main.js"></script>
  </body>
</html>

It should be noted that the ol directory only contains ol.css, ol.css.map, ol.js, and ol.js.map. Can JavaScript import TileLayer from ol/layer/Tile like that (is ol the ol.js file?).

Ross Wardrup
  • 311
  • 1
  • 9
  • 26
  • Are you using some build system? From the example link, they have a package.json that will bundle the javascript. – Mellet Feb 13 '21 at 16:12
  • I'm not. I just downloaded the files from their website. – Ross Wardrup Feb 13 '21 at 16:14
  • 1
    Probably related to [this](https://stackoverflow.com/questions/33516906/which-browsers-support-import-and-export-syntax-for-ecmascript-6). You probably need some bundler to resolve your imports. [Try these steps.](https://openlayers.org/en/latest/doc/tutorials/bundle.html) – Mellet Feb 13 '21 at 16:18
  • 1
    That was it! Thanks! I'm not used to this kind of development so I was going about it all wrong. – Ross Wardrup Feb 13 '21 at 17:01

1 Answers1

2

You are using the module system.That will not work on browser.

I think you are trying to using ES5 (vanilla) javascript. For that use this example. i think it will help you. https://openlayers.org/en/v4.6.5/examples/wms-tiled.html?q=wms

And if you are using module you should use node package manager with bundeling library like webpack.

suman11
  • 41
  • 1
  • 1
  • 3