【问题标题】:Angular and Leaflet add marker on click and get Coord [duplicate]Angular和Leaflet在点击时添加标记并获取坐标[重复]
【发布时间】:2019-12-06 21:33:59
【问题描述】:

我正在尝试在我的 angular 7 项目中实现 Leaflet,我尝试用谷歌搜索解决方案,但没有任何结果适用于 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}`);
    });
  }

仅供参考它不是重复的,同样的问题是 5 岁,现在一切都不同了。

【问题讨论】:

    标签: javascript angular typescript api leaflet


    【解决方案1】:

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

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

    这是一个使用 Angular 8 的示例: Demo

    【讨论】:

    • 它正在工作,但我想在点击添加新标记时删除旧标记
    • 你没有在你的问题中提到这种行为
    【解决方案2】:

    根据 @kboul 的回答,我们可以使用以下代码行来实现(每次我点击具有正确纬度 lng 的地图时添加一个新标记):

    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", e => {
          console.log(e.latlng); // get the coordinates
          if (this.myMarker) { // check
            this.map.removeLayer(this.myMarker); // remove
        } this.myMarker = new marker([e.latlng.lat, e.latlng.lng]).addTo(this.map); // add the marker onclick
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-04
      • 2019-02-14
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 2021-10-21
      相关资源
      最近更新 更多