how to convert latitude and longitude to pixels - c

I have two sets of Lat and Long values corresponding to two corners of a rectangle (top left and bottom right). I want to load a image in the rectangle and as the user clicks on the locations on the rectangle/image, it should return a latitude and longitude (from the detected pixel's coordinates). What should be the calculation to convert pixels to lat and long, given the above spot of inputs.

You should know what geodetic projection has been used to create that map and how rectangular coordinates correspond to geographic ones.
For small map pieces you can use linear approximation, so coordinates might be calculated with linear interpolation.
Example for x-coordinate and longitude:
Lon = LonLeft + X * (LonRight - LonLeft) / Width

Assuming linear interpolation is good enough for your purposes, you can use following formula:
out = (in - inMin) * (outMax - outMin) / (inMax - inMin) + outMin
where in* are image coordinates and out* are map coordinates.
You have to use formula twice; once for horizontal and once for vertical coordinate.

Related

Display sun position with Expo and Three.js

So the idea is quite simple: given the sun's position (azimuth and elevation) I want my app to be able to display a shape using augmented reality when the camera is pointing at the sun.
So there is a few steps:
Convert azimuth and elevation into radians, then into cartesian coordinates to get a simple vector {x, y, z}.
Get the phone's gyroscope data to get its orientation in space as a 3D vector {x, y, z}.
Calculate new coordinates for the sun regarding the phone orientation.
Display a random shape using Three.js at these coordinates.
1 and 2 are quite easy. There are a lot of APIs out there giving the sun's position depending on a location. Then I used a formula to convert the sun's spherical coordinates into cartesian ones:
x = R * cos(ϕ) * sin(θ)
y = R * cos(ϕ) * cos(θ)
z = R * sin(ϕ)
with R, the distance of the point from the origin, θ (the azimuth) and ϕ (the elevation).
I got the device's orientation in space with Expo.io, using their Device Motion API. Documentation here
I'm really struggling with the third step. I don't know how to combine sun and device coordinates in space, and project the whole thing through Three.js perspective camera.
I found this post the other day: Compare device 3D orientation with the sun position but I've found the explanations a bit confusing.
Let's say I want to display a cube with Three:
const geometry = new THREE.BoxGeometry(0.07, 0.07, 0.07);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
cube.position.x = 0;
cube.position.y = 0;
cube.position.z = -1;
The final goal here will be to find the correct {x, y, z} so the cube can be displayed at the sun's location. This vector will be of course updated every time the user moves his phone in space.

how to plot 2D intensity plot in matplotlib?

I have an Nx3 array which stores the values in N coordinates. The first and second column correspond to x and y coordinate respectively, and the third column represents the value at that coordinates. I want to plot a 2D intensity plot, what's the best way to do it?
If the coordinates are evenly spaced, then I can use meshgrid and then use imshow, but in my data the coordinates are not evenly spaced. Besides, the array is very large N~100000, and the values (third column) span several orders of magnitude (so I should be using a logplot?). What's the best way to plot such a graph?
You can use griddata to interpolate your data at all 100000 points to a uniform grid (say 100 x 100) and then plot everything with a Log scaling of the colours,
x = data[:,0]
y = data[:,1]
z = data[:,2]
# define grid.
xi = np.linspace(np.min(x),np.max(x),100)
yi = np.linspace(np.min(y),np.max(y),100)
# grid the data.
zi = griddata(x,y,z,xi,yi,interp='linear')
#pcolormesh of interpolated uniform grid with log colormap
plt.pcolormesh(xi,yi,zi,norm=matplotlib.colors.LogNorm())
plt.colormap()
plt.show()
I've not tested this but basic idea should be correct. This has the advantage that you don't need to know your original (large) dataset and can work simply with the grid data xi, yi and zi.
The alternative is to colour a scatterplot,
plt.scatter(x, y, c=z,edgecolors='none', norm=matplotlib.colors.LogNorm())
and turn off the outer edges of the points so they make up a continuous picture.

Map scale factor when converting from Mercator to Equirectangular

Lets say I have a map in Mercator projection, and I know top and bottom latitudes:
topLatitude = 80; bottomLatitude = -55;
I also know width and height of a map:
width = 800; height = 500;
I want to rescale the map to Equirectangular projection, keeping the same width.
How can I calculate new height of a map?
I came up with a solution.
This is formula to calculate x and y of Mercator projected map:
Here is function for y:
function degreesToRadians(degrees){
return degrees / 180 * Math.PI;
}
function mercatorLatitudeToY(latitude){
return Math.log(Math.tan(Math.PI / 4 + degreesToRadians(latitude) / 2));
}
When R=1 the result you get is radians. So I calculate y for top and bottom latitudes.
Next, I calculate the same radians if the projection is Equirectangular - I simply need to convert top and bottom latitude to radians. And last thing - I just need to find aspect ratio of differences:
var scale = (mercatorLatitudeToY(topLatitude) - mercatorLatitudeToY(bottomLatitude))/ (degreesToRadians(topLatitude) - degreesToRadians(bottomLatitude));
For map without Antarctica, aspect ratio is ~1.5

How to solve the cyclicity in a sphere?

I find the neighbor cell of A(lat1, 0)(in (lat, lon) and lon is between 0-360 degrees), search return a point B:(lat2,359).
I want to judge which quadrant is B located in(use A as the original point of coordinates)?
In this problem I have two questions:
1). I can use cross product by the 4-coordinates to judge direction but the (lat2, 359) is in the right direction according to the Rectangular Plane Coordinate System and actually I want the (lat2, -1) instead of (lat2, 359), how to deal with the case?
2). In a sphere within what km can I regard distance as line in stead of great circle?
Thank you!
You can adjust your longitude to a range of -180 to 180. This can be done by adjusting the variable's value as follows:
if (lon > 180.0) lon -= 360.0;
Or by using (lon > 180.0 ? lon - 360.0 : lon) instead of just lon, which leaves the original value of lon intact.
You should probably do the same for the latitude.

