简体   繁体   English

Openlayers3从element获取地图

[英]Openlayers3 get map from element

Is there a way in Openlayers 3 to get the map that is attached to a specific html element? 在Openlayers 3中有没有办法获得附加到特定html元素的地图?

Something like: 就像是:

var map = new ol.Map({
  view: new ol.View({
    center: [0, 0],
    zoom: 1
  }),
  layers: [
    new ol.layer.Tile({
      source: new ol.source.MapQuest({layer: 'osm'})
    })
  ],
  target: 'map'
});

//Later on, in a different file
var myMap = $("#map").ol.Map()

The map object has a reference to the HTML element but the HTML element does not have a reference to the map object. map对象具有对HTML元素的引用,但HTML元素没有对map对象的引用。 The HTML element does not know about the map object at all. HTML元素根本不知道地图对象。

If you use jQuery you could possibly store a reference to the map in the jQuery object using the data method . 如果使用jQuery,则可以使用data方法在jQuery对象中存储对映射的引用。 For example: 例如:

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

And then, to get a reference to the map from the element: 然后,从元素中获取对地图的引用:

var map = $('#map').data('map');

For clarity, here is another example demonstrating erilem's answer with a map var and map div that are not named 'map'. 为清楚起见,这是另一个例子,展示了erilem的答案,其中map var和map div未命名为“map”。

mapElement = '#mapDiv'
mymap = new ol.Map({        
  target: mapDiv,
  view: new ol.View({
     ...
  })
});
$(mapElement).data('map', mymap);

Then you can reference that map with jquery using data with the data method. 然后,您可以使用数据方法使用数据使用jquery引用该映射。 In my case I then wanted to use the ol updateSize() to update mymap. 在我的情况下,我然后想使用ol updateSize()来更新mymap。

thisMap = $(mapElement).data('map')
thisMap.updateSize();

This is useful when I have more than one map on a page. 当我在页面上有多个地图时,这很有用。 Where I use: 我在哪里使用:

mapDiv = id +'-map'      
mapElement = '#' + mapDiv
maps[i] = new ol.Map({        
    target: mapDiv,
    view: new ol.View({
        ...
    })
});
$(mapElement).data('map', maps[i])

And then: 然后:

thisMapId = activeDataset + '-map'
thisMapElement = '#' + thisMapId
thisMap = $(thisMapElement).data('map')
thisMap.updateSize()

Where id = activeDataset 其中id = activeDataset

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM