Angular 和 Leaflet 在点击时添加标记并获取坐标

Nad*_*dim 2 javascript api leaflet typescript angular

我正在尝试在我的 Angular 7 项目中实现 Leaflet,我尝试用 google 搜索解决方案,但没有任何结果是针对 AngularJS 或 Vanilla JavaScript 的。

这是我的 ts 文件:

 ngAfterViewInit(): void {
    //Init map & add tile
    this.map = new Map('map').setView([25.1220946, 56.3342466], 13);
    tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}').addTo(this.map);
    //onClick
    this.map.on("click", function(e){
    //Add marker
    this.myMarker = marker([e.latlng.lat, e.latlng.lng]).addTo(this.map);
    // console.log();
      console.log(`Your lat is : ${e.latlng.lat} and your lang :  ${e.latlng.lng}`);
    });
  }
Run Code Online (Sandbox Code Playgroud)

仅供参考,这不是重复的,同样的问题已经有 5 年了,现在一切都不同了。

kbo*_*oul 5

要在地图单击上添加标记,您需要在实例化地图对象后监听地图单击事件:

\n\n
ngOnInit() {\n    this.map = L.map("map").setView([25.1220946, 56.3342466], 13);\n    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {\n      attribution:\n        \'\xc2\xa9 <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors\'\n    }).addTo(this.map);\n\n    this.map.on("click", e => {\n      console.log(e.latlng); // get the coordinates\n      L.marker([e.latlng.lat, e.latlng.lng], this.markerIcon).addTo(this.map); // add the marker onclick\n    });\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

以下是使用 Angular 8 的示例:\n演示

\n

  • 您在问题中没有提到这种行为 (2认同)