Google Maps - Deriving Lat/Lon points - latitude-longitude

I would like to derive the lat/lon which stands x inches east and y inches south from a given lat/lon point.
For this purpose I used information and formulas from the following link: http://www.appelsiini.net/2008/11/introduction-to-marker-clustering-with-google-maps
Basically my methods do the following:
public static double adjustLongitudeByPixels(double longitude, long pixelsY) {
int zoom = 21; // use zoom level 21
double scaledPixels = (pixelsY << (21 - zoom)) / GOOGLE_SCALING_AT_ZOOM_21;
return xToLongitude(longitudeToX(longitude) + scaledPixels);
}
public static double adjustLatitudeByPixels(int overviewScale, double latitude, long pixelsX) {
int zoom = 21; // use zoom level 21
double scaledPixels = (pixelsX << (21 - zoom)) / GOOGLE_SCALING_AT_ZOOM_21;
return yToLatitude(latitudeToY(latitude) + scaledPixels);
}
...where longitude/latitude are the ones from the starting point and the pixels are the number of pixels east or south from the starting point.
I obtain the pixelsX and pixelsY by multiplying my real x/y inch distances by 96 (number of pixels per inch). So I basically obtain the pixels at scaling 1:1.
Since the latitudeToY and longitudeToX use units pixels at zoom level 21, I divide by the scaling at zoom level 21.
If I am not wrong this scaling is 1:282.124305.
This method does not yield the expected results, though. The resulting lat/lon are slightly different than what I expect.
Please let me know if I have flaws in my logic...
Thanks in advance!

Related

Obtaining a quadrilateral from four points then splitting it into two triangles

