【问题标题】:Javascript leafletjs get user position for distance calcJavascript Leafletjs获取距离计算的用户位置
【发布时间】:2019-12-09 11:47:44
【问题描述】:

我目前正在尝试创建一个地图应用程序,到目前为止,地图加载和自定义信息和图标都可以正常工作。但是,我想向用户显示到地图上的标记有多远(距离)。

此代码有效,但我希望“from”变量成为用户当前位置而不是预定位置。

var onePlace = L.marker([63, 20], {icon: thisIcon}).bindPopup('My text'),
    theOtherPlace = L.marker([65, 20], {icon: thatIcon}).bindPopup('My text');

var to = onePlace.getLatLng();
var from = theOtherPlace.getLatLng();
var distance = from.distanceTo(to);

为了设置用户在地图上的位置,我使用他们快速入门指南中的代码,看起来像这样

    primaryMap.locate({
    });

    primaryMap.on('locationfound', positionFound);
    primaryMap.on('locationerror', positionNotFound);

    function positionFound(e) { 

    var myPosition = L.marker(e.latlng, {
    }).addTo(primaryMap);
}    
    function positionNotFound(e) {
    alert(e.message);
}

但是如何获得我在后期设置的位置是我正在努力的。

基本上,我想要的是这个

var myPos = [??].getLatLng();
var to = onePlace.getLatLng();
var distance = myPos.distanceTo(to);

第一次发帖,部分代码格式不正确,见谅。

无论如何,如果有人可以在这里帮助我,我将非常感激。一直被困在这个问题上,似乎在文档中找不到任何有用的东西(可能只是不太理解,因为我对此很陌生)。

提前致谢!

更新:

jsfiddle:https://jsfiddle.net/xcyniic/98sy6zxb/27/ 也许这可以帮助阐明我在做什么/做错了什么。

【问题讨论】:

    标签: javascript leaflet geopositioning


    【解决方案1】:

    您从 locationfound 事件中获取 latlng。

    primaryMap.on('locationfound', positionFound);
    function positionFound(e) { 
       var myPos = e.latlng;
       var to = onePlace.getLatLng();
       var distance = myPos.distanceTo(to); 
    }
    

    更新

    要获取外部的 pos 值,您必须在外部创建变量并测试它是否不为空;

    var myPos = null;
    primaryMap.on('locationfound', positionFound);
    function positionFound(e) { 
       myPos = e.latlng;
       calcDistances();
    }
    
    
    function calcDistances(){
       if(myPos){
          var to = onePlace.getLatLng();
          var distance = myPos.distanceTo(to); +
    
          var to2 = twoPlace.getLatLng();
          var distance = myPos.distanceTo(to2); 
    
          //...
       }
    }
    

    我认为你的想法是错误的。 locationfound 事件不会立即调用,它是一个异步服务。所以你必须在事件被调用并找到用户位置后计算距离。

    【讨论】:

    • 感谢您的回答。这是我尝试过的事情,不幸的是我需要能够从 positionFound 函数之外访问 myPos (获得多个位置,用户应该能够看到他们的距离)。也许我误解了一些东西,但是如果我尝试从位置函数之外访问 myPos,我只会收到一个错误,说它没有定义(在我假设的范围之外。)。
    • 我已尝试使用您输入的代码,但 myPos 始终为空。我可能在做一些根本错误的事情。我的最终目标是这样的: myPlace = L.marker([63, 20], {icon: myIcon}).bindPopup('My text' + myPos.distanceTo(myPlace);但由于我无法获取 myPos,这不起作用。
    • 我猜结尾看起来更像:myPlace = L.marker([63, 20], {icon: myIcon}).bindPopup('My text' + myPos.getLatLng().distanceTo (myPlace.getLatLng());
    • 你能在 jsfiddle.net 上创建一个例子吗?并尝试标记是否放置function positionFound(e) { L.marker(e.latlng).addTo(map)}
    • 谢谢,我想你已经搞定了。由于某种原因,在我尝试获取 myPos 的值之后调用 positionFound 。仍然不知道为什么,因为它应该在我的距离函数之前被调用...我会尝试添加一个 jsfiddle稍后。
    猜你喜欢
    • 2011-04-03
    • 2011-12-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    相关资源
    最近更新 更多