简体   繁体   中英

My button onClick recenter for OpenLayers doesn't work

I'm building an angular application using openlayers that when I click a button it will recenter my map .I'm trying to re-center my map when I onClick to a button but it doesnt work.

ERROR TypeError: Cannot read property 'setCenter' of undefined.

Can someone tell me what I'm doing wrong. Thanks in advance !

import { Component } from '@angular/core';
import {fromLonLat} from 'ol/proj'
import {view} from 'ol/View';
import * as ol from 'openlayers';

export class AppComponent {
  distance = 60;
  points: Array<{ x: number; y: number; }> = [];
  position : Array<{ x: number; y: number; id: string; radius: number,color:string, place:string}> = 
  [
      {x:11.5820,y:48.1351,id:"munich",radius:20, color:"red", place:"m"},
      {x:13.388866,y:52.517071,id:"berlin", radius:40,color:"blue", place:"b"},
  ];

  coords = {
    berlin: [13.388866, 52.517071]
 };

 onClick (city: string) {
  view.setCenter({
     center: fromLonLat(this.coords[city]),
     duration: 2000
  });
}

  mapOnClick(evt) {
    console.log(evt);
    const map = evt.map;
    // this bit checks if user clicked on a feature
    const p = map.forEachFeatureAtPixel(evt.pixel,
     function(feature, layer) {
      console.log("got feature" + feature.getId());
      return feature;

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

Lets try this once just for suggestion,

import OlView from 'ol/View';

view: OlView;

 ngOnInit() {
    this.view = new OlView({
      center: fromLonLat(this.coords[city]),
      zoom: 3
    });
  }

I hope its solve your problem if you received proper data for this.coords[city] variable. You need to pass data like this, center: fromLonLat([6.661594, 10.32371]) .

For more Reference, Use OpenLayers 4 with Angular 5

You may get some idea from this above url example.

Thanks,

Muthukumar

If you are trying to recenter there must already be a view, but if it was constructed inside the map constructor there won't be a view variable and you will need to reference it using map.getView(). Also setCenter() doesn't do animated recentering. Assuming your map variable is map try:

  map.getView().animate({
     center: fromLonLat(this.coords[city]),
     duration: 2000
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM