Svinjica
Svinjica

Reputation: 2519

Is it possible to add OpenLayers library to vue-cli 3

I'm trying to implement Openlayers with vue-cli-3 but it seems that somehow I can't do it right, I'm missing something.

First, I installed vue cli

npm install @vue/cli -g

Then I added additional dependencies or to be more precise OpenLayers library.

npm install ol.

But I'm somehow failing in adding/registering dependencies in registering ol globally (in main.js file)

In my App.vue file when I import files like this it doesn't work. I'm getting this two errors

[Vue warn]: Error in nextTick: "ReferenceError: ol is not defined"

ReferenceError: ol is not defined

import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

export default {

  data() {
    return {
      testing: 'SomeTests',
    }
  },
  mounted() {
    this.$nextTick(function () {
      initMap();
    })
  }
}
function initMap() {
  var myMap = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    target: 'map',
    view: new ol.View({
      center: [0, 0],
      zoom: 2,
    })
  })
};

But when I include script and link tag in my index.html then code above works normally.

<head>
  <link rel="stylesheet" href="https://openlayers.org/en/v5.2.0/css/ol.css" type="text/css">
  <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.2.0/build/ol.js"></script>
  <title>ol-basic</title>
</head>

My question is this. Is it possible to just import elements as it is recommended on ol page with using modules and is it possible to somehow register ol package globally in my main.js file

Upvotes: 0

Views: 2024

Answers (2)

Svinjica
Svinjica

Reputation: 2519

Ok, after additional consultation I've finally figure it out. Here it is working example, hope it helps someone.

// Import everything from ol
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';

function initMap() {
  new Map({
    target: 'map',
    layers: [
      new TileLayer({
        source: new XYZ({
          url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
        })
      })
    ],
    view: new View({
      center: [0, 0],
      zoom: 2
    })
  }

Upvotes: 1

Abid Hasan
Abid Hasan

Reputation: 658

You're never importing ol, which is it is undefined, thereby giving you those errors. Try the following:

// Import everything from ol
import * as ol from 'ol';

// The OSM and TileLayer API is taken from the OpenLayers API.
function initMap() {
  var myMap = new ol.Map({
    layers: [
      new TileLayer({
        source: new OSM()
      })
    ],
    target: 'map',
    view: new ol.View({
      center: [0, 0],
      zoom: 2,
    })
  })
}

I tried it in a quick Vue project, and the function runs without any reference errors

Upvotes: 0

Related Questions