WPF: Getting new coordinates after a Rotation

With reference to this programming game I am currently building.
alt text http://img12.imageshack.us/img12/2089/shapetransformationf.jpg
To translate a Canvas in WPF, I am using two Forms: TranslateTransform (to move it), and RotateTransform (to rotate it) [children of the same TransformationGroup]
I can easily get the top left x,y coordinates of a canvas when its not rotated (or rotated at 90deg, since it will be the same), but the problem I am facing is getting the top left (and the other 3 points) coordinates.
This is because when a RotateTransform is applied, the TranslateTransform's X and Y properties are not changed (and thus still indicate that the top-left of the square is like the dotted-square (from the image)
The Canvas is being rotated from its center, so that is its origin.
So how can I get the "new" x and y coordinates of the 4 points after a rotation?
[UPDATE]
alt text http://img25.imageshack.us/img25/8676/shaperotationaltransfor.jpg
I have found a way to find the top-left coordinates after a rotation (as you can see from the new image) by adding the OffsetX and OffsetY from the rotation to the starting X and Y coordinates.
But I'm now having trouble figuring out the rest of the coordinates (the other 3).
With this rotated shape, how can I figure out the x and y coordinates of the remaining 3 corners?
[EDIT]
The points in the 2nd image ARE NOT ACCURATE AND EXACT POINTS. I made the points up with estimates in my head.
[UPDATE] Solution:
First of all, I would like to thank Jason S for that lengthy and Very informative post in which he describes the mathematics behind the whole process; I certainly learned a lot by reading your post and trying out the values.
But I have now found a code snippet (thanks to EugeneZ's mention of TransformBounds) that does exactly what I want:
public Rect GetBounds(FrameworkElement of, FrameworkElement from)
{
// Might throw an exception if of and from are not in the same visual tree
GeneralTransform transform = of.TransformToVisual(from);
return transform.TransformBounds(new Rect(0, 0, of.ActualWidth, of.ActualHeight));
}
Reference: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/86350f19-6457-470e-bde9-66e8970f7059/
If I understand your question right:
given:
shape has corner (x1,y1), center (xc,yc)
rotated shape has corner (x1',y1') after being rotated about center
desired:
how to map any point of the shape (x,y) -> (x',y') by that same rotation
Here's the relevant equations:
(x'-xc) = Kc*(x-xc) - Ks*(y-yc)
(y'-yc) = Ks*(x-xc) + Kc*(y-yc)
where Kc=cos(theta) and Ks=sin(theta) and theta is the angle of counterclockwise rotation. (to verify: if theta=0 this leaves the coordinates unchanged, otherwise if xc=yc=0, it maps (1,0) to (cos(theta),sin(theta)) and (0,1) to (-sin(theta), cos(theta)) . Caveat: this is for coordinate systems where (x,y)=(1,1) is in the upper right quadrant. For yours where it's in the lower right quadrant, theta would be the angle of clockwise rotation rather than counterclockwise rotation.)
If you know the coordinates of your rectangle aligned with the x-y axes, xc would just be the average of the two x-coordinates and yc would just be the average of the two y-coordinates. (in your situation, it's xc=75,yc=85.)
If you know theta, you now have enough information to calculate the new coordinates.
If you don't know theta, you can solve for Kc, Ks. Here's the relevant calculations for your example:
(62-75) = Kc*(50-75) - Ks*(50-85)
(40-85) = Ks*(50-75) + Kc*(50-85)
-13 = -25*Kc + 35*Ks = -25*Kc + 35*Ks
-45 = -25*Ks - 35*Kc = -35*Kc - 25*Ks
which is a system of linear equations that can be solved (exercise for the reader: in MATLAB it's:
[-25 35;-35 -25]\[-13;-45]
to yield, in this case, Kc=1.027, Ks=0.3622 which does NOT make sense (K2 = Kc2 + Ks2 is supposed to equal 1 for a pure rotation; in this case it's K = 1.089) so it's not a pure rotation about the rectangle center, which is what your drawing indicates. Nor does it seem to be a pure rotation about the origin. To check, compare distances from the center of rotation before and after the rotation using the Pythagorean theorem, d2 = deltax2 + deltay2. (for rotation about xc=75,yc=85, distance before is 43.01, distance after is 46.84, the ratio is K=1.089; for rotation about the origin, distance before is 70.71, distance after is 73.78, ratio is 1.043. I could believe ratios of 1.01 or less would arise from coordinate rounding to integers, but this is clearly larger than a roundoff error)
So there's some missing information here. How did you get the numbers (62,40)?
That's the basic gist of the math behind rotations, however.
edit: aha, I didn't realize they were estimates. (pretty close to being realistic, though!)
I use this method:
Point newPoint = rotateTransform.Transform(new Point(oldX, oldY));
where rotateTransform is the instance on which I work and set Angle...etc.
Look at GeneralTransform.TransformBounds() method.
I'm not sure, but is this what you're looking for - rotation of a point in Cartesian coordinate system:
link
You can use Transform.Transform() method on your Point with the same transformations to get a new point to which these transformations were applied.

Resources