3d distance calculations with GeoDjango

后端 未结 2 1925
眼角桃花
眼角桃花 2020-12-19 21:10

I am using

  • python 2.7.12
  • django 1.10.6
  • postgreSQL 9.5.6
  • postGIS 2.2.2

First question

I ne

2条回答
  •  悲哀的现实
    2020-12-19 22:01

    Let's break the problem down:

    1. In the Distance class documentation, we can read the following:

      Accepts two geographic fields or expressions and returns the distance between them, as a Distance object.

      So the Distance(p1, p2) returns a Distance object.
      If you do:

      p1 = Instrument.objects.get(pk=151071000).coordinates
      p2 = Instrument.objects.get(pk=151071008).coordinates
      d = Distance(m=p1.distance(p2))
      print d.m
      

      You will get the measurement in meters.

      I would stick with the annotate solution, which seems more solid! (opinionated response)


    1. Distance calculates the 2D distance between two points. In order to get a 3D calculation, you need to create one yourself.
      You can have a look at my method from this question: Calculating distance between two points using latitude longitude and altitude (elevation)

      EDIT 2019: Since the initial answer I have composed a Q&A style example here: How to calculate 3D distance (including altitude) between two points in GeoDjango that uses a far better (and less calculation error-prone) distance calculation between 2 points with altitude.

      In sort:

      We need to calculate the 2D great-circle distance between 2 points using either the Haversine formula or the Vicenty formula and then we can combine it with the difference (delta) in altitude between the 2 points to calculate the Euclidean distance between them as follows:

      dist = sqrt(great_circle((lat_1, lon_1), (lat-2, lon_2).m**2, (alt_1 - alt_2)**2)
      

      The solution assumes that the altitude is in meters and thus converts the great_circle's result into meters as well.


    Leaving this here for comment continuation purposes.

    2. Distance calculates the 2D distance between two points. In order to get a 3D calculation, you need to create one yourself.
    You can have a look at my method from this question: Calculating distance between two points using latitude longitude and altitude (elevation)

    • Let polar_point_1 = (long_1, lat_1, alt_1) and polar_point_2 = (long_2, lat_2, alt_2)

    • Translate each point to it's Cartesian equivalent by utilizing this formula:

      x = alt * cos(lat) * sin(long)
      y = alt * sin(lat)
      z = alt * cos(lat) * cos(long)
      

      and you will have p_1 = (x_1, y_1, z_1) and p_2 = (x_2, y_2, z_2) points respectively.

    • Finally use the Euclidean formula:

      dist = sqrt((x_2-x_1)**2 + (y_2-y_1)**2 + (z_2-z_1)**2)
      

提交回复
热议问题