2017-08-10 40 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`);