More

# Calculating distance between latitude and longitude points using python I have a database of 2000 points, which is in CSV format containing latitude and longitude. I want to find the distance between all these points, and then show these points in a map by using pyQGIS; I have seen one example using Fiona but I want to do this in pyQGIS.

I have used following code:

``def offset(iterable): prev = None for elem in iterable: yield prev, elem prev = elem import csv import math def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees). Source: http://gis.stackexchange.com/a/56589/15183 """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2 c = 2 * math.asin(math.sqrt(a)) km = 6367 * c return km with open('1.csv', 'rb') as f1: reader1 = csv.reader(f1) header1 = reader1.next() with open('2.csv', 'rb') as f2: reader2 = csv.reader(f2) header2 = reader2.next() for row1 in offset(header1): for row2 in offset(header2): floats1 = map(float, row1[1:]) floats2 = map(float, row2[1:]) print(floats1) print(floats2) print haversine(floats1,floats1,floats2,floats2)``

Showing error:

``Traceback (most recent call last): File "", line 13, in  IndexError: list index out of range``

My .csv file contains following data with about 2000 data pointt:

``ID LAT LONG 1 12.953578 77.592453 2 12.953511 77.592445 3 12.953145 77.593147 4 12.951835 77.594612``

pseudocode for your problem would be:

``for point1 in csv: for point2 in csv: distance = haversine(point1, point2)``

where haversine is defined as (from e.g. /a/56589/15183) :

``def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees). Source: /a/56589/15183 """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2 c = 2 * math.asin(math.sqrt(a)) km = 6367 * c return km``

… so the full code would be:

``import csv import math def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees). Source: /a/56589/15183 """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2 c = 2 * math.asin(math.sqrt(a)) km = 6367 * c return km with open('1.csv', 'rb') as f1: reader1 = csv.reader(f1, delimiter=";", quoting=csv.QUOTE_NONE) header1 = reader1.next() with open('2.csv', 'rb') as f2: reader2 = csv.reader(f2, delimiter=";", quoting=csv.QUOTE_NONE) header2 = reader2.next() for row1 in reader1: for row2 in reader2: floats1 = map(float, row1[1:]) floats2 = map(float, row2[1:]) print(floats1) print(floats2) print haversine(floats1,floats1,floats2,floats2)``

with the two files 1.csv:

``name;lat;lon NYC;40.58;-74.03``

and 2.csv:

``name;lat;lon Cape Town;-33.90;18.46``

… result checked against http://www.movable-type.co.uk/scripts/latlong.html seems correct.

## Calculating distance between latitude and longitude points using python - Geographic Information Systems

Given latitude and longitude in degrees find the distance between two points on the earth. Image Source : Wikipedia
Examples:

Problem can be solved using Haversine formula:

The great circle distance or the orthodromic distance is the shortest distance between two points on a sphere (or the surface of Earth). In order to use this method, we need to have the co-ordinates of point A and point B.The great circle method is chosen over other methods.
First, convert the latitude and longitude values from decimal degrees to radians. For this divide the values of longitude and latitude of both the points by 180/pi. The value of pi is 22/7. The value of 180/pi is approximately 57.29577951. If we want to calculate the distance between two places in miles, use the value 3, 963, which is the radius of Earth. If we want to calculate the distance between two places in kilometers, use the value 6, 378.8, which is the radius of Earth.

Find the value of the latitude in radians:
Value of Latitude in Radians, lat = Latitude / (180/pi) OR
Value of Latitude in Radians, lat = Latitude / 57.29577951
Find the value of longitude in radians:
Value of Longitude in Radians, long = Longitude / (180/pi) OR
Value of Longitude in Radians, long = Longitude / 57.29577951

Get the co-ordinates of point A in terms of latitude and longitude. Use the above conversion method to convert the values of latitude and longitude in radians. I will call it as lat1 and long1. Do the same for the co-ordinates of Point B and get lat2 and long2.
Now, to get the distance between point A and point B use the following formula:

Distance, d = 3963.0 * arccos[(sin(lat1) * sin(lat2)) + cos(lat1) * cos(lat2) * cos(long2 – long1)]

The obtained distance, d, is in miles. If you want your value to be in units of kilometers, multiple d by 1.609344.
d in kilometers = 1.609344 * d in miles
Thus you can have the shortest distance between two places on Earth using the great circle distance approach.

You've got 4 or 5 or 6 problems:

(2) you are missing some stuff as somebody already mentioned, most probably because

(3) your code is illegible (line far too long, redundant parentheses, 17 pointless instances of "math.")

(4) you didn't notice the remark in the Wikipedia article about using atan2()

(5) You may have been swapping lat and lon when entering your coordinates

