2017-04-22 56 views
-1

我有一個應用程序,我正在使用緯度和經度顯示最近的事件(地點)距離以公里爲單位。用戶的經緯度是可變的,但事件的經緯度是固定的。但是,我無法得到正確的距離是km。例如,谷歌地圖上的正確距離是6.7公里,但是顯示的是8663.90公里。我是android的新手,所以無法獲得解決方案。任何幫助將是偉大的!我的代碼是使用緯度和經度的距離沒有正確顯示android

{ double doubleInstance = d.getDistance(Lat1, Lon1, d.getLatitude(), d.getLongitude(), "N"); 
      String dInstance = String.format("%.2f",doubleInstance); 
      lblview1.setText(" " + String.valueOf(dInstance) + " Km"); } 

{ public double getDistance(double lat1, double lon1, double lat2, double lon2, String unit) { 

    int Radius = 6371;// radius of earth in Km 
    double dLat = Math.toRadians(lat2 - lat1); 
    double dLon = Math.toRadians(lon2 - lon1); 
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) 
      + Math.cos(Math.toRadians(lat1)) 
      * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon/2) 
      * Math.sin(dLon/2); 
    double c = 2 * Math.asin(Math.sqrt(a)); 
    double valueResult = Radius * c; 
    double km = valueResult/1; 
    DecimalFormat newFormat = new DecimalFormat("####"); 
    int kmInDec = Integer.valueOf(newFormat.format(km)); 
    double meter = valueResult % 1000; 
    int meterInDec = Integer.valueOf(newFormat.format(meter)); 
    Log.i("Radius Value", "" + valueResult + " KM " + kmInDec 
      + " Meter " + meterInDec); 

    return Radius * c; 
} } 
+1

不要太辛苦了 - 使用一些內置的方法 - https://developer.android.com/reference/android/location/Location.html#distanceBetween(double,%20double,%20double, %20double,%20float []) – TDG

+0

@TDG你能幫我用代碼嗎? – Ankit

回答

1

使用位置類的方法獲取的距離之間的兩個座標喜歡;

Location.distanceBetween(obj.getLatitude(), obj.getLongitude(), 
             mapCircle.getCenter().latitude, mapCircle.getCenter().longitude, distance); 
+0

兄弟不能正常工作.. :( – Ankit

+0

你有沒有檢查你的座標值並改變參數值以匹配你的座標? – KDeogharkar

+0

lat1和lon1不是固定的..但是,事件lat lon是固定的.. – Ankit

2

設置您的活動位置。並使用位置經理獲取您的當前位置。

double latitude=lat; 
double longitude=lng;  
float distance=0; 
Location crntLocation=new Location("crntlocation"); 
crntLocation.setLatitude(currentLatitude); 
crntLocation.setLongitude(currentLongitude); 

Location eventLocation=new Location("eventlocation"); 
eventLocation.setLatitude(latitude); 
eventLocation.setLongitude(longitude); 


//float distance = crntLocation.distanceTo(eventLocation); in meters 
distance =crntLocation.distanceTo(eventLocation)/1000; // in kms 
相關問題