0

I'm trying to center the map on the geometries that are on the map. To encompass all but until now I have not succeeded in how ...

It centers further than geometries :(

  if (ol.proj.proj4 && ol.proj.proj4.register) { ol.proj.proj4.register(proj4); }

var features;

$.ajax({
    type: "GET",
    url: "get_geojson.php",
    dataType: 'json',
    async: false,
    success: function (response) {
       features = new ol.format.GeoJSON().readFeatures(response);
    }
});

  features.forEach(function(feature){
    feature.setId(undefined);
    feature.getGeometry().transform('EPSG:31700', 'EPSG:3857');
  });

  var map = new ol.Map({
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM(),
        }),
        new ol.layer.Vector({
            source: new ol.source.Vector({
                features: features
            })
        })
    ],
    target: 'map',
    controls: ol.control.defaults({
            attributionOptions:
                ({
                    collapsible: false
                })
        }).extend([
            new ol.control.OverviewMap(),
            new ol.control.FullScreen(),
            new ol.control.ScaleLine()

        ]),
        interactions: [
            new ol.interaction.DragRotateAndZoom(),
            new ol.interaction.MouseWheelZoom(),
            new ol.interaction.DragPan(),
            new ol.interaction.DoubleClickZoom()
        ],
    view: new ol.View({
        center: ol.proj.transform([698282.236, 377375.758], 'EPSG:31700', 'EPSG:3857'),
        zoom: 14,
    })
  });
1

You would need to build an extent from the geometries and fit the view to that

  var extent = ol.extent.createEmpty();
  features.forEach(function(feature){
    feature.setId(undefined);
    feature.getGeometry().transform('EPSG:31700', 'EPSG:3857');
    ol.extent.extend(extent, feature.getGeometry().getExtent());
  });

  var map = new ol.Map({
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM(),
        }),
        new ol.layer.Vector({
            source: new ol.source.Vector({
                features: features
            })
        })
    ],
    target: 'map',
    controls: ol.control.defaults({
            attributionOptions:
                ({
                    collapsible: false
                })
        }).extend([
            new ol.control.OverviewMap(),
            new ol.control.FullScreen(),
            new ol.control.ScaleLine()

        ]),
        interactions: [
            new ol.interaction.DragRotateAndZoom(),
            new ol.interaction.MouseWheelZoom(),
            new ol.interaction.DragPan(),
            new ol.interaction.DoubleClickZoom()
        ],
    view: new ol.View()
  });
  map.getView().fit(extent);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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