poonam patel
poonam patel

Reputation: 145

OpenLayers - On click marker zoom at certain zoom level

I want to create on click event on the marker which zooms at a specific level upon click. current code loads marker and upon click zooms to the maximum zoom level of marker. I want to add a specific zoom level in code so when click event happens on the marker it should set view at that zoom level .i have raster tiles on the map at zoom level 16 and above so, when I click on the marker it should zoom to raster tiles and hide marker from there.

    var marker = new ol.layer.Vector({
      source: new ol.source.Vector({
          format: new ol.format.GeoJSON(),
          url: "data.js"  
      }),
      style: new ol.style.Style({
        image: new ol.style.Icon({
                anchor: [0.5, 0.5],
                anchorXUnits: 'fraction',
                anchorYUnits: 'pixels',
                scale:0.03,
                src: "img.png"
              })
          })  
    });
    map.addLayer(marker);
    map.on("singleclick", (event) => {        
        const feature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
          return feature;
        });
        if (feature instanceof ol.Feature) {
              map.getView().fit(feature.getGeometry());       
         }
      });

Upvotes: 1

Views: 1461

Answers (1)

Mike
Mike

Reputation: 17972

Instead of using fit set the view's center and zoom

map.getView().setCenter(ol.extent.getCenter(feature.getGeometry().getExtent()));
map.getView().setZoom(16);

You can "hide" a feature by giving it a null style

feature.setStyle(null);

Upvotes: 2

Related Questions