【问题标题】:Get points within a certain radius获取一定半径内的点
【发布时间】:2018-02-10 13:48:59
【问题描述】:

我在 PostgreSQL 中有一个纬度和经度列。我想获得一定半径内的所有点。我知道他们是可以实现这一目标的库和扩展,但我想手动完成。 这是我从数据库中获取纬度和经度所做的:

lat1 = Places.query.with_entities(Places.latitude).all()
lon1 = Places.query.with_entities(Places.longitude).all()

接下来我编写了一个函数来将纬度和经度转换为以公里为单位的距离:

result = []
for i in range(len(lat1)):

    x = Decimal(111.12) * (Decimal(28.616700) - lat1[i]['latitude'])
    y = Decimal(111.12) * (Decimal(77.216700) - lon1[i]['longitude']) * Decimal(
    cos(lat1[i]['latitude'])) / Decimal(92.215)
    result.append(sqrt(x * x + y * y))
print result

如何在这个函数中包含我想要的点的半径。另外,lat1 和 lon1 的输出看起来像这样:

{u'latitude': Decimal('28.633300')}

我发现很难转换并不断出错:

TypeError: unsupported operand type(s) for -: 'float' and 'list'

我为 lat1lat1 和 lon1lon1 创建了一个 pastebin,以显示 lat1 和 lon1 的确切输出。

【问题讨论】:

  • lon1 查询应该引用 Places.longitude 否?
  • 改变了。但这不会导致问题
  • lat1 是列表吗?
  • @Skyler 这是一个字典
  • @RaghavPatnecha 是的,但它有助于清除这些问题的小东西。如果正确答案出现,请务必接受并投票。

标签: python postgresql python-2.7 flask-sqlalchemy


【解决方案1】:

您的 lat1 和 lon1 是字典列表。因此,当您访问它们的实际值时,请在循环中执行以下操作,

result = []
for i in range(len(lat1)):
    x = Decimal(111.12) * (Decimal(28.616700) - lat1[i]['latitude']);
    y = Decimal(111.12) * (Decimal(77.216700) - lon1[i]['longitude']) * Decimal(math.cos(lat1[i]['latitude'])) / Decimal(92.215);
    result.append(math.sqrt(x * x + y * y));

以下是示例案例的控制台输出,

>>> lat1=[{u'latitude': Decimal('28.633300')}]
>>> lon1=[{u'longitude': Decimal('28.633300')}]
>>> x = Decimal(111.12) * (Decimal(28.616700) - lat1[0]['latitude']);
>>> y = Decimal(111.12) * (Decimal(77.216700) - lon1[0]['longitude']) * Decimal(math.cos(lat1[0]['latitude'])) / Decimal(92.215);
>>> result = math.sqrt(x * x + y * y);
>>> result
54.84298321157983

【讨论】:

  • TypeError: 列表索引必须是整数,而不是 dict 。明白了
  • 你能用我的 lat1 和 lon1 的 pastebin 输出来验证你的答案吗
  • 我更新了答案请看@RaghavPatnecha
  • 你的工作正常。但是当我尝试迭代时,我得到了一个错误。检查我的代码我已经根据你的回答编辑了它
  • 什么是output?不应该是len(lat1)。您还想用 lon1[i] 和 lat1[i] 替换 lon1[0]、lat1[0]。查看我的更新答案
猜你喜欢
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 2019-07-29
  • 2013-08-30
  • 2017-04-13
相关资源
最近更新 更多