[GIS] Getting GeoJSON properties to appear in popup on feature click in OpenLayers

geojsonopenlayers

I am using OpenLayers 3.

I have a map with a base layer and a geojson cluster layer. I want to be able to click an individual feature on the map and have the contents of the properties be displayed in a popup. I currently have just the position working in the popup but I would like to get information like the name of the feature and various other things. This is my code that gets me a location popup:

var element = document.getElementById('popup');

var popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false
});
map.addOverlay(popup);

// 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);
coord = ol.proj.transform(coord, 'EPSG:3857', 'EPSG:4326');
$(element).popover({
  'placement': 'top',
  'html': true,
  'content': ('<p>Location:</p>'+coord)
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});

This works fine but I would like to get the other properties. I have tried feature.get('property here') instead of feature.getGeometry(); and geometry.getCoordinates(); but that made it so the popup never appeared and the only thing I was getting in firebug was an error in the ol.js b.slice() is not a function. So basically my question is: Is there a clear cut way to display all GeoJSON properties of a feature in a popup? I got my popup using the null island example here

And here is an example JSON feature:

 {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[0.13138000,49.475577]},"properties":{"name":"227006760","speed":"55","Nav_Status":"5"}}]}

Best Answer

You can get -- feature.get('any') -- any geojson property and show in the popup. Take a look at this demo.

You mixed up some points. So, first, get the coordinate to position the popup:

var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();

Note, there is no coordinate transformation.

Second, prepare the popup content:

var content = '<h3>' + feature.get('property here') + '</h3>';
content += '<h5>' + feature.get('other property') + '</h5>';

And finally, show it. Right?