F.13. earthdistance
Модуль earthdistance
реализует два разных варианта вычисления ортодромии (расстояния между точками на поверхности Земли). Первый описанный вариант зависит от модуля cube
. Второй вариант основан на встроенном типе данных point
, в котором в качестве координат задаются широта и долгота.
В этом модуле Земля считается идеальной сферой. (Если для вас это слишком грубо, обратите внимание на проект PostGIS.)
Прежде чем устанавливать earthdistance
, вы должны установить модуль cube
(хотя можно воспользоваться указанием CASCADE
команды CREATE EXTENSION
и установить сразу оба расширения).
Внимание
Расширения earthdistance
и cube
настоятельно рекомендуется устанавливать в одну схему, и при этом в данной схеме недоверенные пользователи не должны в настоящем и будущем иметь право CREATE. В противном случае, если в схеме earthdistance
окажутся объекты, созданные злонамеренным пользователем, возможна угроза безопасности. Более того, используя функции earthdistance
после установки расширения, следует ограничивать путь поиска только доверенными схемами.
F.13.1. Земные расстояния по кубам
Данные хранятся в кубах, представляющих точки (оба угла куба совпадают) по 3 координатам, выражающим смещения x, y и z от центра Земли. Этот модуль предоставляет домен earth
на базе cube
, включающий проверки того, что значение соответствует этим ограничениям и представляет точку, достаточно близкую к сферической поверхности Земли.
Радиус Земли выдаёт функция earth()
(в метрах). Изменив одну эту функцию, вы можете сделать так, чтобы модуль работал с другими единицами, либо выдать другое значение радиуса, которое кажется вам более подходящим.
Этот пакет может также применяться и для астрономических расчётов. Астрономы обычно меняют функцию earth()
, чтобы она возвращала радиус, равный 180/pi()
, и расстояния в результате выдавались в градусах.
В этом модуле реализованы функции для ввода данных, выражающих широту и долготу (в градусах), для вывода ширины и долготы, для вычисления ортодромии между двумя точками и простого указания окружающего прямоугольника, что полезно для поиска по индексу.
Предоставляемые этим модулем функции показаны в Таблица F.5.
Таблица F.5. Функции земных расстояний по кубам
F.13.2. Земные расстояния по точкам
Вторая часть этого модуля основана на представлении точек на Земле в виде значений типа point
, в которых первый компонент представляет долготу в градусах, а второй — широту. Точки воспринимаются как (долгота, широта), а не наоборот, так как долгота ближе к интуитивному представлению как оси X, а широта — оси Y.
В модуле реализован один оператор, показанный в Таблице F.6.
Таблица F.6. Операторы земных расстояний по точкам
Оператор | Возвращает | Описание |
---|---|---|
point <@> point | float8 | Выдаёт расстояние в сухопутных милях между точками на поверхности Земли. |
Заметьте, что в этой части модуля, в отличие от части, построенной на cube
, единицы зашиты жёстко: изменение функции earth()
не повлияет на результат этого оператора.
Представление в виде долготы/широты плохо тем, что вам придётся учитывать граничные условия возле полюсов и в районе +/- 180 градусов долготы. Представление на базе cube
лишено таких нарушений непрерывности.
F.13. earthdistance
The earthdistance
module provides two different approaches to calculating great circle distances on the surface of the Earth. The one described first depends on the cube
module. The second one is based on the built-in point
data type, using longitude and latitude for the coordinates.
In this module, the Earth is assumed to be perfectly spherical. (If that's too inaccurate for you, you might want to look at the PostGIS project.)
The cube
module must be installed before earthdistance
can be installed (although you can use the CASCADE
option of CREATE EXTENSION
to install both in one command).
Caution
It is strongly recommended that earthdistance
and cube
be installed in the same schema, and that that schema be one for which CREATE privilege has not been and will not be granted to any untrusted users. Otherwise there are installation-time security hazards if earthdistance
's schema contains objects defined by a hostile user. Furthermore, when using earthdistance
's functions after installation, the entire search path should contain only trusted schemas.
F.13.1. Cube-Based Earth Distances
Data is stored in cubes that are points (both corners are the same) using 3 coordinates representing the x, y, and z distance from the center of the Earth. A domain earth
over cube
is provided, which includes constraint checks that the value meets these restrictions and is reasonably close to the actual surface of the Earth.
The radius of the Earth is obtained from the earth()
function. It is given in meters. But by changing this one function you can change the module to use some other units, or to use a different value of the radius that you feel is more appropriate.
This package has applications to astronomical databases as well. Astronomers will probably want to change earth()
to return a radius of 180/pi()
so that distances are in degrees.
Functions are provided to support input in latitude and longitude (in degrees), to support output of latitude and longitude, to calculate the great circle distance between two points and to easily specify a bounding box usable for index searches.
The provided functions are shown in Table F.5.
Table F.5. Cube-Based Earthdistance Functions
F.13.2. Point-Based Earth Distances
The second part of the module relies on representing Earth locations as values of type point
, in which the first component is taken to represent longitude in degrees, and the second component is taken to represent latitude in degrees. Points are taken as (longitude, latitude) and not vice versa because longitude is closer to the intuitive idea of x-axis and latitude to y-axis.
A single operator is provided, shown in Table F.6.
Table F.6. Point-Based Earthdistance Operators
Operator | Returns | Description |
---|---|---|
point <@> point | float8 | Gives the distance in statute miles between two points on the Earth's surface. |
Note that unlike the cube
-based part of the module, units are hardwired here: changing the earth()
function will not affect the results of this operator.
One disadvantage of the longitude/latitude representation is that you need to be careful about the edge conditions near the poles and near +/- 180 degrees of longitude. The cube
-based representation avoids these discontinuities.