how to use st_intersection() with re-projection in POSTGIS? - postgresql

This is a shipping route from 'portland to busan' and I want to check the route against land_polygons like how much distance is traveled by a route through land.And the problem is while checking the land intersection it consider as if the route is passing through North America,Europe etc. though it is not passing through any land region in real.
SELECT sum(ST_Length(ST_Intersection(route::geography,polygon))) as intersection
FROM land_polygons l,
routes t
where t.route_id = ? and
ST_intersects(route::geometry,geom);
postgis version:
POSTGIS="2.1.7 r13414" GEOS="3.4.2-CAPI-1.8.2 r3921" PROJ="Rel. 4.8.0,
6 March 2012" GDAL="GDAL 1.10.1, released 2013/08/26" LIBXML="2.9.1"
LIBJSON="UNKNOWN" TOPOLOGY RASTER

How is the route being constructed? It looks like it's being constructed until the date-line, and then from that as a straight line to the "next" date-line, to destination.
You should be constructing these routes as great circle distances, between the sea points.
Interesting blogs/answers:
https://gis.stackexchange.com/questions/109562/does-postgis-have-a-vincenty-distance-calculation
https://gis.stackexchange.com/questions/84443/what-is-this-postgis-query-doing-to-show-great-circle-connections
http://anitagraser.com/2011/08/20/visualizing-global-connections/
The key to all of these examples is the use of ST_Segmentize, that will create many vertices along a projected line, virtually "bending" the line.
After the route construction problem is handled (you are indeed connection two points that are not on the route, going over land), use the spheroid distance functions to get an accurate measure.

Related

Calculate distance between two coordinates using postgres?

I´ve got a job offer to work with postgres and I have not much idea of it. The guy told me to build a simple data base which automatically calculates the distance to my house from a list of some other places (bars, pharmacies, museums, whatever...) everything given in geocoordinates.
I have already installed postgres, also postgis and create a data base. May you give me some hints about how I should do this task? Is there any tutorial or resource I could use to make this tasks easier? Should I use postgis?
Thank you.
PostGIS will do this easily. Boundless Geo have an excellent PostGIS tutorial. I also recommend you are familiar with Ch3 & 4 of the PostGIS manual.
I strongly advise you to learn & understand the difference between projected and unprojected coordinates if you're going to be working with spatial data. Projected means the coordinates have been taken from a 'round earth' and adjusted or projected onto to a flat map page (with coordinates normally given in feet or metres depending on the properties of the projection used). This enables computationally efficient normal cartesian calculations to be done for distance, area, direction, intersection, contains etc. There are trade offs for using projections- You can't preserve all of area, distance, shape, direction when you project a curved line or surface onto a flat map. Different projections are optimised for different trade-offs. Calculations on projected data are only accurate over a relatively small portion of the earth's surface. There are many map projections available to suit various needs and localities. If you are going to be working with projected data, you need to pick a projection that suits your purposes and location. If you don't understand projections, your queries can easily produce garbage without realising it.
Unprojected data (ie, raw Lat/Lon coordinates which is what you have) involve much more complicated calculations as they are done on the curved surface of the spheroid representing the earth. There are a number of reference coordinate systems that are used to express Lat/Lon, however the most common is "WGS84" (which is what "GPS" coordinates are expressed in).
PostGIS objects (in the form of "simple features" as defined by the OGC) can be stored as either "geometry" types (projected coordinates) or "geography" types (unprojected Lon/Lat in WGS84: note the order, a common source of confusion!). As a bit of a wrinkle, Lon/Lat (order again!) can also be stored as a "pseudo projected" geometry type (typically with a projection SRID of '4326' for WGS84 Lon/Lat).
The method you use to calculate distance will depend on how you choose to store your points ('geometry' or 'geography').
See ST_Distance from the PostGIS docs for excellent examples of measuring distance using both geometry and geography points. Note, if you wish to calculate projected map distances you will need to pick an appropriate map projection and use ST_Transform to project your points to the appropriate spatial reference system (currently in SRID 4326- "GPS" coordinates). For only a few points the difference won't be at all noticeable, but once you start doing lots of more complex spatial queries, the difference can be significant. PostGIS has a lot more functions for geometry types than for geography types which may influence your decision. Also see ST_DistanceSpheroid for another possibility for calculating distance from Lon/Lat coordinates.
To start with, I'd store your points as 'geography' to simplify your experiments. Your distances will then be 'great circle' calcs in metres and you won't have to worry about projections initially.

