2017-04-22 2 views
-1

緯度と経度を使用して、最も近いイベント(場所)距離をkmで表示しているアプリがあります。ユーザーの緯度と経度は可変ですが、イベントの緯度と経度は固定されています。ただし、正しい距離はkmです。たとえば、正しい距離はGoogleマップで6.7 kmですが、その表示は8663.90 kmです。私はアンドロイドの初心者ですので、解決策を得ることができません。どんな助けも素晴らしいでしょう!私のコードは緯度と経度を使用して距離が正しく表示されない

{ 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は修正されていません。 – 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 
関連する問題