openlayersangular6openlayers-5

Setting the map as a variable in angular6/openlayers


I use angular 6 and openlayers 5.1.3. I did npm install ol --save successfully and then in my angular I did

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 works fine, but the problem is that if I do

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

and then

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

I get Cannot read property 'olmap' of null referring to this this.olmap.getView().animate({center: coords, zoom: 10});

Why I cannot refer to the olmap with the this.olmap, since I am defining it along with the other vars in Typescript? I never has this problem again, I always access values like this.x

Why do I get this error? What does it mean?

Please explain so I can understand what is wrong and can continue with my project, without having questions.

Thanks


Solution

  • The problem you are seeing relates to Javascript lexical scoping.

    In your Angular 6 project you can use an ES6 arrow function to access the parent lexical scope, your code should now behave as you are expecting:

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

    Further reading:

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