Previous Next JavaScript must be enabled to correctly display this content

## geo_distance

Determines distance between two geospatial objects.

    double geo_distance(any*, any*)

The first and the second parameters `any*` can be any geometric object.

The function returns the geodetic distance between the two input geometries. The returned distance is the minimum among the distances of any pair of points where the first point belongs to the first geometry and the second point to the second geometry. Between two such points, their distance is the length of the geodetic line that connects the points.

Overview of Geodetic Line

A geodetic line between 2 points is the shortest line that can be drawn between the 2 points on the ellipsoidal surface of the earth. For a simplified, but more illustrative definition, assume for a moment that the earth's surface is a sphere. Then, the geodetic line between two points on the earth is the minor arc between the two points on the great circle corresponding to the points, i.e., the circle that is formed by the intersection of the sphere and the plane defined by the center of the earth and the two points.

The following figure shows the difference between the geodetic and straight lines between Los Angeles and London.
Description of the illustration geodetic-vs-straight-line.jpg

If any of the two parameters does not return a single valid geometry object, and if it can be detected at compile time then the function raises an error.

The runtime behavior is as follows:

- Returns -1 if any parameter returns zero or more than 1 item.
- Returns NULL if any parameter returns NULL.
- Returns -1 if any of the parameters is not a geometry object.

Otherwise, the function returns the geodetic distance in meters between the 2 input geometries.

Note:

The results are sorted ascending by distance( displaying the shortest distance first).
Example: How far is the nearest restaurant from the given location?

    SELECT
    t.poi.name AS restaurant_name,
    t.poi.address.street AS street_name,
    geo_distance(
        t.poi.location,
        {
           "type" : "point",
           "coordinates": [-121.94034576416016,37.2812239247177]
        }
    ) AS distance_in_meters
    FROM PointsOfInterest t
    WHERE t.poi.kind = "restaurant" ;

Explanation:

- You query the `PointsOfInterest` table to filter the rows for restaurant.
- You provide the correct location point and determine the distance using the `geo_distance` function.

Result:

    {"restaurant_name":"Coach Sports Bar & Grill","street_name":"80 Edward St","distance_in_meters":799.2645323337218}
    {"restaurant_name":"Ricos Taco","street_name":"80 East Boulevard St","distance_in_meters":976.5361117138553}
    {"restaurant_name":"Effie's Restaurant and Bar","street_name":"80 Woodeard St","distance_in_meters":2891.0508307646282}

The distance between the current location and the nearest restaurant is 799 meters.