Sort latitude and longitude coordinates into clockwise quadrangle
- by Dave Jarvis
Problem
Users can provide up to four latitude and longitude coordinates, in any order. They do so with Google Maps. Using Google's Polygon API (v3), the coordinates they select should highlight the selected area between the four coordinates.
Solutions and Searches
http://stackoverflow.com/questions/242404/sort-four-points-in-clockwise-order
Graham's scan seems too complicated for four coordinates
Sort the coordinates into two arrays (one by latitude, the other longitude) ... then?
Question
How do you sort the coordinates in (counter-)clockwise order, using JavaScript?
Code
Here is what I have so far:
// Ensures the markers are sorted: NW, NE, SE, SW
function sortMarkers() {
var ns = markers.slice( 0 );
var ew = markers.slice( 0 );
ew.sort( function( a, b ) {
if( a.lat() < b.lat() ) {
return -1;
}
else if( a.lat() > b.lat() ) {
return 1;
}
return 0;
});
ns.sort( function( a, b ) {
if( a.lng() < b.lng() ) {
return -1;
}
else if( a.lng() > b.lng() ) {
return 1;
}
return 0;
});
}
What is a better approach?
Thank you.