19

嗨,我需要通过将当前纬度和经度与一些保存的纬度和经度进行比较来在 onchangelocation() 处调用一个事件,但我得到了一个错误。eclipse 无法识别关键字距离,并且为了纠正错误,它提示具有 4 个参数的 crate 方法“距离”......如何修复它???或其他方式做同样的工作???

谢谢并恭祝安康。代码附在下面

@Override
public void onLocationChanged(Location location) {
 double currentLat=location.getLatitude();
 double currentLon=location.getLongitude();

    if (distance(lat,lon,currentLat,currentLon)<2.0){
 //do what you want to do...
  }
}
4

3 回答 3

40

您实际上需要实现一个名为 distance 的函数,该函数将计算两个位置之间的距离。计算两个位置之间的距离是比较经度和纬度值的一种可能方法。

一个比较它们的例子:

@Override
public void onLocationChanged(Location location) {

 double lat2 = location.getLatitude();
 double lng2 = location.getLongitude();

    // lat1 and lng1 are the values of a previously stored location
    if (distance(lat1, lng1, lat2, lng2) < 0.1) { // if distance < 0.1 miles we take locations as equal
       //do what you want to do...
    }
}

/** calculates the distance between two locations in MILES */
private double distance(double lat1, double lng1, double lat2, double lng2) {

    double earthRadius = 3958.75; // in miles, change to 6371 for kilometer output

    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);

    double sindLat = Math.sin(dLat / 2);
    double sindLng = Math.sin(dLng / 2);

    double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
        * Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));

    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

    double dist = earthRadius * c;

    return dist; // output distance, in MILES
}

在 Kotlin 中:

private fun distance(lat1: Double, lng1: Double, lat2: Double, lng2: Double): Double {
    val earthRadius = 3958.75 // in miles, change to 6371 for kilometer output

    val dLat = Math.toRadians(lat2 - lat1)
    val dLng = Math.toRadians(lng2 - lng1)

    val sindLat = sin(dLat / 2)
    val sindLng = sin(dLng / 2)

    val a = sindLat.pow(2.0) +
            (sindLng.pow(2.0) * cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)))

    val c = 2 * atan2(sqrt(a), sqrt(1 - a))

    return earthRadius * c // output distance, in MILES
}
于 2013-08-11T08:54:15.323 回答
16

您可以像这样使用Location类的静态distanceBetween()方法:

import android.location.Location

float[] distance = new float[1];

Location.distanceBetween(lat, lon, currentLat, currentLon, distance);

// distance[0] is now the distance between these lat/lons in meters
if (distance[0] < 2.0) {
    // your code...
}

如果你有两个Location对象,另一个选择是distanceTo()

于 2015-02-24T19:07:09.753 回答
0

所有 4 个输入参数都是浮点数。距离是相对的,不是真实的距离。您需要通过在线搜索一些公式将这个距离转换为实际距离:(我在我的应用程序中使用它来获取离我当前位置最近的地铁站。希望这个片段可以帮助某人:)

float distance(float lat,float lon,float clat,float clon)
{
    float distance;
    float temp1;
    float temp2;
    temp1=(float)((lat-clat)*(lat-clat));
    temp2=(float)((lon-clon)*(lon-clon));
    distance=temp1+temp2;
    return distance;
}
于 2014-08-17T05:38:01.187 回答