[英]Implement Google Places into Google Maps Using My Current Location
[英]Find the location nearest to current location from an array of locations using Google Maps Places API
我有一個包含不同locations' addresses
的array
。 我還檢索了用戶的當前位置。
在陣列中的所有位置中,我想找到nearest
。 一種方法可能是比較Lat-Long
,但還有其他方法可以解決嗎?
注意:我not performing nearby location search
來檢索地址。 假設我已將它們存儲在一個數組中。
您可以使用Location來確定兩個地址之間的距離:
private static float distance(LatLng current, LatLng last){
if(last==null)
return 0;
Location cL = new Location("");
cL.setLatitude(current.latitude);
cL.setLongitude(current.longitude);
Location lL = new Location("");
lL.setLatitude(last.latitude);
lL.setLongitude(last.longitude);
return lL.distanceTo(cL);
}
如果您需要最近的位置,請使用Location.distanceBetween
。
如果您有很多位置並且要求代碼執行得更快,我建議使用以下公式:
double diffLat = Math.abs(lat1 - lat2);
double diffLng = Math.abs(lng1 - lng2);
if (diffLng > 180) {
diffLng = 360 - diffLng;
}
double distanceSquared = diffLat * diffLat + diffLng * diffLng;
不要計算這個的sqrt,因為不需要找到(近似)最近的位置。 只需比較平方值。
if
是存在的,因為您可能有-179和+179經度的位置,這些位置彼此接近。
根據數據,您也可以嘗試對已排序數據進行二進制搜索的算法,但這里有2個維度,因此它不像在有序int[]
查找int
那樣簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.