2017-08-10 199 views
1

我使用Mapbox GL JS来查找用户在地图上单击的点击点的最近特征。它的工作很棒。但是我想输出一个近似的距离。即时通讯使用是下面的代码...Mapbox GL与bbox的大致距离

function nearestFeature(y,x) { 
    var bbox = [[y, x], [y, x]]; 
    var featuresBuilding = map.queryRenderedFeatures(bbox, { layers: ['MyBuildingLayer'] }); 
    if (featuresBuilding[0]) { 
     //found 
    }else{ 
     //widen the area 
     for (i = 1;i<100;i++) { 
      bbox = [[y-i, x-i], [y+i, x+i]]; 
      featuresBuilding = map.queryRenderedFeatures(bbox, { layers: ['MyBuildingLayer'] }); 
      if (featuresBuilding[0]) { 
       //calculate distance 
       var distance = 100*i; 
       break; 
      } 
     } 
    } 
} 

我可能会复杂化这个问题,但本质上我需要计算出的距离分的差距是X/Y和乘以米的距离获得一个粗略的估计。我用VAR距离= 100 *我来说明这一点,我需要弄清楚如何确定虚拟100人的身影......

+1

是您的目标,以“一站式”搜索一旦你打的特点X量我认为你需要什么?澄清一点。 – snkashis

+0

本质上,我开始拓宽BBOX,直到我击中图层上的特定建筑。真的这个信息是补充的。我需要找出的是如何将点差转换为距离。 – RedCrusador

+0

仍然不明白你的问题的本质。也许你可以进一步解释你想要达到的目标以及问题所在。我可以理解你的代码,但是我没有得到:“找出X/Y点差异的距离”。 –

回答

1

我曾经有一个项目,我还需要1px的值作为距离值来构建类似于比例控制(https://www.mapbox.com/mapbox-gl-js/api/#scalecontrol

解决方案是使用当前视口的边界框来计算2个点之间的距离。除以用户视口宽度将会给你1个像素的距离。我使用mapbox scale控件来检查我的值与他们的值,结果似乎是合理的。

我想出了这个解决方案(需要turf.js)。 你可以看到完整的工作例如在快速的jsfiddle我创建: https://jsfiddle.net/andi_lo/38h7m5wx/

function getDistance() { 
 
    const bounds = map.getBounds(); 
 
    const topLeft = turf.point([bounds._ne.lng, bounds._ne.lat]); 
 
    const topRight = turf.point([bounds._sw.lng, bounds._ne.lat]); 
 
    const bottomLeft = turf.point([bounds._ne.lng, bounds._sw.lat]); 
 
    const bottomRight = turf.point([bounds._sw.lng, bounds._sw.lat]); 
 
    
 
    const middleLeft = turf.midpoint(topLeft, bottomLeft); 
 
    const middleRight = turf.midpoint(topRight, bottomRight); 
 
    const distance = turf.distance(middleLeft, middleRight, 'kilometers'); 
 
    return distance; 
 
} 
 

 
const clientWidth = window.innerWidth; 
 
const distance = getDistance(); 
 
const onePixel = distance/clientWidth; 
 
console.log(`1px is ~${onePixel.toFixed(3)} km or ${Math.ceil((onePixel) * 1000)} meters`);