(6) delta(latitude) is computed unnecessarily it doesn't appear in the formula

## PL-SQL – Calculating distance between two geographical points (coordinates based)

This is the first contribution of this blog to PL-SQL community, actually this is a tribute to my great friend Itagyba Abondanza Kuhlman, author of this source code, please visit his blog at http://blog.iak.com.br/ There are a lot of curiosities about the Oracle Database World, his specialty. He is one of those people who came to this planet to the mission of helping humanity to evolve, developing critical thinking, friendship, thinking of things never before thought, leaving wherever he goes a trail of good feelings. Thank You Gyba.

The purpose of this code is to calculate the distance (in Kilometers) between two geographical points using mathematics, specifically trigonometry.

## Haversine formula:

Central angle Haversine can be computed, between two points with r as radius of earth, d as the distance between two points, is latitude of two points and is longitude of two points respectively, as:  ### Law of Haversine:

To derive law of Haversine one needs to start the calculation with spherical law of cosine i.e cos a = cos b * cos c + sin b * sin c * cos A

One can derive Haversine formula to calculate distance between two as:

a = sin²(ΔlatDifference/2) + cos(lat1).cos(lt2).sin²(ΔlonDifference/2)
c = 2.atan2(√a, √(1−a))
d = R.c

ΔlatDifference = lat1 – lat2 (difference of latitude)

ΔlonDifference = lon1 – lon2 (difference of longitude)

R is radius of earth i.e 6371 KM or 3961 miles

and d is the distance computed between two points.

### Here is the example result delivered by Haversine Formula:

Lets take one of latitude-longitude for calculation distance,
NEBRASKA, USA (Latitude : 41.507483, longitude : -99.436554) and
KANSAS, USA (Latitude : 38.504048, Longitude : -98.315949)

Do compute the distance with the above written formula. Your answer would be 347.3 Km(kilo-meter). The snapshot demonstrate the same result with map below.

• You can also find the Tool to calculate the distance between two points on earth and display on Google map.
• Also do see the tutorial for how to make your own customization Google map.
• You can also check for JavaScript code for Haversine formula.

If you are getting problem in understanding Haversine formula or getting error in the result do comment below. Also if you have more relevant information about the same, do share with us by writing below.

## Calculate Distance Between GPS Points in Python

When working with GPS, it is sometimes helpful to calculate distances between points. But simple Euclidean distance doesn’t cut it since we have to deal with a sphere, or an oblate spheroid to be exact. So we have to take a look at geodesic distances.

There are various ways to handle this calculation problem. For example there is the Great-circle distance, which is the shortest distance between two points on the surface of a sphere. Another similar way to measure distances is by using the Haversine formula, which takes the equation

egin a = hav(Deltavarphi) + cos(varphi_1) cdot cos(varphi_2) cdot hav(Deltalambda) end

and takes this to calculate the geodesic distance

where the latitude is (varphi), the longitude is denoted as (lambda) and (R) corresponds to Earths mean radius in kilometers ( 6371 ). We can take this formula now and translate it into Python

Important to note is that we have to take the radians of the longitude and latitude values. We can take this function now and apply distances to different cities. Lets say we want to calculate the distances from London to some other cities.

This already gives us some seemingly accurate result, but let’s compare it to another method.

You can also use geopy to measure distances. This package has many different methods for calculating distances, but it uses the Vincenty’s formulae as default, which is a more exact way to calculate distances on earth since it takes into account that the earth is, as previously mentioned, an oblate spheroid. The Vincenty’s formulae is well described in this article.

As you can see, there is a difference between the values, especially since we work with very large distances, which enhances the distortion of our spheroid-shaped Earth.

There is also the pyproj Python package, which offers Python interfaces to PROJ.4. It is a great package to work with map projections, but in there you have also the Geod class which offers various geodesic computations. To calculate the distance between two points we use the inv function, which calculates an inverse transformation and returns forward and back azimuths and distance.

On a geographic sidenote, the forward azimuth is the direction which is defined as a horizontal angle measured clockwise from a north base line and a back azimuth is the opposite direction of the forward azimuth. You could use this information for example to sail the ocean if this is what you intend.

Thank you for the great website.
How much error is generated in the bearing calculation as a result of using an average radius of the earth? For coordinates separated by no more than 500 miles, is the Haversine formula the best?
Thank you,
Gary

A submarine cable will be extended between two cities I and J that located on both sides of a sea and have the following geodetic coordinates: I (34°55´N, 56°10´E) J (33°56´N, 130°48´E) R = 3671 km.
i) The minimum cable length in kilometers. 5
ii) The direction or azimuth that should be extended this cable from point I.