google map Api를 사용하여 거리계산하기

kang·2020년 4월 10일
1

javascript

목록 보기
3/5

구글 맵을 사용하여 내 위치를 받아오고, 특정 지점들의 좌표값을 받아와서 현재 내 위치와 특정 지점의 거리계산하며 가까운 순으로 리스트로 보여주는 개발을 했었다.


const rad = (x) => {
   return (x * Math.PI) / 180;
};

const getDistance = (p1, p2) => {
    const R = 6378137; // Earth’s mean radius in meter
    const dLat = rad(p2.latiDegr - p1.latitude);
    const dLong = rad(p2.longDegr - p1.longitude);
    const a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(rad(p1.latitude)) * Math.cos(rad(p2.latiDegr)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const d = R * c;
    return d; // returns the distance in meter
  };

const nearPoints = centerList는.map((rows) => { 각 지점의 좌표
    return { ...rows, nearPoint: getDistance(geoLoacation, rows) };
  });
 
const orderBynearPointList = nearPoints.sort((a, b) => {
  return +(a.nearPoint > b.nearPoint) || +(a.nearPoint === b.nearPoint) - 1;
});

위 코드에서 nearPoints에 할당된 centerList는 각 지점의 위도, 경도에 대한 리스트이며,
리스트를 map() 메소드를 사용하여 getDistance 함수에 현재 위치와 각 지점의 위치를 인자로 전달해 거리를 계산하였고, geolocation은 현재 내 위치(위도, 경도)이며, rows는 각 지점의 위도, 경도이다. orderBynearPointList는 가까운 위치로 정렬시켰다.

처음 작업을 진행할 때, 현재 위치를 서버에 보내면 현재 위치와 지점위치간의 거리에 대한 값을 받을 줄 알고 있었는데, 데이터 조회를 해보니 각 지점의 위치만 받을 수 있었다.

담당자에게 문의 해보니 각 지점의 위치만 내려줄 뿐, 계산은 클라이언트 쪽에서 하는거라고 협의 되었다고 전달받아 만들었던 기억이..

profile
ksb

0개의 댓글