25

On the page https://openlayers.org/en/latest/examples/image-vector-layer.html I copied the HTML code from under the map to /tmp/a.html and run firefox /tmp/a.html.

At first two problems appeared easy to fix:

  1. SyntaxError: import declarations may only appear at top level of a module
  2. The character encoding of the HTML document was not declared. The document...

To fix it:

  1. replace <script> by <script type="module">
  2. add <meta charset="UTF-8"> into <head></head>

But what to do with the third error?

TypeError: Error resolving module specifier: ol/Map.js

I have Firefox 60.0.1.

So, are the HTML codes in the examples meant to be used as I did, or did I misunderstand something?

And what do I need in my code to import Map from ol/Map.js?

(I tried to reformulate the question, but if I still deserve a negative ranking, please explain why. Thanks)

xhancar
  • 687
  • 1
  • 6
  • 14
  • ive got the same error trying to help you, this page may not be changed since the update, normally the examples work very well with copy paste – nalm Jun 29 '18 at 11:45
  • I am also trying to use ol es6 modules directly in the browser. I only have a partial answer. To `import Map from ol/Map.js` use a relative or fully qualified path to your ol modules. e.g. `import Map from './node_modules/ol/Map.js';` After doing that I had to edit several ol modes and provide a relative path to node_modules/rbush/rbush.js. Unfortunately I'm still getting errors related to importing rbush. – Richard Greenwood Jul 06 '18 at 15:51

4 Answers4

15

It's because there are some changes due to latest release of OpenLayers (V5.0). Now samples are based on ES6 modules whereas there was before another way of doing

You can compare the "simple" v4.6.5 sample with "simple" master sample

Using <script type="module"> is not enough as it does not solve dependencies when doing import Map from ol/Map.js

There are at least 3 ways of doing:

  1. The usual way to create Openlayers sample using version 5.0.0 is using à bundler like Webpack or Parcel. There is a tutorial for this.

  2. I've also investigated JSPM with this sample

  3. You can always use the old way of doing, like in version 4.6.5 using this other official tutorial without using import.

For solution 1, you can use codesandbox.io to avoid setting a local parcel/webpack environment like illustrated with this tweet.

I know there is a work on progress to refactor the code for samples and I also submitted some suggestions for codesandbox.io e.g https://github.com/openlayers/openlayers/issues/8324

Thomas Gratier
  • 2,311
  • 1
  • 14
  • 15
  • I have a similar issue in that I have an OpenLayers4 based program with a class that extends ol.Tile. With OpenLayers6, ol.Tile doesn't exist in the ol object. Any suggestions on how to deal with that? – A. Mort Oct 02 '20 at 02:59
11

