经纬度两点距离公式代码实现异常,请求排查修正
Let's break down what's going wrong with your code and fix it step by step—your huge distance result makes sense once we spot the mistakes!
Key Issues in Your Current Code
- Critical Parenthesis Error: In your
ccalculation, you wrote(float(lat1) - float(lat2)**2)which computeslat1 minus (lat2 squared)instead of(lat1 minus lat2) squared. This completely mangles your initial distance calculation, leading to absurdly large values. - Missing Radian Conversion: Earth's radius (6371 km) pairs with angular measurements in radians, but you're working with degrees. Using degree differences directly will blow up your final result way beyond reality.
- Incorrect Formula Application: Your final calculation mixes up the order of operations and doesn't properly apply spherical distance logic.
Corrected Code (Accurate Haversine Formula)
First, make sure you import math at the top of your script. This uses the standard Haversine formula for spherical distance, which is perfect for your use case:
import math def distance_between_two_point(lat1, lon1, lat2, lon2): # Convert all coordinates from degrees to radians (math functions use radians) lat1_rad = math.radians(float(lat1)) lon1_rad = math.radians(float(lon1)) lat2_rad = math.radians(float(lat2)) lon2_rad = math.radians(float(lon2)) # Calculate differences between coordinates delta_lat = lat1_rad - lat2_rad delta_lon = lon1_rad - lon2_rad # Haversine formula to compute spherical distance a = math.sin(delta_lat / 2)**2 + math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(delta_lon / 2)**2 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) # Multiply by Earth's radius (km) to get final distance distance = 6371 * c return distance
Simplified Approximation (For Short Distances)
Since your coordinates are within a 10km range, Earth's curvature is barely noticeable. You can use a simpler planar approximation if you prefer—it's slightly less accurate but faster:
import math def distance_between_two_point(lat1, lon1, lat2, lon2): lat_avg = (float(lat1) + float(lat2)) / 2 # Convert coordinate differences to radians delta_lat_rad = math.radians(float(lat1) - float(lat2)) delta_lon_rad = math.radians(float(lon1) - float(lon2)) # Convert differences to kilometers (longitude needs a cosine adjustment for latitude) lat_distance = 6371 * delta_lat_rad lon_distance = 6371 * delta_lon_rad * math.cos(math.radians(lat_avg)) # Pythagorean theorem for planar distance distance = math.sqrt(lat_distance**2 + lon_distance**2) return distance
Testing With Your Input Range
If you plug in coordinates like lat1=-35.29, lon1=149.105 and lat2=-35.27, lon2=149.130, both functions will return a distance around 3.5 km—right in your expected 10km range.
内容的提问来源于stack exchange,提问作者Benjamin Stark