Framework for plotting latitude longitude in a map based on country, state and district depending on the zoom level

I need a framework which takes a set of latitude longitude points and plots on a world map, grouped by country having the count of points as a marker on each country. Grouping here is the count of latitude longitude points in a country.
And as I drill down into a country, the clustering should change to state based one. And the next level, to districts.
Leaflet marker cluster is something very similar to what I have asked for, but the grouping is based on proximity and it doesn't consider country or state boundaries. That is, they are not region aware.
Regionbound.com has tweaked in some code in the leaflet code for making it region aware,
Sample marker definition:
var marker1 = new L.marker([-37.8, 145], {regions: ["Asia-Pac", "Australia", "VIC", "Melbourne"]} );
But the sample code says, every latitude longitude must be defined along with some extra parameter containing place information.
I could get the place information using reverse geocoding, but reverse geocoding every latitude longitude is time consuming right.
Highmaps provided by Highcharts is one another solution, but there, every country has code which should be assigned a value[count of point coordinates belonging to that country].
But all I have is latitude longitude points, no country or state information.
Thus, I need something which takes only a set of latitude longitude and does clustering based on country, state, district depending on the zoom level.
You have 2 separate needs in your questions:
Map your lat/lng coordinates to appropriate administrative areas. E.g. through the reverse geocoding that you mention.
Display "clusters" on those administrative areas depending on zoom level.
As for point 1, you know that lat/lng points do not say by themselves which administrative area(s) they belong to. So "reverse geocoding every latitude longitude" is a mandatory step. Whether time consuming or not depends on the solution you choose to perform this operation.
If I understand correctly, you would like a "framework" that could do that automatically for you. But frameworks are usually data agnostic, and if they do not have data about boundaries of those administrative areas, they cannot help you.
You may rather look for "services" (like the Mapbox Geocoding API that you mention) or software that would already have such data. It is not time consuming if you can program the lookup (or perform "bulk" operations) and if you are not limited by the requests rate and your amount of points to map (which may be the case with Mapbox).
You could very well set up your own application to perform this mapping:
As for the dataset for administrative areas boundaries, you would probably be interested in links in this post: Are there any free administrative boundaries available as shapefiles? If your points are limited to a few countries, it will be easier for you to find the appropriate data source(s).
Once you have that data, many GIS software should be capable of mapping your lat/lng points to the areas they belong to. This would be mainly for a "one-shot" operation, if your set of points do not change much.
A "web-compatible" alternative would be for example to use Leaflet with point in polygon for Leaflet plugin. You would need your boundaries data converted to GeoJSON format first. Again, GIS software should be capable of doing so, or many online services as well (search for "convert geojson" for example).
A server-side solution would avoid having to manage the entire boundaries data through network and in client browser (if you need to perform the mapping dynamically). I am sure many GIS servers are capable of performing this operation, once they are fed with the boundaries data.
For point 2, once you have completed the above step, I think you would have many options available, including those you mention (RegionBound, Highmaps).
Even with standard mapping libraries (Leaflet, OpenLayers 3), you would just need to build your "clusters" (markers on administrative areas with a number saying how many points are in there), like you have to do with Highmaps anyway for example.
Computing the number of "clustered" point is as easy as filtering your points per area name / code. Then switch the clusters to the desired administrative level when the map zoom changes.
So the key is really to determine first to which areas your points belong to (point 1).
Then a small question would rise about where to place the "cluster" marker:
On centroid of the administrative area? You need the coordinates of that centroid from your data source, or a good algorithm to compute it from the boundaries (good luck on that…).
On "center" of the bounding box of the area? Leaflet can easily compute that: from your area vector shape, you would do myShape.getBounds().getCenter().
On barycentre / centroid of the clustered points? This is what Leaflet.markercluster and RegionBound do (do not know for Highmaps).
Good luck!

