我有一个带有 2 个文本输入和一张传单地图的简单表单,一旦用户点击地图,我就会得到该位置的经度和纬度。
我正在功能中设置地图ngOnInit()
,并且一旦用户单击,我就有一个要设置的纬度全局变量。然后在表单提交中,当我尝试控制台记录 this.latitude 时,它总是显示未定义或 0,以防我将其初始化为 0。
这是我的组件:
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)
}
}
简短版本:如何在内部设置变量值,ngOnInit()
然后在同一组件的其他函数中检索该值?我错过了什么?任何帮助,将不胜感激。谢谢