Python latitude longitude distance

Как рассчитать расстояние между двумя точками с помощью GEOPY в Python

В этом уроке мы обсудим различные методы, с помощью которых пользователь может рассчитать расстояние между двумя местами на Земле. geopy – это библиотека Python, которая помогает рассчитать географическое расстояние.

Сначала нужно установить geopy с помощью следующей команды:

После успешной установки мы готовы к работе с библиотекой geopy.

Вычисление расстояния между двумя точками

Ниже приведены важные методы, которые мы будем использовать, чтобы рассчитать расстояние между двумя точками с помощью GEOPY в Python:

Геодезическое расстояние – это длина кратчайшего пути между двумя точками на любой поверхности Земли. В следующем примере мы покажем, как пользователь может вычислить геодезическое расстояние на основе данных широты и долготы.

# First, import the geodesic module from the geopy library from geopy.distance import geodesic as GD # Then, load the latitude and longitude data for New York & Texas New_York = (40.7128, 74.0060) Texas = (31.9686, 99.9018) # At last, print the distance between two points calculated in kilo-metre print ("The distance between New York and Texas is: ", GD(New_York, Texas).km)
The distance between New York and Texas is: 2507.14797665193

Расстояние по большому кругу – это кратчайший путь между двумя точками на сфере. В этом случае мы предположим, что Земля – это идеальная сфера. В следующем примере показано, как пользователь может рассчитать расстояние по большому кругу, используя данные долготы и широты двух точек.

# First, import the great_circle module from the geopy library from geopy.distance import great_circle as GC # Then, load the latitude and longitude data for New York & Texas New_York = (40.7128, 74.0060) Texas = (31.9686, 99.9018) # At last, print the distance between two points calculated in kilo-metre print ("The distance between New York and Texas is: ", GC(New_York, Texas).km)
The distance between New York and Texas is: 2503.045970189156

Ортодромическое расстояние используется для вычисления кратчайшего расстояния между двумя точками широты и долготы на поверхности земли.

Читайте также:  Как создать объект typescript

Используя этот метод, пользователю необходимо иметь координаты двух точек (P и Q).

Сначала нужно преобразовать значения точек широты и долготы из десятичных градусов в радианы, а затем разделить значения широты и долготы на (180 / π). Пользователь должен использовать значение «π = 22/7». Тогда значение (180 / π) будет «57,29577». Если пользователь хочет рассчитать расстояние в милях, он может использовать значение радиуса Земли, то есть «3963», а если в километрах – использовать значение «6,378,80».

How to calculate the value of latitude in radians: The value of Latitude in Radian: Latitude (La1) = La1 / (180/?) OR The value of Latitude in Radian: Latitude (La1) = La1 / 57.29577 How to calculate the value of longitude in radians: The value of Longitude in Radian: Longitude (Lo1) = Lo1 / (180/?) OR The value of Longitude in Radian: Longitude (Lo1) = Lo1 / 57.29577

Пользователю нужны координаты точки P и точки Q с точки зрения долготы и широты, а затем необходимо использовать приведенную выше формулу для преобразования их в радианы.

Теперь рассчитаем расстояние между двумя точками по следующей формуле.

Distance (D) = 3963.0 * arccos[(sin(La1) * sin(La2)) + cos(La1) * cos(La2) * cos(Lo2 - Lo1)]
Distance (D) = 3963.0 * arccos[(sin(La1) * sin(La2)) + cos(La1) * cos(La2) * cos(Lo2 - Lo1)]

Таким образом, пользователь может рассчитать кратчайшее расстояние между двумя заданными точками на Земле с помощью формулы гаверсинуса.

