Skip to content

Instantly share code, notes, and snippets.

@gboone gboone/midpoint
Created Nov 28, 2015

Embed
What would you like to do?
How to find a geographic midpoint in js
function setLatLng(dataset) {
var lat = dataset.lat
var lng = dataset.lng
return new L.LatLng(lat, lng)
}
function latLngRadians(dataset) {
return _.map(dataset, function(item) {
var latRad = item.lat*(Math.PI/180)
var lngRad = item.lng*(Math.PI/180)
return [latRad, lngRad]
})
}
function radToCart(radians) {
var cartesian = []
_.each(radians, function(coordinate) {
var cartesianLat = Math.cos(coordinate[0]) * Math.cos(coordinate[1]);
var cartesianLng = Math.cos(coordinate[0]) * Math.sin(coordinate[1]);
var sineLat = Math.sin(coordinate[0]);
cartesian.push({"x":cartesianLat, "y":cartesianLng, "z":sineLat})
})
return cartesian
}
function geoMidpoint(coordinates) {
var carts = radToCart(coordinates);
var allX = _.map(carts, function(cart) {
return cart.x
})
var meanX = allX.reduce(function(p, c, i, a) {
return (p + c)/a.length
})
var allY = _.map(carts, function(cart) {
return cart.y
})
var meanY = allY.reduce(function(p, c, i, a) {
return (p + c)/a.length
})
var allZ = _.map(carts, function(cart) {
return cart.z
})
var meanZ = allZ.reduce(function(p, c, i, a) {
return (p + c)/a.length
})
var midpoint = [meanX, meanY, meanZ]
var lon = Math.atan2(meanY, meanX)
var hyp = Math.sqrt(meanX * meanX + meanY * meanY)
var lat = Math.atan2(meanZ, hyp)
lat = lat*(180/Math.PI)
lon = lon*(180/Math.PI)
midpoint = [lat, lon]
return midpoint
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.