【问题标题】:Leaflet How To Update User Position Marker Real Time传单如何实时更新用户位置标记
【发布时间】:2017-10-28 17:20:17
【问题描述】:

我正在尝试更新用户在传单中的位置。就像当用户带着手机走路时,他们的位置标记也会像谷歌地图一样根据位置数据移动。

现在我只是在他们的初始位置上放了一个标记

    this.map.locate({
  setView: true,
  maxZoom: 120
}).on("locationfound", e => {

  leaflet.marker([e.latitude, e.longitude]).bindPopup("YOU ARE HERE!").addTo(this.map);



  console.log("lokasyon bulundu");
}).on("locationerror", error => {

  console.log("lokasyon bulunamadi");
});

尝试了 update() 方法,但无法使其工作。我想我应该每秒获取用户位置数据,如果不同,则绘制新标记并删除旧标记?这是一种有效的方法吗?

谢谢 编辑这是我根据答案尝试的。它不工作。我从数据库中提取数据并基于该确定自定义标记

this.map.locate({
    setView: true,
    maxZoom: 120,
    watch:true,
    enableHighAccuracy:true
  }).on("locationfound", e => {
      if (!usermarker) {

        if(this.profileData.avatar == "https://i.hizliresim.com/zJJ239.png"){
          usermarker = new L.marker(e.latlng,{icon : ayi}).addTo(this.map);
        }else if(this.profileData.avatar == "https://i.hizliresim.com/mJJrkP.png"){
          usermarker = new L.marker(e.latlng,{icon : ironman}).addTo(this.map);
        }else if(this.profileData.avatar == "https://i.hizliresim.com/vJJQpp.png"){
          usermarker = new L.marker(e.latlng,{icon : dino}).addTo(this.map);
        }else if(this.profileData.avatar == "https://i.hizliresim.com/zJJ2B9.png"){
          usermarker = new L.marker(e.latlng,{icon : petyr}).addTo(this.map);
        }
      } else if(this.profileData.avatar == "https://i.hizliresim.com/zJJ239.png") {
          usermarker.setLatLng(e.latlng);
      }
  }).on("locationerror", error => {
      if (usermarker) {
          map.removeLayer(usermarker);
          usermarker = undefined;
      }
  });

【问题讨论】:

    标签: javascript geolocation leaflet


    【解决方案1】:

    只需检查是否创建了标记,如果没有创建,则使用 L.Marker 的setLatLng 方法更新它:

    将标记位置更改为给定点。

    参考:http://leafletjs.com/reference-1.2.0.html#marker-setlatlng

    例子:

    var marker;
    
    this.map.locate({
      setView: true,
      maxZoom: 120
    }).on("locationfound", e => {
        if (!marker) {
            marker = new L.marker(e.latlng).addTo(this.map);
        } else {
            marker.setLatLng(e.latlng);
        }
    }).on("locationerror", error => {
        if (marker) {
            map.removeLayer(marker);
            marker = undefined;
        }
    });
    

    【讨论】:

    • 您好,感谢您的回答。我尝试了类似的方法,但它不起作用。prntscr.com/h3gdc5 我所做的是从数据库中提取数据并基于此更改标记。
    猜你喜欢
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 2015-12-20
    • 2013-05-28
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    相关资源
    最近更新 更多