I am trying to convert a lat / long point to a 2d point so that I can display it on a world image - a projection of a mercator.
I saw various ways to do this and a few questions about the stack overflow - I tried different pieces of code, and although I get the correct longitude to the pixel, the latitude is always off - it seems more reasonable.
I need a formula to account for image size, width, etc.
I tried this piece of code:
double minLat = -85.05112878; double minLong = -180; double maxLat = 85.05112878; double maxLong = 180; // Map image size (in points) Double mapHeight = 768.0; Double mapWidth = 991.0; // Determine the map scale (points per degree) double xScale = mapWidth/ (maxLong - minLong); double yScale = mapHeight / (maxLat - minLat); // position of map image for point double x = (lon - minLong) * xScale; double y = - (lat + minLat) * yScale; System.out.println("final coords: " + x + " " + y);
In the example I'm trying, latitude seems to be off by about 30 pixels. Any help or advice?
Update
Based on this question: Lat / lon to xy
I tried using the provided code, but I still have problems converting the latitude, longitude is ok.
int mapWidth = 991; int mapHeight = 768; double mapLonLeft = -180; double mapLonRight = 180; double mapLonDelta = mapLonRight - mapLonLeft; double mapLatBottom = -85.05112878; double mapLatBottomDegree = mapLatBottom * Math.PI / 180; double worldMapWidth = ((mapWidth / mapLonDelta) * 360) / (2 * Math.PI); double mapOffsetY = (worldMapWidth / 2 * Math.log((1 + Math.sin(mapLatBottomDegree)) / (1 - Math.sin(mapLatBottomDegree)))); double x = (lon - mapLonLeft) * (mapWidth / mapLonDelta); double y = 0.1; if (lat < 0) { lat = lat * Math.PI / 180; y = mapHeight - ((worldMapWidth / 2 * Math.log((1 + Math.sin(lat)) / (1 - Math.sin(lat)))) - mapOffsetY); } else if (lat > 0) { lat = lat * Math.PI / 180; lat = lat * -1; y = mapHeight - ((worldMapWidth / 2 * Math.log((1 + Math.sin(lat)) / (1 - Math.sin(lat)))) - mapOffsetY); System.out.println("y before minus: " + y); y = mapHeight - y; } else { y = mapHeight / 2; } System.out.println(x); System.out.println(y);
When using the source code, if the latitude value is positive, it returned a negative point, so I changed it a bit and tested it with extreme latitudes, which should be point 0 and point 766, it works fine. However, when I try a different ex latitude value: 58.07 (just north of the UK), it displays as northern Spain.
java math maps 2d mercator
drunkmonkey Jan 15 '13 at 1:19 2013-01-15 01:19
source share