from math import radians, cos, sin, asin, sqrt # For calculating the distance in Kilometres def distance_1(La1, La2, Lo1, Lo2): # The math module contains the function name "radians" which is used for converting the degrees value into radians. Lo1 = radians(Lo1) Lo2 = radians(Lo2) La1 = radians(La1) La2 = radians(La2) # Using the "Haversine formula" D_Lo = Lo2 - Lo1 D_La = La2 - La1 P = sin(D_La / 2)**2 + cos(La1) * cos(La2) * sin(D_Lo / 2)**2 Q = 2 * asin(sqrt(P)) # The radius of earth in kilometres. R_km = 6371 # Then, we will calculate the result return(Q * R_km) # driver code La1 = 40.7128 La2 = 31.9686 Lo1 = -74.0060 Lo2 = -99.9018 print ("The distance between New York and Texas is: ", distance_1(La1, La2, Lo1, Lo2), "K.M") # For calculating the distance in Miles def distance_2(La1, La2, Lo1, Lo2): # The math module contains the function name "radians" which is used for converting the degrees value into radians. Lo1 = radians(Lo1) Lo2 = radians(Lo2) La1 = radians(La1) La2 = radians(La2) # Using the "Haversine formula" D_Lo = Lo2 - Lo1 D_La = La2 - La1 P = sin(D_La / 2)**2 + cos(La1) * cos(La2) * sin(D_Lo / 2)**2 Q = 2 * asin(sqrt(P)) # The radius of earth in Miles. R_Mi = 3963 # Then, we will calculate the result return(Q * R_Mi) print ("The distance between New York and Texas is: ", distance_2(La1, La2, Lo1, Lo2), "Miles")
The distance between New York and Texas is: 2503.04243426357 K.M The distance between New York and Texas is: 1556.985899699659 Miles

В этом уроке мы обсудили различные методы расчета расстояния между двумя точками на поверхности земли с помощью библиотеки geopy и показали примеры каждого метода.

Источник

Distance Between Two Geo-Locations in Python

distance between two points based on latitude/longitude

Have you wondered how we calculate distance using longitude and latitude in python? Well, let’s figure it out. In this article, we explore four methods to calculate the distance between two points using latitude and longitude in Python. These methods include the Haversine formula, Math module, Geodesic distance, and Great Circle formula. Each method has its own implementation and advantages in various applications.

Code Implementation to Find Distance Between Two Locations using Latitude and Longitude

To calculate the distance between two points based on latitude and longitude in Python, you can use various methods such as the Haversine formula, math module, geodesic distance, or the great circle distance. These calculations are useful in applications involving location-based data, such as navigation, mapping, geolocation, tracking, logistics, delivery, outdoor activities, and research.

Let’s get right into the implementation now.

Distance

Example 1: Using Haversine Formula

The Haversine formula is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical triangles. It’s used to calculate the shortest distance between two points on the Earth’s surface. It provides good accuracy for small distances.

import haversine as hs from haversine import Unit loc1=(19.0760, 72.8777) loc2=(18.5204, 73.8567) result=hs.haversine(loc1,loc2,unit=Unit.KILOMETERS) print("The distance calculated is:",result)

We would be using haversine module to use the haversine formula which would be utilized to calculate the distance between two locations. This module is imported by its alias hs with that we also import Unit to later change the unit of result according to our preference eg meters, kilometers, or miles. In loc1 we mention Mumbai’s coordinates and in loc2 Pune’s coordinates. After calculating the distance using hs.haversine() we store it in variable result .And later print it.

Note: To install the haversine module use this command in the command prompt : pip install haversine

The distance calculated is : 120.15246793062427

Example 2: Using Math Module

This method uses the spherical law of cosines, which is a trigonometric formula that calculates the great-circle distance between two points on the Earth’s surface. It’s simpler than Haversine but may be less accurate for long distances due to floating-point rounding errors.

from math import radians, sin, cos, acos print("Input coordinates of two points:") mlat = radians(float(input("Location 1 latitude: "))) mlon = radians(float(input("Location 2 longitude: "))) plat = radians(float(input("Location 1latitude: "))) plon = radians(float(input("Location 2 longitude: "))) dist = 6371.01 * acos(sin(mlat)*sin(plat) + cos(mlat)*cos(plat)*cos(mlon - plon)) print("The distance is %.2fkm." % dist)