How does routing services for OSM determine the distance between two points

I am going to design an Android application and I will be needing the distances of the pathways inside our university(pathways between buildings)
I read about OSM(OpenStreetMap) and tried it. It is a map which is editable which means anyone can contribute to that map(like a wikipedia map version).
It has many routing services that give routes and directions between two point(start and end).
There is a routing service named GraphHopper and it is very easy to use. I can just drag and drop the start and end pt and it gives the distance(km) between the two pts.
What I want to know is how did they come up with the distance?
Is the distance reliable and accurate?
Any help is greatly appreciated because I want to use the distances for my Android app and I need to know if these distances have basis.
The distance is 'accurate' in the sense that it correctly processes the existing information from OpenStreetMap and correctly adds road segments for the final route. You can just try for your local area and compare to your own knowledge.
There could be mapping errors, where a road is incorrectly mapped. And there could be also roads missing and so the router uses a detour making the path unnecessarily longer. Also there are different modes like for cars or bikes or fastest and shortest where you get a different distance between two coordinates.

Geoserver - How do I draw a geodesic line that represents the great circle between two points

I'm using Geoserver version 2.1.1, Postgres 9 and PostGIS 2.0
What I want to achieve should (i think!) be quite straight forward. I want to render on a map a line that represents the Great Circle between two cities on the earths surface.
My database contains the city locations represented as geography points defined as latitude and lonfitude pairs.
I have a layer defining an SQL view in Geoserver which retrieves a linestring (st_makeline) from the two coordinates for the specified cities. I'm having to type cast the geographies to geometries to get this to work.
But when I draw the returned line on a map what i get is a straight line and not the curved line that I am expecting.
Can someone tell me how I should be going about this?
Thanks!
PostGIS offers mainly "constructors" of the base geometries point, linestring and polygone, like ST_MakeLine.
And what yo uwant to do depends also on the coordinate reference system you use when displaying your map layers.
Here's a nice trick about great circles or parts of:
https://gis.stackexchange.com/questions/5204/curved-point-to-point-route-maps
Yours, Stefan
P.S. Here's some related stuff:
Drawing circles on a sphere
And here's some math:
http://www.mathworks.ch/matlabcentral/newsreader/view_thread/277881
I had a similar problem in cartodb (which also uses PostGIS); I wanted to get curved lines from straight lines. Maybe this post can help.

Calculate nearest point of KML polygon for iPhone app

I have a series of nature reserves that need to be plotted, as polygon overlays, on a map using the coordinates contained within KML data. I’ve found a tutorial on the Apple website for displaying KML overlays on map instances.
The problem is that the reserves vary in size greatly - from a small pond right up to several hundred kilometers in size. As a result I can’t use the coordinates of the center point to find the nearest reserves. Instead I need to calculate the nearest point of the reserves polygon to find the nearest one. With the data in KML - how would I go about trying to achieve this?
I've only managed to find one other person ask this and no one had replied :(
Well, there are a couple different solutions depending on your needs. The higher the accuracy required, the more work required. I like Phil's meanRadius parameter idea. That would give you a rough idea of which polygon is closest and would be pretty easy to calculate. This idea works best if the polygons are "circlish". If the polygon are very irregular in shape, this idea loses it's accuracy.
From a math standpoint, here is what you want to do. Loop through all points of all polygons. Calculate the distance from those points to your current coordinate. Then just keep track of which one is closest. There is one final wrinkle. Imagine a two points making a line segment that is very long. You are located one meter away from the midpoint of the line. Well, the distance to these two points is very large, while, in fact you are very close to the polygon. You will need to calculate the distance from your coordinate to every possible line segment which you can do in a variety of manners which are outlined here:
http://www.worsleyschool.net/science/files/linepoint/distance.html
Finally, you need to ask yourself, am I in any polygons? If you're 10 meters away from a point on a polygon, but are, in fact, inside the polygon, obviously, you need to consider that. The best way to do that is to use a ray casting algorithm:
http://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm