1

How can I get hold of a OpenLayers3 map object associated with a specific id or class (unique)?

I searched and found this thread, which says something like:

var map = $('.my_map_class').data('openlayers'); //assuming there is just one map on the page

But I got an typeerror saying that map is not defined. I have tried replacing $ with jQuery, and it didn't work either.

Any pointers?

6

Your code snippet would work if a reference to the map object was added to the DOM element using jQuery's data function. With something like this:

$('.my_map_class').data('openlayers', mapObject);

But OpenLayers does not do that for you. (OpenLayers is not even based on jQuery.)

So if you want to get a reference to the map object from the DOM element using jQuery you have to add that reference yourself, using data as done above.

This is what I'd do:

var map = new ol.Map({
  target: 'map'
  // ...
});
$('#map').data('map', map);

With that you can get a reference to the map using:

var map = $('#map').data('map');
|improve this answer|||||
  • For use without jQuery: document.getElementById("map").data = map; and var map = document.getElementById("map").data; – bennos Sep 26 '18 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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