# Calculating distances using lat-long coordinates

Date: 2016/01/19

These functions can be used to calculate the great circle distance (i.e., the shortest distance across a sphere) between points on the Earth. Function `distance` calculates the distance (to the nearest meter) between two points from latitude and longitude points in decimal degrees (not minutes/seconds). Function `distmat` takes a vector of place names with associated vectors of decimal degree latitudes and longitudes, and returns a matrix with the distance between all of the points. This is very useful for using distance as a predictor of ties in a network, for example.

Disclaimer: The distance calculations here do not account for altitude, so user beware! Also, somewhat different formulae may be more appropriate for different applications.

```
distance <- function(lat1, lon1, lat2, lon2) {
theta = lon1-lon2
dist = acos(pmin(dist, 1))
dist = dist * 180/pi
dist = dist * 60 * 1.1515 * 1609.344
dist = round(dist, 0)
return(dist)
}

distmat <- function(placenames, lats, lons) {
proxmat <- matrix(nrow=length(placenames), ncol=length(placenames))
colnames(proxmat) <-  rownames(proxmat) <- placenames
for (i in 1:length(placenames)) {
for (j in 1:length(placenames)) {
lat1 <- lats[i]
lon1 <- lons[i]
lat2 <- lats[j]
lon2 <- lons[j]
proxmat[i,j] <- distance(lat1, lon1, lat2, lon2)
}
}
return(proxmat)
}

```