Android Location.distanceTo

时间:2013-05-28 20:13:46

标签: gps latitude-longitude android-location

我写了一个函数来确定两个GPS位置之间的距离。

public float latDistance(Location newLocal){
        // get distance
           Location tempLocal1 = new Location("ref1");
           Location tempLocal2 = new Location("ref2");
           // get lon difference
           tempLocal1.setLatitude(local.getLatitude());
           tempLocal1.setLongitude(0);
           tempLocal1.setAltitude(0);

           tempLocal2.setLatitude(newLocal.getLatitude());
           tempLocal2.setLongitude(0);
           tempLocal2.setAltitude(0);
           return  tempLocal2.distanceTo(tempLocal1);


       }

我的问题是,这会带来负值吗?我的目标是获得一个距离,反映他们是向北还是向南移动..所以,如果他们从起始位置向南移动,我想要一个负值,如果北方是一个正值?

似乎我总是得到一个正数,但我不知道这是否只是我的无比的gps读数

修改

my code now looks like this.. and i know it irregular to ask people to comment on the logic, but its a difficult thing to test as it relies on a gps signal and to test i have to basically go out side and get a good signal, which pulls me away from my IDE and LogCat..

public float getLattitudeDistance(Location newLocal){
        // get distance
           Location tempLocal1 = new Location("ref1");
           Location tempLocal2 = new Location("ref2");
           // get lon difference
           tempLocal1.setLatitude(local.getLatitude());
           tempLocal1.setLongitude(0);
           tempLocal1.setAltitude(0);

           tempLocal2.setLatitude(newLocal.getLatitude());
           tempLocal2.setLongitude(0);
           tempLocal2.setAltitude(0);

           if(local.getLatitude()>newLocal.getLatitude()){
               return  -tempLocal2.distanceTo(tempLocal1);
           }else{
               return  tempLocal2.distanceTo(tempLocal1);
           }


       }

public float getLongitudeDistance(Location newLocal){
        // get distance
           Location tempLocal1 = new Location("ref1");
           Location tempLocal2 = new Location("ref2");
           // get lon difference
           tempLocal1.setLatitude(0);
           tempLocal1.setLongitude(local.getLongitude());
           tempLocal1.setAltitude(0);

           tempLocal2.setLatitude(0);
           tempLocal2.setLongitude(newLocal.getLongitude());
           tempLocal2.setAltitude(0);

           if(local.getLongitude()>newLocal.getLongitude()){
               return  -tempLocal2.distanceTo(tempLocal1);
           }else{
               return  tempLocal2.distanceTo(tempLocal1);
           }


       }

这看起来是对的吗?

1 个答案:

答案 0 :(得分:4)

不,距离永远不会消极!

对于南方运动,您可以扩展您的代码:

float distance =  tempLocal2.distanceTo(tempLocal1);
// lat1: previous latitude
// lat2: current latitude
if (lat2 < lat1) {
  // movement = south
  distance = -distance:
} else {
  // movement = north or parallel aeqator or not moving
}
return distance

虽然我建议分开距离和南方运动(将来也许你想要发现一个东西方运动)