Calculate distance between two points in google maps V3

后端 未结 15 1958
醉梦人生
醉梦人生 2020-11-22 02:27

How do you calculate the distance between two markers in Google maps V3? (Similar to the distanceFrom function inV2.)

Thanks..

15条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 02:48

      /**
       * Calculates the haversine distance between point A, and B.
       * @param {number[]} latlngA [lat, lng] point A
       * @param {number[]} latlngB [lat, lng] point B
       * @param {boolean} isMiles If we are using miles, else km.
       */
      function haversineDistance(latlngA, latlngB, isMiles) {
        const squared = x => x * x;
        const toRad = x => (x * Math.PI) / 180;
        const R = 6371; // Earth’s mean radius in km
    
        const dLat = toRad(latlngB[0] - latlngA[0]);
        const dLon = toRad(latlngB[1] - latlngA[1]);
    
        const dLatSin = squared(Math.sin(dLat / 2));
        const dLonSin = squared(Math.sin(dLon / 2));
    
        const a = dLatSin +
                  (Math.cos(toRad(latlngA[0])) * Math.cos(toRad(latlngB[0])) * dLonSin);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        let distance = R * c;
    
        if (isMiles) distance /= 1.609344;
    
        return distance;
      }
    

    I found a version online which is 80% right but plugged in the wrong parameter and is inconsistent in using the inputs, this version fixed that completely

提交回复
热议问题