2017-03-28 19 views
1

私は2つの場所があり、メートルで距離を計算したいと思います。私はいくつかのコードを書いたが、完全には機能していない。メートルの2つの場所間の距離を計算します

private void getDistancBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2) 
{ 
    Location loc1 = new Location(""); 
    loc1.setLatitude(lat1); 
    loc1.setLongitude(lon1); 

    Location loc2 = new Location(""); 
    loc2.setLatitude(lat2); 
    loc2.setLongitude(lon2); 

    int R = 6371; // km 

    double dLat = deg2rad(lat2-lat1); 
    double dLon = deg2rad(lon2-lon1); 
    double a = 
      Math.sin(dLat/2) * Math.sin(dLat/2) + 
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
          Math.sin(dLon/2) * Math.sin(dLon/2) 
      ; 
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    double distanceInMeters = R * c; 
    Log.e("distanceInMeters",distanceInMeters/10000+"mm"); 
} 

public double deg2rad(double deg) { 
    return deg * (Math.PI/180); 
} 

距離をメートルで計算するにはどうすればよいですか?私の目標は、メートル> 200なら何かをすることです。どうすれば問題を解決できますか?

答えて

0

2つの緯度/経度の間の距離を計算するには、&を使用します。

/** 
* Calculate distance between two points in latitude and longitude taking 
* into account height difference using the Haversine method as its base. 
* 
* Elevation should be in meters. If you are not interested in elevation, pass 0. 
* 
* @return Distance in meters 
*/ 
private double distanceBetween(double lat1, double lat2, double lon1, 
           double lon2, double el1, double el2) { 

    final int R = 6371; // Radius of the earth 

    double latDistance = Math.toRadians(lat2 - lat1); 
    double lonDistance = Math.toRadians(lon2 - lon1); 
    double a = Math.sin(latDistance/2) * Math.sin(latDistance/2) 
      + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) 
      * Math.sin(lonDistance/2) * Math.sin(lonDistance/2); 
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); 
    double distance = R * c * 1000; // convert to meters 

    double height = el1 - el2; 

    distance = Math.pow(distance, 2) + Math.pow(height, 2); 

    return Math.sqrt(distance); 
} 
3

このためにホイールを再作成する必要はありません。

Location.distanceBetween()メソッドを使用できます。 the documentationから

:あなたの距離を計算するためのコードの下に使用することができ

private float getDistancBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2) { 

    float[] distance = new float[2]; 

    Location.distanceBetween(lat1, lon1, 
      lat2, lon2, distance); 

    return distance[0]; 
} 
0

は、ここでは、2つの場所

間のメートルでのおおよその距離が簡単な例である計算2つのメーター間の位置:

private double distanceBetween(double lat1, double lon1, double lat2, double lon2) { 
    double theta = lon1 - lon2; 
    double dist = Math.sin(deg2rad(lat1)) 
      * Math.sin(deg2rad(lat2)) 
      + Math.cos(deg2rad(lat1)) 
      * Math.cos(deg2rad(lat2)) 
      * Math.cos(deg2rad(theta)); 
    dist = Math.acos(dist); 
    dist = dist * 180.0/Math.PI; 
    dist = dist * 60 * 1.1515*1000; 
    return (dist); 
} 

private double deg2rad(double deg) { 
    return (deg * Math.PI/180.0); 
} 
関連する問題