OpenLayers 4 - fit to extent of selected features
Asked Answered
E

2

6

Me again. So, yesterday I faced a bit of a problem with zooming to selected features and I'm hoping that some of you can push me in right direction.Here it goes...

I'm trying to implement autocomplete/search bar using Materialize Materialize Framework. (Here is fiddle example of simple searchbar)

  $(document).ready(function(){
    $('input.autocomplete').autocomplete({
      data: {
        "Apple": null,
        "Microsoft": null,
        "Google": 'https://placehold.it/250x250'
      },
    });
  });

Now, what I'm trying to do is to call and populate data using geojson features and to implement fit to extent for selected feature. If I'm understanding correctly I need to save extent for selected feature and pass it in with

map.getView().fit(selectedFeature.getSource().getExtent(), animationOptions);

Or Am I doing this completely wrong?

$(document).ready(function() {
function sendItem(val) {
    console.log(val);
}

var animationOptions = {
    duration: 2000,
    easing: ol.easing.easeOut
};

$(function() {
    $.ajax({
        type: 'GET',
        url: 'geojson/jls.geojson',
        dataType: 'json',
        success: function(response) {
            var jls_array = response;
            var features = jls_array.features;
            var jls = {};

            for (var i = 0; i < features.length; i++) {
                var geo = features[i].properties;
                jls[geo['JLS_IME']] = null;
            }
            console.log(jls)
            $('input.autocomplete').autocomplete({
                data: jls,
                limit: 5,
                onAutocomplete: function(txt) {
                    sendItem(txt);
                    map.getView().fit(vectorJLS.getSource().getExtent(), animationOptions);
                }
            });
        }
    });
});
});

And here is example of my geojson object

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name":"EPSG:3765" } },
"features": [
{ "type": "Feature", "properties": { "JLS_MB": "00116", "JLS_IME": "BEDEKOVČINA", "JLS_ST": "OP", "JLS_SJ": "Bedekovčina", "ZU_RB": "02", "ZU_IME": "Krapinsko-zagorska", "ZU_SJ": "Krapina", "pov": 51.42 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 461117.98, 5108379.85 ], [ 461124.53, 5108368.39 ], [ 461132.37, 5108354.26 ]...

UPDATE - SOLUTION

So, as fellow Dube nicely pointed out with logical and practical solution where he's finding feature and zooming selected feature within geojson layer source with simple .find() method.

I only tweaked a bit existing code with added variable before ajax call

var source_layer = vectorJLS.getSource(); // collecting layer source

$(function() {
    $.ajax({
        type: 'GET',
        url: 'geojson/jls.geojson',
        dataType: 'json'.....

onAutocomplete: function(txt) {
  var feature = source_layer.getFeatures().find(function(f) { return f.get('JLS_IME') === txt; });
  if (feature) {
    const extent = feature.getGeometry().getExtent()
    map.getView().fit(extent);
  }
};

Here is layer that I'm trying to iterate and on select to zoom on feature

Eleazar answered 10/4, 2018 at 6:37 Comment(2)
you are using the extent of the source (I assume vectorJLS is a layer), so you'll zoom onto the whole layer, not just a specific feature. What do you want to zoom to? what does not work?Ecotype
@Ecotype True, I'm trying to to iterate trough to zoom on specific feature on select to be fair this is pretty challenging :)Eleazar
E
5

The feature itself does not have an extent, but it's geometry has one:

const extent = feature.getGeometry().getExtent()
map.getView().fit(extent);

However, so far you seem not to have OpenLayers feature objects, just a plain json object, which you got in the ajax response. Let's transform it:

var source = new ol.source.Vector({
features: (new ol.format.GeoJSON({
  featureProjection: "EPSG:3765" // probably not required in your case
})).readFeatures(featureCollection);

You do not need to add the vector to the map to determine the specific feature and it's extent:

onAutocomplete: function(txt) {
  var feature = source.getFeatures().find(function(f) { return f.get('JLS_IME') === txt; });
  if (feature) {
    const extent = feature.getGeometry().getExtent()
    map.getView().fit(extent);
  }
};
Ecotype answered 10/4, 2018 at 20:33 Comment(3)
It works. Thank you :) I only needed to tweak code a bit. I ll update answer. God bless Swiss chocolate :)Eleazar
I have several features and I'd like to display all of those in view, Is it possible to fit view to multiple features?Fernery
I got it I just needed to getExtent() of sourceFernery
S
1

I'm not sure how your map-application should work, but i think you should use the Select-Interaction if you want to handle selected features ('ol/interaction/select') because you can use all the events fired and set a custom style for your selection. The content of the Select Interaction is an ol.Collection which contains your selected features. So beside your Vectorlayer you should also implement an Select-Interaction:

const selectedItems = new ol.interaction.Select({
        layers: [yourbasicvectorlayer],
        style: new ol.style.Style({...})
    });
//Listen if any new items are pushed into the selection
selectedItems.getFeatures().on('add', function(feature) {
    //for one feature:
    map.getView().fit(feature.getGeometry().getExtent(), AnimationOptions);
    //for multiple features --> so everytime a new is added
    //Create an empty extent like:
    let extent = new ol.extent.createEmpty();
    selectedItems.getFeatures().forEach(feature) {
        //add extent of every feature to the extent
        extent = new ol.extent.extend(extent, feature.getGeometry().getExtent(); 
    }
    map.getView().fit(extent, animationOptions);
})
// Dont forget to add the Select Interaction to the map
map.addInteraction(selectedItems).
//you can fill the selection interaction programmatically
selectedItems.getFeatures().push(yourfeature);

Didn't tested the code. With an Select-Interaction its more overhead but better structured. You can also just use the part in the listener for a single-multi feature(s) approach. Let me know if i'm completly misunderstanding :-)

Scarcity answered 10/4, 2018 at 8:34 Comment(1)
Plus 1 for your effort but to be fair I need something slightly different. I need to combine search bar and ajax call with interaction map interaction or to be more precise zoom to extent of selected feature. e.g. when I write "Italy" in search bar i want to automatically zoom to that feature. Once again, thank you for effort but I believe that my search will continue :)Eleazar

© 2022 - 2024 — McMap. All rights reserved.