Sort latitude and longitude coordinates into clockwise quadrangle

Posted by Dave Jarvis on Stack Overflow See other posts from Stack Overflow or by Dave Jarvis
Published on 2010-05-18T07:21:40Z Indexed on 2010/05/18 7:40 UTC
Read the original article Hit count: 258

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

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.

© Stack Overflow or respective owner

Related posts about coordinates

Related posts about geometry