Leaflet地图事件上的Angular 7变量访问问题

时间:2019-03-01 07:16:25

标签: angular typescript leaflet

我在Angular上使用Leaflet。我创建了一张地图。后来我在地图上添加了一个标记。当单击地图上的某个位置时,将调用onMapClick函数。但是我无法在onMapClick函数中访问标记和地图。调用initMap函数时,我可以在console.log结果中看到标记。调用onMapClick函数时,我无法访问标记。我得到一个错误。错误是标记未定义。我该如何解决?

import {Component, OnInit} from '@angular/core';
declare let L;

@Component({
    selector: 'app-map',
    templateUrl: './map.component.html',
    styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit {
    map;
    lat;
    lng;
    marker;

    constructor() {
    }

    ngOnInit() {
        this.initMap();
    }
    initMap() {
        this.map = new L.Map('map', {
            zoomControl: true,
            maxZoom: 20,
            minZoom: 5,
            center: new L.LatLng(41.00650212603, 28.8530806151128),
            zoom: 10
        });

        const tileLayers = {
            'Google Uydu': L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&hl=tr&x={x}&y={y}&z={z}', {
                subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
                maxNativeZoom: 20,
                zIndex: 0,
                maxZoom: 20
            }).addTo(this.map)
        };
        L.control.layers(tileLayers, null, {collapsed: false}).addTo(this.map);

        this.marker = L.marker(this.map.getCenter(), {
            draggable: true,
            icon: L.icon({
                iconUrl: './assets/img/marker-icon-2x.png',
                iconSize: [25, 35],
                iconAnchor: [30 / 2, 35],
            })
        }).addTo(this.map);
        console.log("this.marker", this.marker);
        this.map.on('click', this.onMapClick);
    }

    onMapClick(e) {
        this.lat = e.latlng.lat;
        this.lng = e.latlng.lng;
        console.log("this.marker", this.marker);
        this.marker.setLatLng(new L.LatLng(e.latlng.lat, e.latlng.lng));
        this.map.panTo(new L.LatLng(e.latlng.lat, e.latlng.lng));
        this.map.setView(new L.LatLng(e.latlng.lat, e.latlng.lng), 18);
    }
}

2 个答案:

答案 0 :(得分:1)

我认为您错过了在this.onMapClick上传递事件的机会

因此应为this.map.on("click", e => this.onMapClick(e));

您可以找到更多有关原因的here

Demo

答案 1 :(得分:0)

如果没有有效的代码示例,很难准确地找出问题所在。仅仅阅读代码,我认为您在onMapClick()方法中引用了错误的上下文。

this并不是您的角度类,而是地图本身。

要在回调中引用您的angular类,您必须将另一个上下文绑定到它。

实现此目标的一种方法如下:

this.map.on('click', this.onMapClick.bind(this));

现在,this中的onMapClick()应该指向您的角度类。