Skip to content

Instantly share code, notes, and snippets.

@kylehotchkiss
Created December 15, 2012 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylehotchkiss/4297528 to your computer and use it in GitHub Desktop.
Save kylehotchkiss/4297528 to your computer and use it in GitHub Desktop.
Here's a coordinate midpoint calculator. Useful for displaying maps with lots of points... and centering them better?
<!DOCTYPE html>
<html>
<head>
<title>Coordinate Midpoint Calculator</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var RADIANS = Math.PI / 180;
var DEGREES = 180 / Math.PI;
var midpoint = function( startLat, startLon, endLat, endLon ) {
var distanceLon = ( endLon - startLon ) * RADIANS;
startLat = startLat * RADIANS;
startLon = startLon * RADIANS;
endLat = endLat * RADIANS;
endLon = endLon * RADIANS;
var x = Math.cos(endLat) * Math.cos(distanceLon);
var y = Math.cos(endLat) * Math.sin(distanceLon);
var latitude = (Math.atan2( Math.sin(startLat) + Math.sin(endLat), Math.sqrt( (Math.cos(startLat) + x) * (Math.cos(startLat) + x) + (y * y)))) * DEGREES;
var longitude = ( startLon + Math.atan2( y, Math.cos(startLat) + x )) * DEGREES;
return { latitude: latitude, longitude: longitude };
}
jQuery("document").ready(function() {
jQuery("input").keyup(function() {
var startLat = jQuery("input[name=startLat]").val();
var startLon = jQuery("input[name=startLon]").val();
var endLat = jQuery("input[name=endLat]").val();
var endLon = jQuery("input[name=endLon]").val();
if ( startLat != "" && startLon != "" && endLat != "" && endLon != "" ) {
var point = midpoint(startLat, startLon, endLat, endLon);
jQuery(".result").html(point.latitude + ", " + point.longitude);
} else {
jQuery(".result").html("- - -");
}
});
});
</script>
<style>
input {
display: block;
}
</style>
</head>
<body>
<div class="calculator">
<input type="number" name="startLat" min="-90" max="90" step="any" placeholder="Starting Latitude" />
<input type="number" name="startLon" min="-180" max="180" step="any" placeholder="Starting Longitude" />
<input type="number" name="endLat" min="-90" max="90" step="any" placeholder="Ending Latitude" />
<input type="number" name="endLon" min="-180" max="180" step="any" placeholder="Ending Longitude" />
</div>
<div class="result">- - -</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment