2

I'm trying to use some OpenLayers libraries in my code, and called him in JavaScript like this:

  import Map from 'ol/Map.js';
  import Overlay from 'ol/Overlay.js';
  import View from 'ol/View.js';
  import {toStringHDMS} from 'ol/coordinate.js';
  import TileLayer from 'ol/layer/Tile.js';
  import {fromLonLat, toLonLat} from 'ol/proj.js';
  import OSM from 'ol/source/OSM.js';

But I'm receiving the following error:

  error unexpected identifier
0

2 Answers 2

5

This form is inteneded for development environment (like node.js and npm), where you can run it uncompiled and then has to compiled to be run on the client side.

If you don't have required development environment (like me), you first need full build of the OpenLayers library (ol.js, see https://openlayers.org/download/). Then you have to learn how to reference objects/methods that you see in examples intended for development environment. Once you learn it, it's quite simple.

For example:

  • instead of New Map you use New ol.Map
  • instead of New View you use New ol.View
  • instead of New OSM you use New ol.source.OSM
  • instead of fromLonLat you use ol.proj.fromLonLat

Compare this with the import statements and you'll see the logic.

0
3

OpenLayers is intended to be used as npm package (https://npmjs.com/package/ol) inside a node/npm based environment. The code you pasted in the question cannot run directly in the browser. It needs to be bundled, using a tool like Webpack or Parcel.

The OpenLayers website provides a good tutorial on how to do this: https://openlayers.org/en/latest/doc/tutorials/bundle.html.

The confusion probably comes from the examples on the current website, which make the code look as if they can run directly in the browser. This has been fixed with https://github.com/openlayers/openlayers/pull/9103, and the website will be updated with the next release, which is scheduled for later this month.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.