Fabian
Fabian

Reputation: 626

Openlayers 3: Getting data from multiple features

I took the example from the docs and added another feature. On clicking the feature data will be displayed in a popup. I add another feature with different data. If I click the features in series it'll show the data from the first feature I clicked. If I click a feature, click somewhere else and then the other feature: It works like expected.

I've created a jsfiddle showing this problem. (In my firefox the map will only show if I click on the 'shield' icon in the top-left corner of the address bar and select 'Disable Protection on This Page'. See this question)

Seems like the correct feature is not taken using this example code:

// display popup on click
map.on('click', function(evt) {
  var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature, layer) {
        return feature;
      });
  if (feature) {
    var geometry = feature.getGeometry();
    var coord = geometry.getCoordinates();
    popup.setPosition(coord);
    $(element).popover({
      'placement': 'top',
      'html': true,
      'content': feature.get('name')
    });
    $(element).popover('show');
  } else {
    $(element).popover('destroy');
  }
});

My goal is to click on the features directly one by one and get the correct data displayed.

EDIT: Seems like it's not a problem of OpenLayers but of the popover. When I insert:

console.log(feature.get('name'));

It'll come up with the correct data.

Upvotes: 0

Views: 629

Answers (1)

pavlos
pavlos

Reputation: 3081

You add two points next to each other. So close to each other so you can not disnguish them visually. Change your features declaration to this:

var iconFeature = new ol.Feature({
  geometry: new ol.geom.Point([0, 0]),
  name: 'Null Island',
  population: 4000,
  rainfall: 500
});

var iconFeature2 = new ol.Feature({
  geometry: new ol.geom.Point([100000, 100000]),//here is the change
  name: 'Null Null Island',
  population: 200,
  rainfall: 100
});

Also note that the default projection of your map is EPSG:3857. The coordinates you are trying to pass seems to be on 4326.

You also declare iconStyle twice which doesnt make any difference, just for the sake of correctness

UPDATE

Your main problem comes from bootsrap popover. To overcome the issue you need to do a bit of dirty job and update the content on each click dinamically. Use this piece of code to achive it

  $(element).data("bs.popover").options.content= feature.get('name');
  $(element).popover("show");

and a fiddle here

Upvotes: 1

Related Questions