1

我写了一个函数来确定两个 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);
           }


       }

这看起来对吗?

4

1 回答 1

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

虽然我建议将距离和南运动分开(将来也许你也想检测东西运动)

于 2013-05-28T20:17:17.587 回答