gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
package cn.lili.common.utils; public class HaversineDistance { // 地球的平均半径(单位:公里) private…
- User
package cn.lili.common.utils;
public class HaversineDistance {
// 地球的平均半径(单位:公里) private static final double EARTH_RADIUS = 6378.137; // 方法将角度转换为弧度 public static double toRadians(double degrees) { return degrees * Math.PI / 180.0; } // 方法计算两个点之间的距离 public static String getDistance(double lat1, double lon1, double lat2, double lon2) { double radLat1 = toRadians(lat1); double radLat2 = toRadians(lat2); double a = radLat1 - radLat2; double b = toRadians(lon1) - toRadians(lon2); double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * EARTH_RADIUS; s = Math.round(s * 10000) / 10000.0; return String.format("%.2f 公里", s); // 格式化为两位小数 } public static void main(String[] args) { // 示例用户坐标 double userLat = 30.571732; double userLon = 114.324304; // 示例商家坐标 double businessLat = 30.644688; double businessLon = 114.423084; // 计算距离 String distance = getDistance(userLat, userLon, businessLat, businessLon); // 打印距离 System.out.println("经纬度计算的距离: " + distance); }}
帮我转换为vue的方法
- Assistant
当然可以!我们可以把Haversine公式实现为一个JavaScript函数,然后可以在Vue.js组件中使用它。以下是如何在Vue.js中实现这个功能的示例:
首先,创建一个JavaScript函数用于计算哈弗萨恩距离:
// utils/haversineDistance.js export function toRadians(degrees) { return degrees * Math.PI / 180.0; } export function getDistance(lat1, lon1, lat2, lon2) { const EARTH_RADIUS = 6378.137; const radLat1 = toRadians(lat1); const radLat2 = toRadians(lat2); const a = radLat1 - radLat2; const b = toRadians(lon1) - toRadians(lon2); let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * EARTH_RADIUS; s = Math.round(s * 10000) / 10000.0; return `${s.toFixed(2)} 公里`; }然后在你的Vue.js组件中使用这个函数:
<template> <div> <h2>经纬度计算的距离: {{ distance }}</h2> </div> </template> <script> import { getDistance } from './utils/haversineDistance'; export default { data() { return { userLat: 30.571732, userLon: 114.324304, businessLat: 30.644688, businessLon: 114.423084, distance: '' }; }, mounted() { this.calculateDistance(); }, methods: { calculateDistance() { this.distance = getDistance(this.userLat, this.userLon, this.businessLat, this.businessLon); } } }; </script> <style scoped> h2 { color: blue; } </style>