Nearest places from a certain point - postgresql

I have the following table
create table places(lat_lng point, place_name varchar(50));
insert into places values (POINT(-126.4, 45.32), 'Food Bar');
What should be the query to get all places close to particular lat/long?
gis is installed.

If you actually wanted to use PostGIS:
create table places(
lat_lng geography(Point,4326),
place_name varchar(50)
);
-- Two ways to make a geography point
insert into places values (ST_MakePoint(-126.4, 45.32), 'Food Bar1');
insert into places values ('POINT(-126.4 45.32)', 'Food Bar2');
-- Spatial index
create index places_lat_lng_idx on places using gist(lat_lng);
Now to find all of the places within 1 km (or 1000 m):
select *, ST_Distance(lat_lng, ST_MakePoint(-126.4, 45.32)::geography)
from places
where ST_DWithin(lat_lng, ST_MakePoint(-126.4, 45.32)::geography, 1000)
order by ST_Distance(lat_lng, ST_MakePoint(-126.4, 45.32)::geography);

select *
from places
where lat_lng <-> POINT(-125.4, 46.32) < 1
order by lat_lng <-> POINT(-125.4, 46.32)

Create an Indexing on a location field :
CREATE INDEX ON table_name USING GIST(location);
GiST index is capable of optimizing “nearest-neighbor” search :
SELECT * FROM table_name ORDER BY location <-> point '(-74.013, 40.711)' LIMIT 10;
Note: The point first element is longitude and the second element is latitude.

Related

What is wrong with my ST_Within query - query result contains point twice although it exists only once

I have two point tables, tab_1 and tab_2. I want to query all points from the first table that are probably the same points from the table 2. So i give the points from table 2 a buffer. Then I want to get the points from table 1 and query from table 2 within a 30 m buffer. My problem is, I get the points from table 1 and table 2 twice. But point 1 from table 1 exists only once and point 1 from table 2 also only once.
My query is:
with
"points1" as
(
select id, geom from tab_1
)
,
"points2" as
(
select id, geom from tab_2
)
select "points1".*, "points2".* from "points1", "points2"
where
st_within(st_transform("points1".geom, 31468), st_buffer(st_transform("points2".geom, 31468), 30)) = true;
id_tab1
geom
id_tab2
geom
st_distance
767074270
POINT (11.6968379 48.132722)
16455
POINT (11.69707 48.13265)
19.041083533921977
767074270
POINT (11.6968379 48.132722)
16455
POINT (11.69707 48.13265)
19.041083533921977
The query should be give only one result:
id_tab1
geom
id_tab2
geom
st_distance
767074270
POINT (11.6968379 48.132722)
16455
POINT (11.69707 48.13265)
19.041083533921977
Is my query wrong?
STEP 1. Query
SELECT *
FROM tab_1
JOIN tab_2
ON ST_DWithin
( ST_Transform(tab_1.geom, 31468)
, ST_Transform(tab_2.geom, 31468)
, 30
)
STEP 2. Spatial index
Most likely, the query cannot use the spatial index (even if it exists) and the function ST_DWithin() properly (ST_Transform() does not allow using an existing spatial index).
Solution - create new spatial indexes for EPSG:31468
CREATE
INDEX tab_1_geom_31468_idx
ON tab_1
USING GIST (ST_Transform(geom, 31468))
;
CREATE
INDEX tab_2_geom_31468_idx
ON tab_2
USING GIST (ST_Transform(geom, 31468))
;

Indexing issue in postgres

It is impossible to speed up the database due to indexing.
I create a table:
CREATE TABLE IF NOT EXISTS coordinate( Id serial primary key,
Lat DECIMAL(9,6),
Lon DECIMAL(9,6));
After that I add indexing:
CREATE INDEX indeLat ON coordinate(Lat);
CREATE INDEX indeLon ON coordinate(Lon);
Then the table is filled in:
INSERT INTO coordinate (Lat, Lon) VALUES(48.685444, 44.474254);
Fill in 100k random coordinates.
Now I need to return all coordinates that are included in a radius of N km from a given coordinate.
SELECT id, Lat, Lon
FROM coordinate
WHERE acos(sin(radians(48.704578))*sin(radians(Lat)) + cos(radians(48.704578))*cos(radians(Lat))*cos(radians(Lon)-radians(44.507112))) * 6371 < 50;
The test execution time is approximately 0.2 seconds, and if you do not do CREATE INDEX, the time does not change. I suspect that there is an error in the request, maybe you need to rebuild it somehow?
I'm sorry for my english
An index can only be used if the indexed expression is exactly what you have on the non-constant side of the operator. That is obviously not the case here.
For operations like this, you need to use the PostGIS extension. Then you can define a table like:
CREATE TABLE coordinate (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
p geography NOT NULL
);
and query like this:
SELECT id, p
FROM coordinate
WHERE ST_DWithin(p, 'POINT(48.704578 44.507112)'::geography, 50);
This index would speed up the query:
CREATE INDEX ON coordinate USING gist (p);

Postgis nearest coordinates