had the same problem. openlayers is outstanding, v5 examples are not :(

e.g.https://openlayers.org/en/latest/examples/animation.html

my fix for v5(.3.0) examples:

    <!-- ADD build-REFERENCE for v5(.3.0) // github.com/openlayers/openlayers/ -->
    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>

    <script>
    // CONVERT imports to var
    var Map                 = ol.Map;        //~ import Map from 'ol/Map.js';
    var View                = ol.View;       //~ import View from 'ol/View.js';
    var {easeIn, easeOut}   = ol.easing;     //~ import {easeIn, easeOut} from 'ol/easing.js';
    var TileLayer           = ol.layer.Tile; //~ import TileLayer from 'ol/layer/Tile.js';
    var {fromLonLat}        = ol.proj;       //~ import {fromLonLat} from 'ol/proj.js';
    var OSM                 = ol.source.OSM; //~ import OSM from 'ol/source/OSM.js';        
    // ...

process: use "copy" on example page, "paste" to new html file. modify like above. run in firefox.

lou
  • 131
  • 1
  • 3
  • thanks a lot, see https://stackoverflow.com/a/56549364/903783 too for some more cases like import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js' and how to convert those too (maybe there's a better way, improvised a bit there) – George Birbilis Jun 11 '19 at 18:00
4

based on lou's answer, here's a fix I just did for the Marker animation example:

<head>
<meta charset="UTF-8">
<title>Marker Animation</title>
<link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css">

<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>

<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
</head>

<body>
<div id="map" class="map"></div>

<label for="speed">
  speed:&nbsp;
  <input id="speed" type="range" min="10" max="999" step="10" value="60">
</label>

<button id="start-animation">Start Animation</button>

<script>
  var Feature = ol.Feature; //import Feature from 'ol/Feature.js';
  //var Map = ol.Map; //import Map from 'ol/Map.js'; //commented-out, use ol.Map in code instead of Map, internal JS Map object causes conflicts in newer browsers
  var View = ol.View; //import View from 'ol/View.js';
  var Polyline = ol.format.Polyline; //import Polyline from 'ol/format/Polyline.js';
  var Point = ol.geom.Point; //import Point from 'ol/geom/Point.js';
  var {Tile, Vector} = ol.layer; //import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';
  var TileLayer = Tile;
  var VectorLayer = Vector;

  //var BingMaps = ol.source.BingMaps; //import BingMaps from 'ol/source/BingMaps.js';

  var VectorSource = ol.source.Vector; //import VectorSource from 'ol/source/Vector.js';
  var {Circle, Fill, Icon, Stroke, Style} = ol.style; //import {Circle as CircleStyle, Fill, Icon, Stroke, Style} from 'ol/style.js';
  var CircleStyle = Circle;

  // This long string is placed here due to jsFiddle limitations.
  // It is usually loaded with AJAX.
  var polyline = [ ...

and to use an ESRI sattelite map or OpenStreetMap (plain) map instead of Bing Maps one (which requires a key), do this extra edit to the Marker animation example:

  var map = new ol.Map({ //don't do new Map(...) here, uses some internal JS Map object in newer browsers
    target: document.getElementById('map'),
    loadTilesWhileAnimating: true,
    view: new View({
      center: center,
      zoom: 10,
      minZoom: 2,
      maxZoom: 19
    }),
    layers: [
      new TileLayer({
        source:
            //new ol.source.OSM()
        
            new ol.source.XYZ({
              attributions: ['Powered by Esri',
                             'Source: Esri, DigitalGlobe, GeoEye, Earthstar Geographics, CNES/Airbus DS, USDA, USGS, AeroGRID, IGN, and the GIS User Community'],
              attributionsCollapsible: false,
              url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
              maxZoom: 23
            })

            /*
            new BingMaps({
              imagerySet: 'AerialWithLabels',
              key: 'Your Bing Maps Key from http://www.bingmapsportal.com/ here'
            })
            */
      }),
      vectorLayer
    ]
  });
George Birbilis
  • 2,782
  • 2
  • 33
  • 35
  • vectorLayer - how did you create (new) this object? – OhadR Jun 10 '20 at 18:38
  • 1
    var vectorLayer = new VectorLayer({ source: new VectorSource({ features: [routeFeature, geoMarker, startMarker, endMarker] }), style: function(feature) { /*hide geoMarker if animation is active*/ if (animating && feature.get('type') === 'geoMarker') { return null; } return styles[feature.get('type')]; } }); – George Birbilis Jun 15 '20 at 02:03
  • 1
    Beware of the "new Map" I had used there, doesn't seem to work in latest browsers where there's a built-in Map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) object. You need to do map = new ol.Map instead and remove the var Map = ol.Map at the start (will update the sample) – George Birbilis Jan 12 '21 at 09:55
  • 1
    Thanks again for hinting about the map object. – QMaster Jan 12 '21 at 15:53
1
The example doesn't work because of you maybe just copy past data from page and not look to DOC menu item
https://openlayers.org/en/latest/doc/tutorials/bundle.html
So step by step:
1. npm init (here u set your index.js as an entry point)
2. npm install ol (it adds OpenLayer to your application)
3. npm install --save-dev parcel-bundler
4. npm start (it run a web server on localhost:1234 and you will see your example working fine
If needed, then
5. npm build (it create /dist folder which you needed a copy to your web server, inside it will be converted js file.
Alex Z
  • 113
  • 6