3

I've problems with a selection of a feature from VectorTile. I've no problem with selection using Vector:

  var vectortile_layer = new ol.layer.Vector({
    source: new ol.source.Vector({
        url: 'https://ahocevar.com/geoserver/ne/ows?service=WFS&version=1.0.0' +
          '&request=GetFeature&typeName=ne%3Ane_10m_admin_0_countries&outputFormat=application%2Fjson',
        format: new ol.format.GeoJSON(),
    }),
  });
  map.addLayer(vectortile_layer);

  var highlightStyle = new ol.style.Style({
    fill: new ol.style.Fill({
      color: 'rgba(255,0,255,1.0)'
    }),
    stroke: new ol.style.Stroke({
      color: 'rgba(0, 0, 0, 1.0)',
      width: 2
    })
  });

  var selected = null;

  map.on('singleclick', function(e) {
    if (selected !== null) {
      selected.setStyle(undefined);
      selected = null;
    }

    map.forEachFeatureAtPixel(e.pixel, function(f) {
      selected = f;
      f.setStyle(highlightStyle);
      return true;
    });

  });

But when I try to use a VectorTile with the code below:

  var vectortile_layer = new ol.layer.VectorTile({
    source: new ol.source.VectorTile({
      format: new ol.format.MVT(),
      url: 'https://ahocevar.com/geoserver/gwc/service/tms/1.0.0/' +
            'ne:ne_10m_admin_0_countries@EPSG%3A900913@pbf/{z}/{x}/{-y}.pbf'
    }),
  });
  map.addLayer(vectortile_layer);

  var highlightStyle = new ol.style.Style({
    fill: new ol.style.Fill({
      color: 'rgba(255,0,255,1.0)'
    }),
    stroke: new ol.style.Stroke({
      color: 'rgba(0, 0, 0, 1.0)',
      width: 2
    })
  });

  var selected = null;

  map.on('singleclick', function(e) {
    if (selected !== null) {
      selected.setStyle(undefined);
      selected = null;
    }

    map.forEachFeatureAtPixel(e.pixel, function(f) {
      selected = f;
      f.setStyle(highlightStyle);
      return true;
    });

  });

On click I see this error:

Uncaught TypeError: f.setStyle is not a function

I'm using OpenLayers 6.3.1

2

1 Answer 1

5

For that code to work you would need to use new ol.format.MVT({featureClass: ol.Feature}), (see https://openlayers.org/en/latest/apidoc/module-ol_format_MVT-MVT.html) as the default RenderFeature does not have a setStyle method. Note that if a polygon is split between tiles you will only select one part of it, and only at one zoom level. This example may be a better method https://openlayers.org/en/latest/examples/vector-tile-selection.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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