0
votes

I'm trying to set a simple form text field containing the longitute and latitute from inside of a clicklistener of OpenlLayers. As a result I get

ERROR TypeError: Cannot read property 'setValue' of undefined

Why is this.lat and this.long producing an undefined? I guess because I'm inside of this listener, because when I set a value in that ngOnInit method it works. How can I set the value from inside of the clickListener? What am I missing?

import { FormControl } from "@angular/forms";
import { Component, OnInit } from "@angular/core";

declare var ol: any;

@Component({
  selector: "app-spotcreation",
  templateUrl: "./spotcreation.component.html",
  styleUrls: ["./spotcreation.component.css"]
})
export class SpotcreationComponent implements OnInit {
  source = new ol.source.OSM();

  map: any;

  lon = new FormControl();
  lat = new FormControl();

  ngOnInit() {
    this.map = new ol.Map({
      target: "map",
      controls: ol.control.defaults({
    attributionOptions: {
      collapsible: false
    }
      }),
      layers: [
    new ol.layer.Tile({
      source: this.source
    })
      ],
      view: new ol.View({
    center: ol.proj.fromLonLat([18.405, 45.095]),
    zoom: 8
      })
    });

    this.map.on("click", this.clickListener);
  }

  clickListener = function(args) {
    var lonlat = ol.proj.transform(args.coordinate, "EPSG:3857", "EPSG:4326");

    var latitude = lonlat[0];
    var longitude = lonlat[1];

    this.lat.setValue(latitude);
    this.lon.setValue(longitude);
  };
}
1

1 Answers

1
votes

The issue is with the context which is changed. That is why lat and lon is not accessible. You can modify your as below to ensure you are not loosing the current class context.

    this.map.on("click", args=>{
       var lonlat = ol.proj.transform(args.coordinate, "EPSG:3857", "EPSG:4326");
       var latitude = lonlat[0];
       var longitude = lonlat[1];
       this.lat.setValue(latitude);
       this.lon.setValue(longitude);
    })

Do not forget to remove function clickListener since the code has been moved inside the map.on function.