Search code examples
javascriptautomationopenlayers

Can you create a javascript method that creates an openlayers map object?


I am trying to automate the creation of openlayers map objects, as follows HTML:

<div id="map1"></div>
<div id="map2"></div>

Javascript:

function createMap(mapObject, mapDiv) {
mapObject = new ol.Map({
   layers: new ol.layer.Tile({source: new ol.source.OSM()}),
   target: mapDiv,
   view: new ol.View({center: ol.proj.fromLonLat([32.0, 34.5]), zoom: 8})
})
}
createMap(map1, "map1");
createMap(map2, "map2");

Say I wanted to create some event that overlays a layer on either of the map objects when that events occurs, I could modify the above code as follows: HTML

...
<button id="btn1" type='submit'>Load To Map 1</button>
<button id="btn2" type='submit'>Load To Map 2</button>

JavaScript

...
$('#btn1').on('click', function(e) {
const key = 'some random numbers';
let raster = new TileLayer({
      minZoom: 14, // visible at zoom levels above 14
      source: new TileJSON({
        url: 'https://api.maptiler.com/maps/outdoor/tiles.json?key=' + key,
        tileSize: 512,
      }),
    });
createMap(map1, "map1");
map1.addLayer(raster);
}
$('#btn2').on('click', function(e) {
const key = "some random numbers";
let raster = new TileLayer({
      source: new XYZ({
        attributions: attributions,
        url:
          'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
        maxZoom: 20,
      })
    });
createMap(map2, "map2");
map1.addLayer(raster);
}

The question is, why doesn't this work with an error that map1 or map2 is undefined?


Solution

  • You can't define a variable through a function.

    What you can do, is return the object in the function instead.

    function createMap(mapDiv) {
      return new ol.Map({
        layers: new ol.layer.Tile({source: new ol.source.OSM()}),
        target: mapDiv,
        view: new ol.View({center: ol.proj.fromLonLat([32.0, 34.5]), zoom: 8})
      })
    }
    

    Then define a variable by

    let map1 = createMap("map1");
    

    So, your code will be

    $('#btn1').on('click', function(e) {
      const key = 'some random numbers';
      let raster = new TileLayer({
        minZoom: 14, // visible at zoom levels above 14
        source: new TileJSON({
          url: 'https://api.maptiler.com/maps/outdoor/tiles.json?key=' + key,
          tileSize: 512,
        }),
      });
      let map1 = createMap("map1");
      map1.addLayer(raster);
    }
    
    $('#btn2').on('click', function(e) {
      const key = "some random numbers";
      let raster = new TileLayer({
        source: new XYZ({
          attributions: attributions,
          url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
          maxZoom: 20,
        })
      });
    
      let map2 = createMap("map2")
      map2.addLayer(raster);
    }