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.
Question
How do you sort an array of latitude and longitude coordinates in (counter-)clockwise order?
Solutions and Searches
StackOverflow Questions
- Drawing resizable (not intersecting) polygons
- How to sort points in a Google maps polygon so that lines do not cross?
- Sort Four Points in Clockwise Order
Related Sites
- http://www.daftlogic.com/projects-google-maps-area-calculator-tool.htm
- http://en.literateprograms.org/Quickhull_%28Javascript%29
- http://www.geocodezip.com/map-markers_ConvexHull_Polygon.asp
- http://softsurfer.com/Archive/algorithm_0103/algorithm_0103.htm
Known Algorithms
- Graham’s scan (too complicated)
- Jarvis March algorithm (handles N points)
- Recursive Convex Hull (removes a point)
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.position.lat() < b.position.lat() ) {
return -1;
}
else if( a.position.lat() > b.position.lat() ) {
return 1;
}
return 0;
});
ns.sort( function( a, b ) {
if( a.position.lng() < b.position.lng() ) {
return -1;
}
else if( a.position.lng() > b.position.lng() ) {
return 1;
}
return 0;
});
var nw;
var ne;
var se;
var sw;
if( ew.indexOf( ns[0] ) > 1 ) {
nw = ns[0];
}
else {
ne = ns[0];
}
if( ew.indexOf( ns[1] ) > 1 ) {
nw = ns[1];
}
else {
ne = ns[1];
}
if( ew.indexOf( ns[2] ) > 1 ) {
sw = ns[2];
}
else {
se = ns[2];
}
if( ew.indexOf( ns[3] ) > 1 ) {
sw = ns[3];
}
else {
se = ns[3];
}
markers[0] = nw;
markers[1] = ne;
markers[2] = se;
markers[3] = sw;
}
Thank you.
Given the points:
you want to find the following bound walk:
?
If this is correct, here’s a way:
Here’s a quick demo for the map:
(I know little JavaScript, so I might, or probably have, violated some JavaScript code conventions…):
Note: your should double, or triple check the conversions from
lat,lontox,yas I am a novice if it comes to GIS!!! But perhaps you don’t even need to convert anything. If you don’t, theupperLeftfunction might just return the lowest point instead of the highest, depending on the locations of the points in question. Again: triple check these assumptions!When executing the snippet above, the following gets printed:
Alternate Distance Function