将地图设置为 angular6/openlayers 中的变量

Setting the map as a variable in angular6/openlayers

我使用 angular 6 和 openlayers 5.1.3。我成功地 npm install ol --save 然后在我的 angular 我做到了

import OlMap from 'ol/map';
import OlXYZ from 'ol/source/xyz';
import OlTileLayer from 'ol/layer/tile';
import OlView from 'ol/View';
import * as OlProj from 'ol/proj';
import 'ol/ol.css';

export class myComponent {

 olmap: OlMap;
 source: OlXYZ;
 layer: OlTileLayer;
 view: OlView;
  //other, non-ol stuff
   loading: boolean = false;
   myname: String;

  ngOnInit() {

    this.source = new OlXYZ({
      url:'http://tile.stamen.com/terrain/{z}/{x}/{y}.jpg'
    });

    this.layer = new OlTileLayer({
      source: this.source
    });

    this.view = new OlView({
      center: OlProj.fromLonLat([6.661594, 50.433237]),
      zoom: 3,
    });

    const olmap = new OlMap({
      target: 'map',
      layers: [this.layer],
      view: this.view
    });


    navigator.geolocation.getCurrentPosition(function(pos) {
      const coords = OlProj.fromLonLat([pos.coords.longitude, pos.coords.latitude]);
      olmap.getView().animate({center: coords, zoom: 10});
    });

  }//ngOnInit

这很好用,但问题是如果我这样做

    this.olmap = new OlMap({
      target: 'map',
      layers: [this.layer],
      view: this.view
    });

然后

    navigator.geolocation.getCurrentPosition(function(pos) {
      const coords = OlProj.fromLonLat([pos.coords.longitude, pos.coords.latitude]);
      this.olmap.getView().animate({center: coords, zoom: 10});
    });

我得到 Cannot read 属性 'olmap' of null refering to this this.olmap.getView().animate({center: coords, zoom: 10});

为什么我不能用 this.olmap 引用 olmap,因为我在 Typescript 中将它与其他变量一起定义?我再也没有遇到过这个问题,我总是访问 this.x

这样的值

为什么会出现此错误?这是什么意思?

请解释一下,这样我才能明白哪里出了问题,并且可以继续我的项目,而不会有任何问题。

谢谢

您看到的问题与 Javascript 词法作用域有关。

在您的 Angular 6 项目中,您可以使用 ES6 箭头函数访问父词法作用域,您的代码现在应该按预期运行:

navigator.geolocation.getCurrentPosition((pos) => {
  const coords = OlProj.fromLonLat([pos.coords.longitude, pos.coords.latitude]);
  this.olmap.getView().animate({center: coords, zoom: 10});
});

进一步阅读:

All You Need to Not Know About ES2015 Arrow Functions and “this”
You Don't Know JS: Scope & Closures - Appendix C: Lexical-this