# Make a line from a set of GPS points close to a specific GPS point with PostGIS

I have to develop a map-matching algorithm. At the moment I only match GPS points with the closest road segment. I'm looking for a way to compare the directions between a GPS point and a road to improve the matching. I have already looked at many subjects and I found a way to compare the directions but I've an issue for getting the direction of each GPS point.

I use PostGIS to store and manipulate my data, and I want to compute the azimuth of each GPS point. My problem is to have the set of points which can be used to build a line and calculate the azimuth of this line with:

``````ST_Azimuth(ST_StartPoint(lineBuilt), ST_EndPoint(lineBuilt))
``````

My idea was to take all GPS points inside an area around the current GPS point to build a line and finally give the direction of this line to the current GPS point. My problem is to get the actual GPS point, currentPoint in the query below:

``````SELECT degrees(ST_Azimuth(ST_StartPoint(new_line),ST_EndPoint(new_line)))
FROM
(
SELECT DISTINCT ON(gps.gid) gps.gid, ST_MakeLine(gps.geom ORDER BY gps.gid) AS new_line FROM gps WHERE ST_DWITHIN( currentPoint?, gps.geom, 50)
) AS query;
``````
• What do you mean by " apparently I'm not as good as I should be with SQL to achieve it"? Are you getting an error? Are you getting wrong results? If you say what's wrong with your query it will be much easier for everyone to help you. – Jakub Kania Jul 1 '15 at 12:32
• Thanks for the feedback, I thought that the question mark in the query was explicit enough. Note that I solved my problem by using a function and a FOR loop but this isn't really optimized for a big amount of data (it takes to much time), I would like to know if it's possible to do the same thing with a simple query. – Clem G. Jul 1 '15 at 12:58