Leaflet如何更新用户位置标记实时

时间:2017-10-28 17:20:17

标签: javascript geolocation leaflet

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

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

    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");
});

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

感谢 编辑这是我根据答案尝试的。它没有work.im从db中提取数据并基于确定自定义标记

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;
      }
  });

1 个答案:

答案 0 :(得分:0)

只检查是否有标记创建,如果没有创建它,否则使用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;
    }
});
相关问题