In this method, we use the math module to calculate the distance between two points using their latitude and longitude coordinates.

We convert the coordinates from degrees to radians and use the sine and cosine functions along with the Earth’s mean radius (6371.01 km) to calculate the distance. The acos() function is used to compute the arccosine of the central angle between the two locations.

  • sin(mlat) is the sine of the latitude of a location m
  • sin(plat) is the sine of the latitude of another location p
  • cos(mlat) is the cosine of the latitude of location m
  • cos(plat) is the cosine of the latitude of location p
  • cos(mlon — plon) is the cosine of the difference between the longitudes of the two locations
  • The expression (sin(mlat)*sin(plat) + cos(mlat)*cos(plat)*cos(mlon — plon)) calculates the cosine of the central angle between the two locations
  • acos() is used to calculate the arccosine of the central angle
  • 6371.01 is the mean radius of the Earth in kilometers.

Math Output

Example 3: Using Geodesic Distance

The geodesic method uses the geodesic distance, which is the shortest path between two points along the Earth’s surface. It is more accurate than the Haversine and spherical law of cosines methods, as it accounts for the Earth’s ellipsoidal shape. The Geopy library provides an easy-to-use implementation of this method.

from geopy.distance import geodesic as GD Mumbai =(19.0760, 72.8777) Pune =(18.5204, 73.8567) print("The distance between Mumbai and Pune is: ", GD(Mumbai,Pune).km)

We import geodesic module from geopy library to assist us in calculating the distance. After mentioning the coordinates of locations we use GD() function to calculate the distance.

Geodisc Output

Example 4: Using Great Circle Formula

The great-circle distance is the shortest distance between two points on the surface of a sphere. The great-circle formula is derived from the spherical law of cosines, but with some optimizations for better accuracy. It is a simpler alternative to the geodesic method but may not be as accurate for very long distances or locations near the poles. The Geopy library also provides an implementation of the great-circle distance calculation through the great_circle function.

from geopy.distance import great_circle as GRC Mumbai =(19.0760, 72.8777) Pune =(18.5204, 73.8567) print("The distance between Mumbai and Pune is: ", GRC(Mumbai,Pune).km)

This code is similar to the one before used the only difference is the function used, here we use GRC() function.

Grc Output

Conclusion

We’ve explored four methods to calculate distances between two points using latitude and longitude in Python. These techniques have numerous applications in navigation, mapping, geolocation, logistics, outdoor activities, and research. Which method do you find most suitable for your use case?

Read more interesting articles:

Источник

Finding distance between two latitudes and longitudes in Python

Feature engineering distance from geographic coordinates

When preparing data for a model, there may be a time where it’s useful to find distances between two locations. This post shows how to find the shortest spherical and travel distance between two locations from their latitude and longitude in Python.

🌐 Geographic coordinates

We can locate any place on earth from its geographic coordinates. Geographic coordinates of a location consist of its latitude and longitude position.

📍 Latitude

Latitude is a measurement of the vertical position between North Pole and South Pole. Imaginary horizontal latitude lines are called parallels. Equator is a special parallel that is at 0° latitude and lies halfway between and North Pole and South Pole.

📍 Longitude

Longitude is a measurement of the horizontal position. Imaginary vertical longitude lines are called meridians. The Prime Meridian is a special meridian that is at 0° longitude. Longitudes are also important when it comes to time zones.

Parallels are like a ring whereas meridians are like a half a ring.

📦 Setup

We will import the libraries and set two sample location coordinates in Melbourne, Australia:

import numpy as np
import pandas as pd
from math import radians, cos, sin, asin, acos, sqrt, pi
from geopy import distance
from geopy.geocoders import Nominatim
import osmnx as ox
import networkx as nx
lat1, lon1 = -37.82120, 144.96441 #…

Источник

Оцените статью