0

I would like to zoom in openlayers library to a location eg: Berlin when the user click on the button. can someone tell me how is it possible to be done?

Below are my code:

app.component.html

<button id='berlin' (click)="onClick('berlin')">Zoom to Berlin</button>

app.component.ts

berlin = fromLonLat([13.388866, 52.517071]);

public onClick(city:any) {
   console.log(city);
   view.animate({
      center: city,
      duration: 2000
   });
}
Patryk Brejdak
  • 1,571
  • 14
  • 26
jibu2010
  • 23
  • 7

2 Answers2

1
var bern = ol.proj.transform([7.4458,46.95], 'EPSG:4326', 'EPSG:3857'); 
document.getElementById ("berlin").addEventListener ("click", berlinZoom, false);
 function berlinZoom() {

            var bernview = new ol.View({
                center: bern,
                zoom: 6
            });  
         map.setView(bernview); 
        }
0

You are passing a string, here: 'berlin', to your function onClick, therefore it looks like this:

view.animate({
  center: 'berlin',
  duration: 2000
});

I guess, you would like to jump to [13.388866, 52.517071]. This should do the trick:

coords = {
   berlin: [13.388866, 52.517071],
   // Add other cities
   ...
};

onClick (city: string) {
   view.animate({
      center: fromLonLat(coords[city]),
      duration: 2000
   });
}
pzaenger
  • 11,381
  • 3
  • 45
  • 46
  • i got an error as below: AppComponent.html:46 ERROR TypeError: Cannot read property 'animate' of undefined – jibu2010 Oct 15 '18 at 08:03
  • Looks like your `view` is undefined. Is `view` of type [`ol/view`](https://openlayers.org/en/latest/apidoc/module-ol_View-View.html) and how do you pass it to your component? Even better would be something like `map.getView().animate(...);` – pzaenger Oct 15 '18 at 09:06