I'm trying to make a REST service that returns a list of places ordered by distance from the user coordinate. I found this query using postgis:
SELECT *
FROM your_table
ORDER BY your_table.geom <-> "your location..."
LIMIT 5;
But I'm not able to apply this to my actual database. I have a table that contains these columns:
title, address, description, latitude, longitude
all these values as Strings.
I'll be very happy if someone help me. Thx!
I dont know why, but ORDER BY <-> isnt exact. Sometime the closest link is on the 3rd position. So I get 101 element and then use distance to selected the closest one.
CREATE OR REPLACE FUNCTION map.get_near_link(
x numeric,
y numeric)
RETURNS TABLE(Link_ID int, distance int) AS
$BODY$
DECLARE
strPoint text;
BEGIN
strPoint = 'POINT('|| X || ' ' || Y || ')';
With CTE AS (
SELECT Link_ID,
TRUNC(ST_Distance(ST_GeomFromText(strPoint,4326), geom )*100000)::integer as distance
FROM map.vzla_seg S
ORDER BY
geom <-> ST_GeomFromText(strPoint, 4326)
LIMIT 101
)
SELECT *
FROM CTE
ORDER BY distance
LIMIT 5
In order to use PostGIS you have to enable the extension in the database. Ideally, you just run the CREATE EXTENSION postgis; command and it works. NOTE form the install page: DO NOT INSTALL it in the database called postgres. For more information visit the site.
Adding a geometry column (spatial data can be stored in this type of columns) to your table:
SELECT AddGeometryColumn(
'your_schema',
'your_table',
'geom', -- name of the column
4326, -- SRID, for GPS coordinates you can use this, for more information https://en.wikipedia.org/wiki/Spatial_reference_system
'POINT', -- type of geometry eg. POINT, POLYGON etc.
2 -- number of dimension (2 xy - 3 xyz)
);
UPDATE yourtable t SET t.geom = ST_SetSRID(ST_MakePoint(t.x, t.y), 4326)
-- the x and y is the latitude and longitude
Now you can use spatial queries on your table like this:
SELECT
*
FROM
your_table
ORDER BY
your_table.geom <-> ST_SetSRID(ST_MakePoint(x, y), 4326)
LIMIT 5;
NOTE: as others mentioned, below PostgreSQL 9.5 <-> isn't always reliable.

Using PostGIS for location based data

I have a table in postgresql 9.2 that stores the latitude and longitude of locations as integer values.
I intend to do something like when a user searches for a location, he also gets information on other locations that are within a 7 mile radius of that searched location.
How do i use postGIS for this since i am new to it. Any idea.?
You'll actually want to store the latitude and longitude as a point.
CREATE TABLE postal_codes
(
zip character varying(7) NOT NULL,
state character(2) NOT NULL,
city character varying(50) NOT NULL,
geoloc geography(Point,4326) NOT NULL
);
INSERT INTO postal_codes
VALUES (
'35004', 'AL', 'Moody',
ST_GeographyFromText('SRID=4326;POINT(-86.50249 33.606379)') -- lon lat
);
You can then get all points within a certain distance using STDWithin.
SELECT geoloc
FROM postal_codes
WHERE ST_DWithin(
geoloc, -- The current point being evaluated
'thegeolocyoustoredawaysomewhere', -- the location of the person
-- you're giving info to
7 * 1.6 * 1000 -- Miles to meters
);
Or:
SELECT geoloc
FROM postal_codes
WHERE ST_DWithin(
geoloc,
(
SELECT geoloc
FROM postal_codes
WHERE zip = '12345'
),
7 * 1.6 * 1000
);
To boost performance a bit for other kinds of queries (not any seen here), use a GiST index:
CREATE INDEX geoloc_idx
ON postal_codes
USING gist (geoloc);

Simultaneous selecting from tables and functions which use values from these tables

I have 3 tables: lightnings, powerlines, masts.
The main fields:
lightnings.geo_belief - an ellipse of a probable hitting.
powerlines.geo_path - a geo polyline of powerline's path.
masts.geo_coordinates - a geo point of a mast placing.
The task:
To calculate lightning strokes that hit powerline's corridor (5000
meters - its radius, and it is generated as a geometry by function
powerline_corridor())
To get info about a powerline's mast, nearest to a respective lightning hit and to get the distance from lightning.geo_ellipse to masts.geo_coordinates.
So I can select lightnings:
SELECT l.*
FROM lightnings l
JOIN ( SELECT geo_path, powerline_corridor(geo_path, 5000::smallint) AS geo_zone
FROM powerlines WHERE id=1)
AS by_pl
ON ST_Intersects(by_pl.geo_zone, l.geo_belief)
Also I have got the function namos_nearest_mast(powerlines.id, lightnings.geo_belief):
CREATE OR REPLACE FUNCTION public.namos_nearest_mast (
powerline_id integer,
geo public.geometry
)
RETURNS public.obj_powerline_masts AS
$body$
SELECT *
FROM obj_powerline_masts
WHERE powerline_id=$1
ORDER BY $2 <-> geo_coordinates ASC
LIMIT 1
$body$
LANGUAGE 'sql';
Couldn't you suggest good solutions for selecting?
Following is all I've done by myself:
SELECT
t.*,
ROUND(st_distance(namos_transform_meters(m.geo_coordinates), namos_transform_meters(t.geo_belief))) AS dist_m
FROM obj_powerline_masts AS m
JOIN
(
SELECT
l.*,
(SELECT id FROM nearest_mast(1, l.geo_belief)) AS mast_id
FROM lightnings l
JOIN (SELECT geo_path, powerline_corridor(geo_path, 5000::smallint) AS geo_zone FROM powerlines WHERE id=1) AS by_pl ON ST_Intersects(by_pl.geo_zone, l.geo_belief)
LIMIT 50 OFFSET 50
) AS t
ON t.mast_id=m.id
But I'm not sure if it's an optimal solution. For instance, in PHP I can't apply dataProviders on such queries (which abstracts e.g. working with pagination), because of we can't affect on subqueries in a trivial way.