distance.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import Storage from './../store/storage.js';
  2. // 获取弧度
  3. // 根据两点的经纬度计算距离
  4. function getRad(d) {
  5. return (d * Math.PI) / 180.0;
  6. };
  7. // 计算距离 lat1,lng1 第一个坐标 lat2,lng2 目标坐标
  8. function getFlatternDistance(lat1, lng1, lat2, lng2) {
  9. var f = getRad((lat1 + lat2) / 2);
  10. var g = getRad((lat1 - lat2) / 2);
  11. var l = getRad((lng1 - lng2) / 2);
  12. var sg = Math.sin(g);
  13. var sl = Math.sin(l);
  14. var sf = Math.sin(f);
  15. var s, c, w, r, d, h1, h2;
  16. var a = 6378137.0;
  17. var fl = 1 / 298.257;
  18. sg = sg * sg;
  19. sl = sl * sl;
  20. sf = sf * sf;
  21. s = sg * (1 - sl) + (1 - sf) * sl;
  22. c = (1 - sg) * (1 - sl) + sf * sl;
  23. w = Math.atan(Math.sqrt(s / c));
  24. r = Math.sqrt(s * c) / w;
  25. d = 2 * w * a;
  26. h1 = (3 * r - 1) / 2 / c;
  27. h2 = (3 * r + 1) / 2 / s;
  28. return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
  29. }
  30. let latitude = '';
  31. let longitude = '';
  32. // 计算距离
  33. function calculateDistance(shopPosition) {
  34. var arr = Storage.getCache('longitude')
  35. latitude = arr.latitude
  36. longitude = arr.longitude
  37. if (latitude && longitude) {
  38. const [lat, lon] = shopPosition.split(",")
  39. const cal = getFlatternDistance(latitude, longitude, Number(lat), Number(lon))
  40. const number = Math.round(cal)
  41. if (cal > 999) {
  42. return (number / 1000).toFixed(1) + 'km'
  43. } else {
  44. return number + '米'
  45. }
  46. } else {
  47. return ''
  48. }
  49. }
  50. export default calculateDistance;