0

I'm trying to get country string by coordinates, but feature is null.

Why feature is null? how could I fix it?

I tested with onclick event.pixel and it does returns feature but then I use map.getPixelFromCoordinate to get pixel feature becomes null

var vectorLayer = new ol.layer.Vector({
    source: new ol.source.Vector({
        url: 'https://openlayers.org/en/v4.6.5/examples/data/geojson/countries.geojson',
        format: new ol.format.GeoJSON()
    })
});

var map = new ol.Map({
    layers: [ vectorLayer],
    target: 'map',
    view: new ol.View({
        center: [0, 0],
        zoom: 1
    }),
    logo:false
  });

this does not work

map.once('postrender', function() {
    var pixel = map.getPixelFromCoordinate([-0.0508, 51.5160]);

    var feature = map.forEachFeatureAtPixel(pixel, function(feature) { 
        return feature;
    });

    console.log("Country:"+feature.get("name"));
});
Mikebel
  • 51
  • 8

1 Answers1

0

It's because by the time postrender event is called, loading of features is not complete. You can use postcompose event on vectorLayer instead. If the function is going to be more complex I would recommend using ol.source.Vector's loader function.

vectorLayer.on('postcompose', function () {
    var pixel = map.getPixelFromCoordinate(ol.proj.fromLonLat([-0.0508, 51.5160]));
    var feature = map.forEachFeatureAtPixel(pixel, function (feature) {
        return feature;
    });
    console.log("Country:"+feature.get("name"));
});

Also you seem to be passing EPSG:4326 coordinates which needs transformation to EPSG:3857 (which is used by OpenLayers by default).

pavankguduru
  • 315
  • 1
  • 13