Given 4 unordered points, how do I obtain two triangles from those points WITHOUT forming an hourglass shape or having the triangles overlap. Convex quadrilaterals are fine, but I'd prefer a method that would remove the point near the center bounded by the other points within a single triangle. I have a semi-working solution, but it isn't pretty. I have previously tried Delaunay triangulation, forming 4 triangles via a center point and moving around it radially adding points to create triangles, amongst other methods. I cannot seem to find any information of this topic besides splitting triangles.
So this is what I did and it seemed to work well. For the first triangle, take the first 3 points and make that a triangle. Then, store a list of the midsections of the points for each edge. The midsection that is closest to the fourth point is on the edge that has the other 2 points that will make your second triangle.
pseudo code
func getMidsection(Point a, Point b) -> Point
{
Point midsection = Point(
(a.x + b.x) / 2,
(a.y + b.y) / 2,
(a.z + b.z) / 2
);
return midsection;
}
func getTrianglesFromPoints(Point[4] points) -> Triangle[2]
{
// define first triangle as first 3 points
Triangle tri1 = Triangle(points[0], points[1], points[2]);
Point[3] midsections;
float recordDist = -1;
int closestMidsection;
// loop through each edge in the first triangle
for(i : [0, 3) )
{
// get the midsection using the current point and next point in the first triangle
midsections[i] = getMidsection(points[i], points[(i+1)%3]);
// if the 4th point's distance to the midsection is smaller than past values, set the smallest dist to that point
if(dist(points[3], midsections[i]) < recordDist or recordDist == -1)
{
recordDist = dist(points[3], midsections[i]);
closestMidsection = i;
}
}
// define triangle2 from the closest midsection
Triangle tri2 = Triangle(points[closestMidsection], points[(closestMidsection + 1) % 3, points[3]);
// return the triangles
return [tri1, tri2];
}

How to teleport a player two block on his left?

I tried several things, like using vectors, but It didn't work for me. Than I tried searching on the internet and it didn't work as well.
Vector direc = l.getDirection().normalize();
direc.setY(l.getY());
direc.normalize();
direc.multiply(-1);
l.add(direc);
Player#teleport(l.getBlock().getLocation());
// or
Player#teleport(l);
Use Vector#rotateAroundY​ to rotate the player's direction vector 90 degrees to the left.
Vector dir = player.getLocation().getDirection(); // get player's direction vector
dir.setY(0).normalize(); // get rid of the y component
dir.rotateAroundY(Math.PI / 2); // rotate it 90 degrees to the left
dir.multiply(2); // make the vector's length 2
Location newLocation = player.getLocation().add(dir); // add the vector to the player's location to get the new location
Location location = player.getLocation();
Vector direction = location.getDirection();
direction.normalize();
float newZ = (float)(location.getZ() + (2 * Math.sin(Math.toRadians(location.getYaw() + 90 * direction)))); //2 is your block amount in Z direction
float newX = (float)(location.getX() + (Math.cos(Math.toRadians(location.getYaw() + 90 * direction))));
You have to know in which direction you want to teleport the player

Longitude, Latitude, Altitude to 3D-Cartesian Coordinate Systems

I'm wondering about the transformation from Lat,Lon,Alt Values to 3D-Systems like ECEF (Earth-Centered).
This can be implemented as follows (https://gist.github.com/1536054):
/*
* WGS84 ellipsoid constants Radius
*/
private static final double a = 6378137;
/*
* eccentricity
*/
private static final double e = 8.1819190842622e-2;
private static final double asq = Math.pow(a, 2);
private static final double esq = Math.pow(e, 2);
void convert(latitude,longitude,altitude){
double lat = Math.toRadians(latitude);
double lon = Math.toRadians(longitude);
double alt = altitude;
double N = a / Math.sqrt(1 - esq * Math.pow(Math.sin(lat), 2));
x = (N + alt) * Math.cos(lat) * Math.cos(lon);
y = (N + alt) * Math.cos(lat) * Math.sin(lon);
z = ((1 - esq) * N + alt) * Math.sin(lat);
}
What in my opinion seems very strange is the fact, that a little change of the altitude, affects x,y and z, where I would expect, that it just affect one axis. For example, if I have two GPS-Points, which have same lat/lon values but different altitude values, I'll get 3 different x,y,z coordinates.
Can someone explain the "idea" behind this? This looks very curious to me... Is there any other 3D-System, in which only one of the values is changing, when I lower/higher my altitude value?
Thanks a lot!
If you look at this picture: ECEF Coordinate System
then you see why.
ECEF is a cube arround the earth, centered in earth center.
if altitude raises you move out.
Lat/lon is an "angular" coordinate system where lat,lon are angles,
ECEF is a cartesian coordinate system!
Probaly you thougt ECEF is like LatLon with center earth has altitude 0, but this is not the case.

calculate latitude and longitude along a circumference of a known circle with known distance

I dont need help with a programming language, I need help from someone to calculate the gps coordinates of points of a specific distance, namely 22 feet apart, on the circumference of a circle. I know the beginning gps coordinates and the radius. I am pretty sure the haversine, or the speherical law of cosines has the answer, but its been a long time since I have used any trig formulas and I cant figure it out. I am using decimal degrees and am programing in this vb.net. If someone could dumb this down for me it would be a great help.
As I understand you have:
Coordinate of the center of
circumference.
Distance between
two point on the circumference of a
circle.
Radius of circumference.
In my opinion this is not enough for calculating other point's coordinates. You should have as minimum yet one point coordinate, because we only can guess where points are placed on the circumference.
Here's the basic algorithm:
Calculate the angular measure whose arc length is 22 feet, with the given radius
numPoints = Math.PI * 2 / angularMeasure
for i in range(numPoints):
calculate proportion around the circle we are, in terms of degrees or radians
calculate the location of the endpoint of a great circle or rhumb arc from the center point moving in the specific azimuth direction (from the proportion around the circle) the given radius
This last point is the hardest part. Here's code from the WorldWind SDK (available: http://worldwind.arc.nasa.gov/java/) (Note- you'll have to calculate the radius in terms of angles, which you can do pretty easily given the radius / circumference of the earth)
/*
Copyright (C) 2001, 2006 United States Government
as represented by the Administrator of the
National Aeronautics and Space Administration.
All Rights Reserved.
*/
/**
* Computes the location on a rhumb line with the given starting location, rhumb azimuth, and arc distance along the
* line.
*
* #param p LatLon of the starting location
* #param rhumbAzimuth rhumb azimuth angle (clockwise from North)
* #param pathLength arc distance to travel
*
* #return LatLon location on the rhumb line.
*/
public static LatLon rhumbEndPosition(LatLon p, Angle rhumbAzimuth, Angle pathLength)
{
if (p == null)
{
String message = Logging.getMessage("nullValue.LatLonIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
if (rhumbAzimuth == null || pathLength == null)
{
String message = Logging.getMessage("nullValue.AngleIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
double lat1 = p.getLatitude().radians;
double lon1 = p.getLongitude().radians;
double azimuth = rhumbAzimuth.radians;
double distance = pathLength.radians;
if (distance == 0)
return p;
// Taken from http://www.movable-type.co.uk/scripts/latlong.html
double lat2 = lat1 + distance * Math.cos(azimuth);
double dPhi = Math.log(Math.tan(lat2 / 2.0 + Math.PI / 4.0) / Math.tan(lat1 / 2.0 + Math.PI / 4.0));
double q = (lat2 - lat1) / dPhi;
if (Double.isNaN(dPhi) || Double.isNaN(q) || Double.isInfinite(q))
{
q = Math.cos(lat1);
}
double dLon = distance * Math.sin(azimuth) / q;
// Handle latitude passing over either pole.
if (Math.abs(lat2) > Math.PI / 2.0)
{
lat2 = lat2 > 0 ? Math.PI - lat2 : -Math.PI - lat2;
}
double lon2 = (lon1 + dLon + Math.PI) % (2 * Math.PI) - Math.PI;
if (Double.isNaN(lat2) || Double.isNaN(lon2))
return p;
return new LatLon(
Angle.fromRadians(lat2).normalizedLatitude(),
Angle.fromRadians(lon2).normalizedLongitude());
}
You are looking for the equation of what is called a "small circle". Look at this book for the equation of the small circle and the arc length equation for that small circle. However, because your distances are so small, you could consider your area flat and use simpler geometry. Using UTM coordinates would make the calculations much simpler than using lat/long.
The Haversine formula relates to great circles, not small circles...

Converting Longitude & Latitude to X Y on a map with Calibration points

If i have a jpeg map with size sizeX, sizeY
and some calibration points on the map (X, Y, Lon, Lat)
What would be the algorithm for calculating the corresponding XY point in the map with a given Longitude / Latitude pair?
Here's what worked for me, without so much bs.
int x = (int) ((MAP_WIDTH/360.0) * (180 + lon));
int y = (int) ((MAP_HEIGHT/180.0) * (90 - lat));
The lat,lon coordinates were given to me by Android devices. So they should be in the same standard used by all Google Earth/Map products.
If using the Equidistant Cylindrical Projection type map, here is what you need to do:
Find the Latitude and longitude of your location tutorial here: http://lifehacker.com/267361/how-to-find-latitude-and-longitude
Input that information into the following formulas:
x = (total width of image in px) * (180 + latitude) / 360
y = (total height of image in px) * (90 - longitude) / 180note: when using negative longitude of latitude make sure to add or subtract the negative number i.e. +(-92) or -(-35) which would actually be -92 and +35
You now have your X and Y to plot on your imageMore information can be found about this formula and the map type here: http://www.progonos.com/furuti/MapProj/Dither/CartHow/HowER_W12/howER_W12.html#DeductionEquirectangular
There is plenty of information on the Internet about calculating the distance between two pairings of latitude and longitude. We're using those calculations on our public website and they are not trivial to understand/discuss (so I won't try to cover them here). That said, they are easy to implement.
Once you have a function that returns distance, you should be able to caculate the width and height of the map in terms of distance between the corners.
Then you can calculate the horizontal and vertical distance of your point from the top-left corner.
Now you find out what ratio of the map's width is represented by the distance between the left side and your point, apply that ratio to the pixel width and you have the number of pixels between the left side and your point. Repeat for the y-axis.
(Pixels from left side) = (total width in pixels) * ((geocode distance between left and your point) / (geocode distance between left side and right side))
(Pixels from top) = (total height in pixels) * ((geocode distance between top and your point) / (geocode distance between top and bottom))
EDIT: As you research this further you will note that some solutions will present more accurate results than others due to the fact that you are approximating distance between two points on a spherical surface and mapping that on a flat surface. The accuracy decreases as the distance increases. Best advice to you is to try it out first and see if it meets your needs.
This is fairly straight forward and simple.. let me explain how its possible.
Latitude and Longitude are imaginary lines drawn on earth so that you can accurately pinpoint any location on the world . simply put they are the X and Y coords of a plane.
Latitude is a vertical line running from north to south with its 90 deg at the north pole and -90deg at the south pole.
Longitude on the other hand is a horizontal line running east to south with -180deg in the west and 180deg in the east.
you can convert the latLng into pixel coords as by assuming that the width of the html container is the width of the world and the same applies to the the height.
Formula - Longitude - pixel
(givenLng*widthOfContainerElement)/360
where 360 is the total longitude in degrees
Formula -Latitude - pixel
(givenLat*heightOfContainerElement)/180
where 180 is the total latitude in degree
//Height is calculated from the bottom
you can find a working implementation of this formula here, on my website (it uses JavaScript only)
http://www.learntby.me/javascript/latLngconversion.php
let me know if you still need any clarifications.
There are many different map projection schemes. You would have to know which one(s) are used by your maps.
For more information about map projection algorithms and forward/reverse mapping check out this link. It provides the formulas for a number of common projections.
Just make this(for Mercator projection map):
extension UIView
{
func addLocation(coordinate: CLLocationCoordinate2D)
{
// max MKMapPoint values
let maxY = Double(267995781)
let maxX = Double(268435456)
let mapPoint = MKMapPointForCoordinate(coordinate)
let normalizatePointX = CGFloat(mapPoint.x / maxX)
let normalizatePointY = CGFloat(mapPoint.y / maxY)
let pointView = UIView(frame: CGRectMake(0, 0, 5, 5))
pointView.center = CGPointMake(normalizatePointX * frame.width, normalizatePointY * frame.height)
pointView.backgroundColor = UIColor.blueColor()
addSubview(pointView)
}
}
My simple project for adding coordinate on UIView: https://github.com/Glechik/MapCoordinateDrawer
<!DOCTYPE html>
<html>
<head>
<style>
#point{font-face:Arial; font-size:18px; color:#FFFF00; width:12px; height:12px;text-shadow: 2px 2px #000000}
#canvas {position: absolute; top: 0px; left: 0px; z-index: -2}
html,
body,
#canvas {
width: 100%;
height: 100%;
overflow: hidden;
margin: 0
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(window).on("load resize",function(e){
var w = $("#canvas").width();
var h = $("#canvas").height();
// New York, NY (https://maps.googleapis.com/maps/api/geocode/json?address=New%20York,%20NY)
var lat = 40.91525559999999;
var long = -73.70027209999999;
var x = ((w/360) * (180 + long)) - 9;
var y = ((h/180) * (90 - lat)) - 18;
$("#text").text('X:'+x+', Y:'+y);
$("#point").offset({ top: y, left: x });
});
</script>
</head>
<body>
<div id="text"></div>
<div id="point">▼</div>
<img id="canvas" border="0" src="http://friday.westnet.com/~crywalt/dymaxion_2003/earthmap10k.reduced.jpg">
</body>
</html>
I have tried this approach:
int x = (int) ((MAP_WIDTH/360.0) * (180 + lon));
int y = (int) ((MAP_HEIGHT/180.0) * (90 - lat));
but this one works better for me : https://medium.com/#suverov.dmitriy/how-to-convert-latitude-and-longitude-coordinates-into-pixel-offsets-8461093cb9f5
here is a shortcut to code part of the article above :
https://gist.github.com/blaurt/b0ca054a7384ebfbea2d5fce69ae9bf4#file-latlontooffsets-js