Java/Android

GPS 좌표를 이용한 거리 구하기

체리필터 2013. 7. 29. 21:41
728x90
반응형

구글링을 통해서 GPS의 좌표를 통한 거리 구하는 공식을 어렵게 찾아 적용했다.

내용은 아래와 같다.


if(oldCoordinate != null) {

// TODO 거리 누적...

double theta = oldCoordinate.getLongitude() - Double.parseDouble(lp.getLongitude());

double dist = Math.sin(Utility.deg2rad(oldCoordinate.getLatitude())) * Math.sin(Utility.deg2rad(Double.parseDouble(lp.getLatitude()))) +

Math.cos(Utility.deg2rad(oldCoordinate.getLatitude())) * Math.cos(Utility.deg2rad(Double.parseDouble(lp.getLatitude()))) * Math.cos(Utility.deg2rad(theta));

if(dist < -1 || dist > 1) {

logger.d("dist : %s", dist);

}

dist = Math.acos(dist);

dist = Utility.rad2deg(dist);

dist = dist * 60 * 1.1515; // statute miles. 단위는 기본 마일.

dist = dist * 1.609344;

if(dist != Double.NaN) {

totalDist += dist*1000;

}

} else {

oldCoordinate = new Coordinate();

}

if(!"".equals(lp.getAltitude())) oldCoordinate.setAltitude(Double.parseDouble(lp.getAltitude()));

if(!"".equals(lp.getLatitude())) oldCoordinate.setLatitude(Double.parseDouble(lp.getLatitude()));

if(!"".equals(lp.getLongitude())) oldCoordinate.setLongitude(Double.parseDouble(lp.getLongitude()));


하지만 dist 값이 -1보다 작거나 1보다 큰 값이 반환되는 경우 Math.acos에 잘못된 파라미터로 들어가게되고, acos는 NaN을 반환하게 된다.

팀 동료와 고민하면서 구글링하게 된 결과 나온 것은 아래와 같다.


float[] distance = new float[3];

if(oldCoordinate != null) {

Location.distanceBetween(oldCoordinate.getLatitude(), oldCoordinate.longitude,

Double.parseDouble(lp.getLatitude()), Double.parseDouble(lp.getLongitude()), distance);

totalDist += distance[0];

} else {

oldCoordinate = new Coordinate();

}

if(!"".equals(lp.getAltitude())) oldCoordinate.setAltitude(Double.parseDouble(lp.getAltitude()));

if(!"".equals(lp.getLatitude())) oldCoordinate.setLatitude(Double.parseDouble(lp.getLatitude()));

if(!"".equals(lp.getLongitude())) oldCoordinate.setLongitude(Double.parseDouble(lp.getLongitude()));


그냥 Location 안에 static으로 선언 된 distanceBetween 메소드를 이용하면 된다.

알기까지 무지막지한 삽질...

알고나면 허무한 ㅠㅠ

728x90
반응형