我如何排序的坐标列表逆时针矩形? [英] How can I sort a coordinate list for a rectangle counterclockwise?

查看:1020
本文介绍了我如何排序的坐标列表逆时针矩形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个坐标列表为矩形整理逆时针,使东北角的第一个坐标。这些地理坐标(即经度,纬度)十进制形式。 1

I need to sort a coordinate list for a rectangle counterclockwise, and make the north-east corner the first coordinate. These are geographic coordinates (i.e. Longitude, Latitude) in decimal form.1

例如,这里有4个角的矩形的,从西北角落,顺时针方向:

For example, here are the 4 corners of a rectangle, starting with the north-west corner and moving clockwise:

[
  { "lat": 34.495239, "lng": -118.127747 }, # north-west
  { "lat": 34.495239, "lng": -117.147217 }, # north-east
  { "lat": 34.095174, "lng": -117.147217 }, # south-east
  { "lat": 34.095174, "lng": -118.127747 }  # south-west
]

我需要梳理这些逆时针和改变锚/起点是东北:

I need to sort these counterclockwise and change the "anchor"/starting point to be north-east:

[
  { "lat": 34.495239, "lng": -117.147217 }, # north-east
  { "lat": 34.495239, "lng": -118.127747 }, # north-west
  { "lat": 34.095174, "lng": -118.127747 }, # south-west
  { "lat": 34.095174, "lng": -117.147217 }  # south-east
]

我不知道什么样的顺序名单将在最初(即顺时针或逆时针)。我不知道哪个角落里重新presents列表中的第一个坐标。

I do not know what order the list will be in initially (i.e. clockwise or counterclockwise). I do not know which corner the first coordinate in the list represents.


1 <子>这不是在映射到地球表面,但因为我有两个相对的角落,我呼吁它的可读性矩形真正的矩形。形状包装+ 180 / -180经度或+ 90 / -90纬度是不是一个问题。

推荐答案

解决方案似乎pretty的简单:

solution seems pretty straightforward:

>>> import math
>>> mlat = sum(x['lat'] for x in l) / len(l)
>>> mlng = sum(x['lng'] for x in l) / len(l)
>>> def algo(x):
    return (math.atan2(x['lat'] - mlat, x['lng'] - mlng) + 2 * math.pi) % (2*math.pi)

>>> l.sort(key=algo)

基本上,算法中正常化输入到 [0,二皮] 的空间,这将是自然排序逆时针。注意,操作者%和*操作具有相同的precedence所以括号周围(2 * math.pi)是重要的,以获得有效结果。

basically, algo normalises the input into the [0, 2pi] space and it would be naturally sorted "counter-clockwise". Note that the % operator and the * operator have the same precedence so the parenthesis around (2*math.pi) are important to get a valid result.

这篇关于我如何排序的坐标列表逆时针矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