Search code examples
angularleafletngoninit

Unable to change variable value inside ngOnInit()


I have a simple form with 2 text inputs and a leaflet map, once the user clicks on the map, I get the longitude and latitude of the location.

I'm setting the map in the ngOnInit() funuction, and I have a global variable for the latitude that I want to set once the user clicks. Then in the form submission when I try to console log this.latitude it always says undefined or 0 in case I initialized it to 0.

Here's my component:

import { Component, OnInit } from '@angular/core';
import { RestService } from '../providers/rest.service';
import { SnotifyService } from '../../../node_modules/ng-snotify';
import { NgForm } from '../../../node_modules/@angular/forms';
import { Bank } from '../models/bank';

declare let L;

@Component({
  selector: 'app-add-bank',
  templateUrl: './add-bank.component.html',
  styleUrls: ['./add-bank.component.css']
})
export class AddBankComponent implements OnInit {
  bank:Bank;
  map:any;
  latitude:Number;
  longitude:any;

  constructor(private restService :RestService,private snotifyService: SnotifyService) { 
    this.latitude = 0;
    if(! this.bank){  
      this.bank={

        name:"",
        adress:"",   
        location:{
          coordinates:[0,0]
        }

      };
    }
  }

  ngOnInit() {
    this.addMap();  
  }

  addMap(){
    const map = L.map('map').setView([36.798854, 10.152786], 8);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    var Marker;
    map.on('click', function addMarker(e){

      let latlng = map.mouseEventToLatLng(e.originalEvent);

      console.log(latlng.lat + ', ' + latlng.lng);
        this.latitude = latlng.lat
        console.log("addmap",this.latitude)
      //remove previous markers
      if (Marker) {
        map.removeLayer(Marker);
      }
      // Add marker to map at click location; add popup window

      Marker = new L.marker(e.latlng, {
        draggable: true,
        icon: L.icon({
          iconSize: [ 25, 41 ],
          iconAnchor: [ 13, 41 ],
          iconUrl: 'assets/leaflet/images/marker-icon.png',
          shadowUrl: 'assets/leaflet/images/marker-shadow.png'
        }),
      }).addTo(map);
    });

  }

    testForm(form :NgForm){
        console.log('data : ', form.value )
        console.log("ngform",this.latitude)

    }
}

Short version: How can I set a variable value inside ngOnInit() then retrieve that value in the other functions in the same component? What am I missing? Any help would be appreciated. Thank you


Solution

  • For me your are facing a "scope" problem.

    map.on('click', function addMarker(e){
    

    here you declare a function, in the function scope the "this" keyword will be the function and not your component. You should replace this code by

    map.on('click', addMarker(e) => {
    

    With Arrow Functions you will not get the problem ;)