0

I am trying to display a map of the USA in OpenLayers, and am trying to fit it to a layer. I tried map.getView().fit(Usa.getSource().getExtent()); but that didn't do anything. I thought that maybe the extent was the same as the map for some reason, but no other lines of code would run after that line of code. I am not experienced with openlayers, and javascript is not my first language, so I assume the problem is something silly that I have overlooked. Here is all of the code:

const Usa = new VectorLayer({
  source: new VectorSource({
    url: '/data/Usa.geojson',
    format: new GeoJSON(),

  }),
  
});
const map = new Map ({
  view: new View({
    
    center: [0,0],
    zoom: 1,
    projection: 'EPSG:3857',
  }),
  target: 'map-container',
  
});
map.addLayer(Usa);
map.getView().fit(Usa.getSource().getExtent());
3
  • You need to wait until the source has loaded Usa.getSource().on('featuresloadend', () => { map.getView().fit(Usa.getSource().getExtent()); });
    – Mike
    Commented Jun 12, 2023 at 20:22
  • That worked perfectly thank you! I'm going to answer and reference to your comment.
    – teop
    Commented Jun 12, 2023 at 20:32
  • Also, is there any mention of why this is necessary on the API docs?
    – teop
    Commented Jun 12, 2023 at 20:37

1 Answer 1

0

As @Mike commented: "You need to wait until the source has loaded Usa.getSource().on('featuresloadend', () => { map.getView().fit(Usa.getSource().getExtent()); });".

Your Answer

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

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