使用经度和纬度比较两个位置 [英] Comparing two locations using their Longitude and Latitude

查看:35
本文介绍了使用经度和纬度比较两个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi i need to cal an event at onchangelocation(), by comparing current latitude and longitude with some saved latitude and longitude but i m getting an error. eclipse is not recognizing key word distance, and for correction error it is giving hint to crate method "distance" having 4 parameter ... how to fix it??? or some other way to do same work???

谢谢和问候.代码附在下面

thanks and regards. code is attached below

@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...
  }
}

推荐答案

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

You actually need to implement a function called distance that will calculate the distance between two locations. Calculating the distance between two locations is one possible way of comparing the longitude and latitude values.

比较它们的示例:

@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 中:

And in 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
}

这篇关于使用经度和纬度比较两个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