0

I am using osm and openlayers to display two maps.

I created a custom control:

function getDrawPolygonControl() {
  const button = document.createElement('button');
  button.innerHTML = '<i class="fas fa-pen"></i>';

  button.addEventListener('click', e => {
    // how to get the correct map instance here????
    console.log(e);
  });

  const element = document.createElement('div');
  element.className = 'ol-draw ol-control';
  element.appendChild(button);

  return new ol.control.Control({element: element});
}

In my initMap() function i add it to the respective map using:

const controls = [new ol.control.FullScreen(), new ol.control.Attribution(), getDrawPolygonControl()];

  const map = new ol.Map({
    view: view,
    target: target,
    controls: controls,
  });

The question now is how to i get the correct map instance in my onClick listener?

TheDoctor
  • 2,362
  • 4
  • 22
  • 39

1 Answers1

1

Try calling the control constructor earlier so you can reference it:

function getDrawPolygonControl() {
  const button = document.createElement('button');
  button.innerHTML = '<i class="fas fa-pen"></i>';

  const element = document.createElement('div');
  element.className = 'ol-draw ol-control';
  element.appendChild(button);

  const control = new ol.control.Control({element: element});

  button.addEventListener('click', e => {
    console.log(control.getMap());
  });

  return control;
}
Mike
  • 16,042
  • 2
  • 14
  • 30