Search code examples
javascriptvue.jsnpmvue-cli-3openlayers-5

why openlayers map not working in vue-cli 3


I have added ol package to my vue-cli project through

npm install ol

but the map doesn't load. there is no error and I just find an empty div in the result source.

here is my code =>

the html part :

<div id="map-container"></div>

the js part :

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

export default {
    name: "page",
    data() {
        return {
            ...
        }
    },
    methods: {

        initMap: function () {
            new Map({
                target: 'map-container',
                view: new View({
                center: [0, 0],
                zoom: 2
            })
        });
    },
    mounted: function () {
            this.initMap();
    },
}

NOTE => some where I found that I have to call init function as :

this.$nextTick(function () {
            initMap();
        })

but it made no difference.

guys, I'm running out of time so pls help me. thanks everybody who wanna help


Solution

  • It looks like you are missing a TileLayer. Something like this:

    new Map({
      target: "map-container",
      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
      })
    });