问题
用户可以提供最多四个纬度和经度坐标,任意顺序。他们使用 Google Maps 提供这些坐标。使用 Google 的 Polygon
API(v3),他们选择的坐标应该突出显示所选区域。
问题
如何按(逆)时针顺序排序一个纬度和经度坐标数组?
解决方法和搜索
StackOverflow问题
相关网站
- 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
已知算法
- Graham's scan (过于复杂)
- Jarvis March 算法(处理 N 个点)
- 递归凸包(删除一个点)
代码
这是我目前的代码:
// 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;
}
谢谢您。
d
位于顶部,其次是g,h,e,f,c,b,a
。原始要求并不是非常精确:OP还提到了“凸包”,但那与此无关。我知道的是,OP说:“...正是我想要实现的”,并接受了这个答案作为正确的答案。 - Bart Kiers