Tile Projection Google Maps: Convert Distance to Screen Dimensions - java

I am using the CanvasTileProvider in Google Maps Android v2.
I can convert lat long points to screen pixels.
However I would like to create a method to convert a distance to screen pixels. This will allow me to draw a circle of x radius. Can anyone help with this?
The code below I have butchered and modified from somewhere else so credit to the original author.
/**
* Converts between LatLng coordinates and the pixels inside a tile.
*/
public class TileProjection {
public int x;
public int y;
private int zoom;
private int TILE_SIZE;
private DoublePoint pixelOrigin_;
private double pixelsPerLonDegree_;
private double pixelsPerLonRadian_;
TileProjection(int tileSize, int x, int y, int zoom) {
this.TILE_SIZE = tileSize;
this.x = x;
this.y = y;
this.zoom = zoom;
pixelOrigin_ = new DoublePoint(TILE_SIZE / 2, TILE_SIZE / 2);
pixelsPerLonDegree_ = TILE_SIZE / 360d;
pixelsPerLonRadian_ = TILE_SIZE / (2 * Math.PI);
}
/**
* Get the dimensions of the Tile in LatLng coordinates
*/
public LatLngBounds getTileBounds() {
DoublePoint tileSW = new DoublePoint(x * TILE_SIZE, (y + 1) * TILE_SIZE);
DoublePoint worldSW = pixelToWorldCoordinates(tileSW);
LatLng SW = worldCoordToLatLng(worldSW);
DoublePoint tileNE = new DoublePoint((x + 1) * TILE_SIZE, y * TILE_SIZE);
DoublePoint worldNE = pixelToWorldCoordinates(tileNE);
LatLng NE = worldCoordToLatLng(worldNE);
return new LatLngBounds(SW, NE);
}
/**
* Calculate the pixel coordinates inside a tile, relative to the left upper
* corner (origin) of the tile.
*/
public PointF latLngToPoint(LatLng latLng) {
DoublePoint result = new DoublePoint(1, 1);
// Log.d("Aero","x " + String.valueOf(x));
// Log.d("Aero","y " + String.valueOf(y));
latLngToWorldCoordinates(latLng, result);
worldToPixelCoordinates(result, result);
result.x -= x * TILE_SIZE;
int numTiles = 1 << zoom;
if (latLng.longitude < 0) {
result.x = result.x + (numTiles * TILE_SIZE);
}
result.y -= y * TILE_SIZE;
return new PointF((float) result.x, (float) result.y);
}
private DoublePoint pixelToWorldCoordinates(DoublePoint pixelCoord) {
int numTiles = 1 << zoom;
DoublePoint worldCoordinate = new DoublePoint(pixelCoord.x / numTiles,
pixelCoord.y / numTiles);
return worldCoordinate;
}
/**
* Transform the world coordinates into pixel-coordinates relative to the
* whole tile-area. (i.e. the coordinate system that spans all tiles.)
* <p/>
* <p/>
* Takes the resulting point as parameter, to avoid creation of new objects.
*/
private void worldToPixelCoordinates(DoublePoint worldCoord, DoublePoint result) {
int numTiles = 1 << zoom;
result.x = worldCoord.x * numTiles;
result.y = worldCoord.y * numTiles;
}
private LatLng worldCoordToLatLng(DoublePoint worldCoordinate) {
DoublePoint origin = pixelOrigin_;
double lng = (worldCoordinate.x - origin.x) / pixelsPerLonDegree_;
double latRadians = (worldCoordinate.y - origin.y)
/ -pixelsPerLonRadian_;
double lat = Math.toDegrees(2 * Math.atan(Math.exp(latRadians))
- Math.PI / 2);
return new LatLng(lat, lng);
}
/**
* Get the coordinates in a system describing the whole globe in a
* coordinate range from 0 to TILE_SIZE (type double).
* <p/>
* Takes the resulting point as parameter, to avoid creation of new objects.
*/
private void latLngToWorldCoordinates(LatLng latLng, DoublePoint result) {
DoublePoint origin = pixelOrigin_;
result.x = origin.x + latLng.longitude * pixelsPerLonDegree_;
// Truncating to 0.9999 effectively limits latitude to 89.189. This is
// about a third of a tile past the edge of the world tile.
double siny = bound(Math.sin(Math.toRadians(latLng.latitude)), -0.9999,
0.9999);
result.y = origin.y + 0.5 * Math.log((1 + siny) / (1 - siny))
* -pixelsPerLonRadian_;
}
;
/**
* Return value reduced to min and max if outside one of these bounds.
*/
private double bound(double value, double min, double max) {
value = Math.max(value, min);
value = Math.min(value, max);
return value;
}
/**
* A Point in an x/y coordinate system with coordinates of type double
*/
public static class DoublePoint {
double x;
double y;
public DoublePoint(double x, double y) {
this.x = x;
this.y = y;
}
}
}
This is what I am proposing to use:
public Double MetersToPixels(LatLng latLng, Double distance){
double tileScale = TILE_SIZE / 256;
double pixelsPerMeter =1 / (156543.03392 * Math.cos(latLng.latitude * Math.PI / 180) / Math.pow(2, zoom)) * tileScale;
return pixelsPerMeter * distance;
}

At first you should be aware of the fact, that a circle on the surface of the earth is not exactly a circle on the map. But if you ignore this inaccuracy, you just need to create a LatLng point in 25nm distance, and then use latLngToPoint method to get the pixels. Comparing them with the pixels of the center, gives you the radius. For creating a LatLng in a given distance see the answer to this SO question (method move)

Related

Set player velocity to launch them from point A to point B in an arc with bukkit

I'm trying to code a plugin for a server and I want to launch a player from point A to point B.
I've tried this but a lot of the time it is inaccurate and misses the block by a few blocks.
private Vector calculateVelocity(Location fromLoc, Location toLoc, int heightGain) {
Vector from = fromLoc.toVector();
Vector to = toLoc.toVector();
//Block locations
int endGain = to.getBlockY() - from.getBlockY();
double horizDist = fromLoc.distance(toLoc);
//Height gain
int gain = heightGain;
double maxGain = (gain > (endGain + gain) ? gain : (endGain + gain));
//Solve quadratic equation for velocity
double a = -horizDist * horizDist / (4 * maxGain);
double b = horizDist;
double c = -endGain;
double slope = -b / (2 * a) - Math.sqrt(b * b - 4 * a * c) / (2 * a);
//Vertical velocity
double veloY = Math.sqrt(maxGain * 0.115);
//Horizontal velocity
double vH = veloY / slope;
//Calculate horizontal direction
int distX = to.getBlockX() - from.getBlockX();
int distZ = to.getBlockZ() - from.getBlockZ();
double mag = Math.sqrt(distX * distX + distZ * distZ);
double dirX = distX / mag;
double dirZ = distZ / mag;
//Horizontal velocity components
double veloX = vH * dirX;
double veloZ = vH * dirZ;
//Actual velocity
Vector velocity = new Vector(veloX, veloY, veloZ);
return velocity;
}
Any suggetions on what I should do to get it accurate 100% of the time?

Javelin throw simulation calculation of slope of tangent line at every javelin trajectory point

I am trying to simulate javelin throw on android. I calculate slope of tangent line in every point of javelin trajectory. To calculate trajectory coordinates I am using Projectile motion equations
x = (int) (x0 + v0 * t * Math.cos(radians)); //for coordinate x
and
y = (int) (y0 - v0 * t * Math.sin(radians) + 0.5 * g * t * t);
To calculate slope of tangent line to javelin trajectory I derivated this equation with respect to x:
y = Math.tan(radians) * x - g / (2 * Math.pow(v0, 2) * Math.pow(Math.cos(radians), 2)) * x^2
dy = Math.tan(radians) - (g * x) / (Math.pow(v0, 2) * Math.pow(Math.cos(radians), 2))
Problem is, that it works correctly with elevation angle < than approximately 60 degrees.
If elevation angle is bigger, it doesn't calculate correct slope.
Here is the code:
public class ThrowJavelin extends ImageView {
private Context mContext;
int x0 = -1;
int y0 = -1;
int x = x0;
int y = y0;
private Handler h;
private final int FRAME_RATE = 5;
private double t = 0;
private float g = 9.81f;
//initial velocity
private int v0;
//elevation angle in radians
private double radians;
//javelin current angle in degrees
private double javelin_angle;
public ThrowJavelin(Context context, AttributeSet attr) { super(context, attr); }
public ThrowJavelin(Context context, AttributeSet attrs, int defStyleAttr){ super(context, attrs, defStyleAttr); }
public ThrowJavelin(Context context, Bundle args) {
super(context);
mContext = context;
h = new Handler();
//input values
v0 = args.getInt("velocity");
radians = args.getDouble("radians");
}
private Runnable r = new Runnable() {
#Override
public void run() {
invalidate();
}
};
protected void onDraw(Canvas c) {
Bitmap javelin = BitmapFactory.decodeResource(getResources(), R.drawable.jav);
DerivativeStructure alpha = null;
if (x < 0 && y < 0) {
x0 = 0;
y0 = c.getHeight() - 200;
x = x0;
y = y0;
javelin = rotateBitmap(javelin, (float) Math.toDegrees(radians));
} else if (y > y0) { //reset to beginning
x = x0;
y = y0;
t = 0;
javelin = rotateBitmap(javelin, (float) Math.toDegrees(radians));
} else {
//calculate current coordinates (depends on t)
x = (int) (x0 + v0 * t * Math.cos(radians));
y = (int) (y0 - v0 * t * Math.sin(radians) + 0.5 * g * t * t);
if (x == 0) {
javelin_angle = Math.toDegrees(radians);
} else {
// dy of 3rd equation
javelin_angle = Math.toDegrees(Math.tan(radians) - (g * x) / (Math.pow(v0, 2) * Math.pow(Math.cos(radians), 2)));
}
javelin = rotateBitmap(javelin, javelin_angle);
t += 0.3;
}
c.drawBitmap(javelin, x, y, null);
h.postDelayed(r, FRAME_RATE);
}
public Bitmap rotateBitmap(Bitmap image, double angle){
float alpha = (float) angle;
Matrix mat = new Matrix();
System.out.println(-alpha);
mat.postRotate(-alpha);
return Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), mat, true);
}
}
I really don't understand, why ot doesn't work correctly for bigger angles. Any ideas please?
Firstly, your solution for y(x) seems to drop a few variables (e.g. x0). Here is the full solution:
y(x) = y0 + (0.5 * g * (x - x0)^2)/(v0^2 * cos(radians)^2) - (x - x0) * tan(radians)
The derivative with respect to x is:
dy/dx = (g * (x - x0)) / (v0^2 * cos^2(radians)) - tan(radians)
Your solution looks very similar except that its y-axis is inverted and it misses the initial positions.
The angle that corresponds to this derivative is its arctangens:
double c = Math.cos(radians);
javelin_angle = Math.toDegrees(Math.atan((g * (x - x0) / (v0 * v0 * c * c) - Math.tan(radians)));
I assume, there was a reason why you swapped the y-axis. So you may do that again in this formula.
The reason why your formula worked for small angles is that the arctangens is close to the identity for small angles (identity in red, arctangens in blue):

Convert pixel position from Google static map to LatLng

I have a google static map that I have stored in a 2d array. When the user clicks on a pixel I know the row / col [ 0 - 1024 ].
I need to convert that row col back into a lat lng. I have been trying to use the code below to do the conversions from pixel to lat lng and back.
What I have done is to take the center lat lng and the zoom level.
Convert the center lat lng to pixel using fromLatLngToPoint.
Using the row / col from the image and the width and height of the image get
private static PointF getPointFromRowCol(int row, int col, int width, int height, PointF center) {
double adjustedStartCol = center.x - ((double)width / 2);
double adjustedStartRow = center.y - ((double)height / 2);
double adjustedCol = adjustedStartCol + col;
double adjustedRow = adjustedStartRow + row;
PointF adjustedWorldPoint = new PointF(adjustedCol, adjustedRow);
return GoogleMapsProjection2.fromPointToLatLng(adjustedWorldPoint, 17);
}
The problem is when I put the resulting lat lng back into google maps it is off by 100's of meters.
Any ideas?
public final class GoogleMapsProjection2 {
private final int TILE_SIZE = 256;
private PointF _pixelOrigin;
public double _pixelsPerLonDegree;
public double _pixelsPerLonRadian;
public GoogleMapsProjection2() {
this._pixelOrigin = new PointF(TILE_SIZE / 2.0, TILE_SIZE / 2.0);
this._pixelsPerLonDegree = TILE_SIZE / 360.0;
this._pixelsPerLonRadian = TILE_SIZE / (2 * Math.PI);
}
double bound(double val, double valMin, double valMax) {
double res;
res = Math.max(val, valMin);
res = Math.min(val, valMax);
return res;
}
double degreesToRadians(double deg) {
return deg * (Math.PI / 180);
}
double radiansToDegrees(double rad) {
return rad / (Math.PI / 180);
}
public PointF fromLatLngToPoint(double lat, double lng, int zoom) {
PointF point = new PointF(0, 0);
point.x = _pixelOrigin.x + lng * _pixelsPerLonDegree;
// Truncating to 0.9999 effectively limits latitude to 89.189. This is
// about a third of a tile past the edge of the world tile.
double siny = bound(Math.sin(degreesToRadians(lat)), -0.9999, 0.9999);
point.y = _pixelOrigin.y + 0.5 * Math.log((1 + siny) / (1 - siny)) * -_pixelsPerLonRadian;
int numTiles = 1 << zoom;
point.x = point.x * numTiles;
point.y = point.y * numTiles;
return point;
}
public PointF fromPointToLatLng(PointF point, int zoom) {
int numTiles = 1 << zoom;
point.x = point.x / numTiles;
point.y = point.y / numTiles;
double lng = (point.x - _pixelOrigin.x) / _pixelsPerLonDegree;
double latRadians = (point.y - _pixelOrigin.y) / -_pixelsPerLonRadian;
double lat = radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2);
return new PointF(lat, lng);
}
public static PointF fromWorldToPixel(PointF world){
PointF pixelPoint = new PointF(world.x * (1 << 17), world.y * (1 << 17));
return pixelPoint;
}
public static PointF pixelToWorld(PointF world){
PointF pixelPoint = new PointF(world.x / (1 << 17), world.y / (1 << 17));
return pixelPoint;
}
}
This page seems to suggest that you can use the other APIs with the static maps.
It seems worth mentioning that you can actually have the Google Maps Javascript API give you the latitudinal & longitudinal coordinates from pixel coordinates.
While it's a little convoluted in V3 here's an example of how to do it. (NOTE: This is assuming you already have a map and the pixel vertices to be converted to a lat&lng coordinate):
let overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.onAdd = function() {};
overlay.onRemove = function() {};
overlay.setMap(map);
let latlngObj = overlay.fromContainerPixelToLatLng(new google.maps.Point(pixelVertex.x, pixelVertex.y);
overlay.setMap(null); //removes the overlay
Hope that helps someone.
You can try this Java function:
function convertPixelToGeo(tx:Number, ty)
{
$LatBottomSin=min(max(sin($this->mapLatBottom*(M_PI/180)),-0.9999),0.9999);
$worldMapWidth=(($this->mapWidth/$mapLonDelta)*360)/(2*M_PI);
$worldMapRadius = $mapWidth / $mapLonDelta * 360/(2*M_PI);
$mapOffsetY = ($worldMapRadius/2 *log((1+sin($LatBottomSin))/(1-sin($LatBottomSin))));
$equatorY = $this->mapHeight + mapOffsetY;
$a = ($equatorY-$ty)/$worldMapRadius;
$lat = 180/Math.PI * (2 * Math.atan(Math.exp($a)) - Math.PI/2);
$long = $this->mapLonLeft+$tx/$mapWidth*$mapLonDelta;
return new Point($lat,$long);
}
If it doesn't work try this:
int numTiles = 1 << zoom;
tx = tx / numTiles;
ty = ty / numTiles;

Convert latitude/longitude point to a pixels (x,y) on mercator projection

I'm trying to convert a lat/long point into a 2d point so that I can display it on an image of the world-which is a mercator projection.
I've seen various ways of doing this and a few questions on stack overflow-I've tried out the different code snippets and although I get the correct longitude to pixel, the latitude is always off-seems to be getting more reasonable though.
I need the formula to take into account the image size, width etc.
I've 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);
The latitude seems to be off by about 30px in the example I'm trying. Any help or advice?
Update
Based on this question:Lat/lon to xy
I've tried to use the code provided but I'm still having some problems with latitude conversion, longitude is fine.
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 original code if the latitude value is positive it returned a negative point, so I modified it slightly and tested with the extreme latitudes-which should be point 0 and point 766, it works fine. However when I try a different latitude value ex: 58.07 (just north of the UK) it displays as north of Spain.
The Mercator map projection is a special limiting case of the Lambert Conic Conformal map projection with
the equator as the single standard parallel. All other parallels of latitude are straight lines and the meridians
are also straight lines at right angles to the equator, equally spaced. It is the basis for the transverse and
oblique forms of the projection. It is little used for land mapping purposes but is in almost universal use for
navigation charts. As well as being conformal, it has the particular property that straight lines drawn on it are
lines of constant bearing. Thus navigators may derive their course from the angle the straight course line
makes with the meridians. [1.]
The formulas to derive projected Easting and Northing coordinates from spherical latitude φ and longitude λ
are:
E = FE + R (λ – λₒ)
N = FN + R ln[tan(π/4 + φ/2)]
where λO is the longitude of natural origin and FE and FN are false easting and false northing.
In spherical Mercator those values are actually not used, so you can simplify the formula to
Pseudo code example, so this can be adapted to every programming language.
latitude = 41.145556; // (φ)
longitude = -73.995; // (λ)
mapWidth = 200;
mapHeight = 100;
// get x value
x = (longitude+180)*(mapWidth/360)
// convert from degrees to radians
latRad = latitude*PI/180;
// get y value
mercN = ln(tan((PI/4)+(latRad/2)));
y = (mapHeight/2)-(mapWidth*mercN/(2*PI));
Sources:
OGP Geomatics Committee, Guidance Note Number 7, part 2: Coordinate Conversions and Transformation
Derivation of the Mercator projection
National Atlas: Map Projections
Mercator Map projection
EDIT
Created a working example in PHP (because I suck at Java)
https://github.com/mfeldheim/mapStuff.git
EDIT2
Nice animation of the Mercator projection
https://amp-reddit-com.cdn.ampproject.org/v/s/amp.reddit.com/r/educationalgifs/comments/5lhk8y/how_the_mercator_projection_distorts_the_poles/?usqp=mq331AQJCAEoAVgBgAEB&amp_js_v=0.1
You cannot merely transpose from longitude/latitude to x/y like that because the world isn't flat. Have you look at this post? Converting longitude/latitude to X/Y coordinate
UPDATE - 1/18/13
I decided to give this a stab, and here's how I do it:-
public class MapService {
// CHANGE THIS: the output path of the image to be created
private static final String IMAGE_FILE_PATH = "/some/user/path/map.png";
// CHANGE THIS: image width in pixel
private static final int IMAGE_WIDTH_IN_PX = 300;
// CHANGE THIS: image height in pixel
private static final int IMAGE_HEIGHT_IN_PX = 500;
// CHANGE THIS: minimum padding in pixel
private static final int MINIMUM_IMAGE_PADDING_IN_PX = 50;
// formula for quarter PI
private final static double QUARTERPI = Math.PI / 4.0;
// some service that provides the county boundaries data in longitude and latitude
private CountyService countyService;
public void run() throws Exception {
// configuring the buffered image and graphics to draw the map
BufferedImage bufferedImage = new BufferedImage(IMAGE_WIDTH_IN_PX,
IMAGE_HEIGHT_IN_PX,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
Map<RenderingHints.Key, Object> map = new HashMap<RenderingHints.Key, Object>();
map.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
map.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
map.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
RenderingHints renderHints = new RenderingHints(map);
g.setRenderingHints(renderHints);
// min and max coordinates, used in the computation below
Point2D.Double minXY = new Point2D.Double(-1, -1);
Point2D.Double maxXY = new Point2D.Double(-1, -1);
// a list of counties where each county contains a list of coordinates that form the county boundary
Collection<Collection<Point2D.Double>> countyBoundaries = new ArrayList<Collection<Point2D.Double>>();
// for every county, convert the longitude/latitude to X/Y using Mercator projection formula
for (County county : countyService.getAllCounties()) {
Collection<Point2D.Double> lonLat = new ArrayList<Point2D.Double>();
for (CountyBoundary countyBoundary : county.getCountyBoundaries()) {
// convert to radian
double longitude = countyBoundary.getLongitude() * Math.PI / 180;
double latitude = countyBoundary.getLatitude() * Math.PI / 180;
Point2D.Double xy = new Point2D.Double();
xy.x = longitude;
xy.y = Math.log(Math.tan(QUARTERPI + 0.5 * latitude));
// The reason we need to determine the min X and Y values is because in order to draw the map,
// we need to offset the position so that there will be no negative X and Y values
minXY.x = (minXY.x == -1) ? xy.x : Math.min(minXY.x, xy.x);
minXY.y = (minXY.y == -1) ? xy.y : Math.min(minXY.y, xy.y);
lonLat.add(xy);
}
countyBoundaries.add(lonLat);
}
// readjust coordinate to ensure there are no negative values
for (Collection<Point2D.Double> points : countyBoundaries) {
for (Point2D.Double point : points) {
point.x = point.x - minXY.x;
point.y = point.y - minXY.y;
// now, we need to keep track the max X and Y values
maxXY.x = (maxXY.x == -1) ? point.x : Math.max(maxXY.x, point.x);
maxXY.y = (maxXY.y == -1) ? point.y : Math.max(maxXY.y, point.y);
}
}
int paddingBothSides = MINIMUM_IMAGE_PADDING_IN_PX * 2;
// the actual drawing space for the map on the image
int mapWidth = IMAGE_WIDTH_IN_PX - paddingBothSides;
int mapHeight = IMAGE_HEIGHT_IN_PX - paddingBothSides;
// determine the width and height ratio because we need to magnify the map to fit into the given image dimension
double mapWidthRatio = mapWidth / maxXY.x;
double mapHeightRatio = mapHeight / maxXY.y;
// using different ratios for width and height will cause the map to be stretched. So, we have to determine
// the global ratio that will perfectly fit into the given image dimension
double globalRatio = Math.min(mapWidthRatio, mapHeightRatio);
// now we need to readjust the padding to ensure the map is always drawn on the center of the given image dimension
double heightPadding = (IMAGE_HEIGHT_IN_PX - (globalRatio * maxXY.y)) / 2;
double widthPadding = (IMAGE_WIDTH_IN_PX - (globalRatio * maxXY.x)) / 2;
// for each country, draw the boundary using polygon
for (Collection<Point2D.Double> points : countyBoundaries) {
Polygon polygon = new Polygon();
for (Point2D.Double point : points) {
int adjustedX = (int) (widthPadding + (point.getX() * globalRatio));
// need to invert the Y since 0,0 starts at top left
int adjustedY = (int) (IMAGE_HEIGHT_IN_PX - heightPadding - (point.getY() * globalRatio));
polygon.addPoint(adjustedX, adjustedY);
}
g.drawPolygon(polygon);
}
// create the image file
ImageIO.write(bufferedImage, "PNG", new File(IMAGE_FILE_PATH));
}
}
RESULT: Image width = 600px, Image height = 600px, Image padding = 50px
RESULT: Image width = 300px, Image height = 500px, Image padding = 50px
Java version of original Google Maps JavaScript API v3 java script code is as following, it works with no problem
public final class GoogleMapsProjection2
{
private final int TILE_SIZE = 256;
private PointF _pixelOrigin;
private double _pixelsPerLonDegree;
private double _pixelsPerLonRadian;
public GoogleMapsProjection2()
{
this._pixelOrigin = new PointF(TILE_SIZE / 2.0,TILE_SIZE / 2.0);
this._pixelsPerLonDegree = TILE_SIZE / 360.0;
this._pixelsPerLonRadian = TILE_SIZE / (2 * Math.PI);
}
double bound(double val, double valMin, double valMax)
{
double res;
res = Math.max(val, valMin);
res = Math.min(res, valMax);
return res;
}
double degreesToRadians(double deg)
{
return deg * (Math.PI / 180);
}
double radiansToDegrees(double rad)
{
return rad / (Math.PI / 180);
}
PointF fromLatLngToPoint(double lat, double lng, int zoom)
{
PointF point = new PointF(0, 0);
point.x = _pixelOrigin.x + lng * _pixelsPerLonDegree;
// Truncating to 0.9999 effectively limits latitude to 89.189. This is
// about a third of a tile past the edge of the world tile.
double siny = bound(Math.sin(degreesToRadians(lat)), -0.9999,0.9999);
point.y = _pixelOrigin.y + 0.5 * Math.log((1 + siny) / (1 - siny)) *- _pixelsPerLonRadian;
int numTiles = 1 << zoom;
point.x = point.x * numTiles;
point.y = point.y * numTiles;
return point;
}
PointF fromPointToLatLng(PointF point, int zoom)
{
int numTiles = 1 << zoom;
point.x = point.x / numTiles;
point.y = point.y / numTiles;
double lng = (point.x - _pixelOrigin.x) / _pixelsPerLonDegree;
double latRadians = (point.y - _pixelOrigin.y) / - _pixelsPerLonRadian;
double lat = radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2);
return new PointF(lat, lng);
}
public static void main(String []args)
{
GoogleMapsProjection2 gmap2 = new GoogleMapsProjection2();
PointF point1 = gmap2.fromLatLngToPoint(41.850033, -87.6500523, 15);
System.out.println(point1.x+" "+point1.y);
PointF point2 = gmap2.fromPointToLatLng(point1,15);
System.out.println(point2.x+" "+point2.y);
}
}
public final class PointF
{
public double x;
public double y;
public PointF(double x, double y)
{
this.x = x;
this.y = y;
}
}
JAVA only?
Python code here! Refer to Convert latitude/longitude point to a pixels (x,y) on mercator projection
import math
from numpy import log as ln
# Define the size of map
mapWidth = 200
mapHeight = 100
def convert(latitude, longitude):
# get x value
x = (longitude + 180) * (mapWidth / 360)
# convert from degrees to radians
latRad = (latitude * math.pi) / 180
# get y value
mercN = ln(math.tan((math.pi / 4) + (latRad / 2)))
y = (mapHeight / 2) - (mapWidth * mercN / (2 * math.pi))
return x, y
print(convert(41.145556, 121.2322))
Answer:
(167.35122222222225, 24.877939817552335)
public static String getTileNumber(final double lat, final double lon, final int zoom) {
int xtile = (int)Math.floor( (lon + 180) / 360 * (1<<zoom) ) ;
int ytile = (int)Math.floor( (1 - Math.log(Math.tan(Math.toRadians(lat)) + 1 / Math.cos(Math.toRadians(lat))) / Math.PI) / 2 * (1<<zoom) ) ;
if (xtile < 0)
xtile=0;
if (xtile >= (1<<zoom))
xtile=((1<<zoom)-1);
if (ytile < 0)
ytile=0;
if (ytile >= (1<<zoom))
ytile=((1<<zoom)-1);
return("" + zoom + "/" + xtile + "/" + ytile);
}
}
I'm new here, just to write, as I've been following the community for some years. I'm happy to be able to contribute.
Well, it took me practically a day in search of that and your question encouraged me to continue the search.
I arrived at the following function, which works! Credits for this article: https://towardsdatascience.com/geotiff-coordinate-querying-with-javascript-5e6caaaf88cf
var bbox = [minLong, minLat, maxLong, maxLat];
var pixelWidth = mapWidth;
var pixelHeight = mapHeight;
var bboxWidth = bbox[2] - bbox[0];
var bboxHeight = bbox[3] - bbox[1];
var convertToXY = function(latitude, longitude) {
var widthPct = ( longitude - bbox[0] ) / bboxWidth;
var heightPct = ( latitude - bbox[1] ) / bboxHeight;
var x = Math.floor( pixelWidth * widthPct );
var y = Math.floor( pixelHeight * ( 1 - heightPct ) );
return { x, y };
}

Angle between two 3D vectors

I have a series of vertices (pink) that I want to rotate so that one edge of the pattern of vertices matches with the edge of the triangle (white).
To do this, I first create two vectors to represent the edges: floretAB and triangleAB (green). I then find the cross product of the two to get an axis around which I can rotate the vertices (red).
I then get the angle between the two vectors, and use that, with the rotation axis to create a quaternion. Finally, I rotate all the vertices around the quaternion.
Before rotation
_
What rotation should produce
_
However, although the vertices correctly rotate around the quaternion, the angle is not coming out correct, as illustrated here:
This is the code I'm using to get the angle between the two vectors. I don't understand what I'm doing wrong:
double[] cross = new double[3];
crossProduct(floretAB.mX, floretAB.mY, floretAB.mZ, triangleAB.mX, triangleAB.mY, triangleAB.mZ, cross);
double dot = dotProduct(floretAB.mX, floretAB.mY, floretAB.mZ, triangleAB.mX, triangleAB.mY, triangleAB.mZ);
double crossMag = Math.sqrt(cross[0]*cross[0] + cross[1]*cross[1] + cross[2]*cross[2]);
double angle = Math.atan2(crossMag, dot);
public static double dotProduct(double vector1X,double vector1Y,double vector1Z,double vector2X,double vector2Y,double vector2Z){
return vector1X*vector2X + vector1Y*vector2Y + vector1Z*vector2Z;
}
public static void crossProduct(double vector1X,double vector1Y,double vector1Z,double vector2X,double vector2Y,double vector2Z, double[] outputArray){
outputArray[0] = vector1Y*vector2Z - vector1Z*vector2Y;
outputArray[1] = vector1Z*vector2X - vector1X*vector2Z;
outputArray[2] = vector1X*vector2Y - vector1Y*vector2X;
}
Any help with this would be most appreciated as it is really bugging me.
Thanks, James
Edit: Here is the rest of the code:
// get floret p1,p2 vector
// get triangle p1,p2 vector
Vector3D floretAB = new Vector3D(florets3D[0], florets3D[7]);
// get triangle p1,p2 vector
Vector3D triangleAB = new Vector3D(triangle[0], triangle[1]);
// get rotation axis (cross) and angle (dot)
/*
double[] cross = new double[3];
crossProduct(floretAB.mX, floretAB.mY, floretAB.mZ, triangleAB.mX, triangleAB.mY, triangleAB.mZ, cross);
double dotMag = floretAB.getMagnitude() * triangleAB.getMagnitude();
double dot = dotProduct(floretAB.mX, floretAB.mY, floretAB.mZ, triangleAB.mX, triangleAB.mY, triangleAB.mZ) / dotMag;
double angle = Math.acos(dot);
*/
double[] cross = new double[3];
crossProduct(floretAB.mX, floretAB.mY, floretAB.mZ, triangleAB.mX, triangleAB.mY, triangleAB.mZ, cross);
double dot = dotProduct(floretAB.mX, floretAB.mY, floretAB.mZ, triangleAB.mX, triangleAB.mY, triangleAB.mZ);
double crossMag = Math.sqrt(cross[0]*cross[0] + cross[1]*cross[1] + cross[2]*cross[2]);
double angle = Math.atan2(crossMag, dot);
// rotate floret so p1,p2 vector matches with triangle p1,p2 vector
double[] newVerts = new double[3];
Quaternion quat = new Quaternion(cross[0], cross[1], cross[2], angle);
for(int i = 0;i<numfloretVerts;i++){
Vertex3D vert = florets3D[i];
quat.RotateVector(vert.getmX(), vert.getmY(), vert.getmZ(), newVerts);
vert.setmX(newVerts[0]);
vert.setmY(newVerts[1]);
vert.setmZ(newVerts[2]);
}
_
public class Vector3D {
public double mX;
public double mY;
public double mZ;
public Vertex3D point;
/**
* Constructs a vector from two points. The new vector is normalised
*
* #param point1
* #param point2
*/
public Vector3D(Vertex3D point1, Vertex3D point2){
mX = point2.getmX() - point1.getmX();
mY = point2.getmY() - point1.getmY();
mZ = point2.getmZ() - point1.getmZ();
normalise();
point = point1;
}
/**
* Normalises the vector
*/
public void normalise(){
double magnitude = Math.sqrt(mX*mX + mY*mY + mZ*mZ);
if(magnitude!=0){
mX /= magnitude;
mY /= magnitude;
mZ /= magnitude;
}
}
/**
*
* #return the magnitude of the vector
*/
public double getMagnitude(){
return Math.sqrt(mX*mX + mY*mY + mZ*mZ);
}
}
_
public class Quaternion {
private static final double TOLERANCE = 0.00001f;
double w;
double x;
double y;
double z;
public Quaternion(double axisX, double axisY, double axisZ, double angleInRadians){
setAxisAngle(axisX, axisY, axisZ, angleInRadians);
}
public void Normalise(){
// Don't normalize if we don't have to
double mag2 = w * w + x * x + y * y + z * z;
if (Math.abs(mag2) > TOLERANCE && Math.abs(mag2 - 1.0f) > TOLERANCE) {
double mag = (double) Math.sqrt(mag2);
w /= mag;
x /= mag;
y /= mag;
z /= mag;
}
}
public void getConjugate(double[] outputArray){
outputArray[0] = w;
outputArray[1] = -x;
outputArray[2] = -y;
outputArray[3] = -z;
}
public void Multiply(double[] aq, double[] rq, double[] outputArray){
outputArray[0] = aq[0] * rq[0] - aq[1] * rq[1] - aq[2] * rq[2] - aq[3] * rq[3];
outputArray[1] = aq[0] * rq[1] + aq[1] * rq[0] + aq[2] * rq[3] - aq[3] * rq[2];
outputArray[2] = aq[0] * rq[2] + aq[2] * rq[0] + aq[3] * rq[1] - aq[1] * rq[3];
outputArray[3] = aq[0] * rq[3] + aq[3] * rq[0] + aq[1] * rq[2] - aq[2] * rq[1];
}
private double[] vecQuat = new double[4];
private double[] resQuat = new double[4];
private double[] thisQuat = new double[4];
private double[] conj = new double[4];
/**
* Rotates a vector (or point) around this axis-angle
*
* #param vectorX the x component of the vector (or point)
* #param vectorY the y component of the vector (or point)
* #param vectorZ the z component of the vector (or point)
* #param outputArray the array in which the results will be stored
*/
public void RotateVector(double vectorX, double vectorY, double vectorZ, double[] outputArray){
vecQuat[0] = 0.0f;
vecQuat[1] = vectorX;
vecQuat[2] = vectorY;
vecQuat[3] = vectorZ;
thisQuat[0] = w;
thisQuat[1] = x;
thisQuat[2] = y;
thisQuat[3] = z;
getConjugate(conj);
Multiply(vecQuat,conj,resQuat);
Multiply(thisQuat,resQuat,vecQuat);
outputArray[0] = vecQuat[1];
outputArray[1] = vecQuat[2];
outputArray[2] = vecQuat[3];
}
/**
* set Quaternion by providing axis-angle form
*/
public void setAxisAngle(double axisX, double axisY, double axisZ, double angleInRadians){
w = (double) Math.cos( angleInRadians/2);
x = (double) (axisX * Math.sin( angleInRadians/2 ));
y = (double) (axisY * Math.sin( angleInRadians/2 ));
z = (double) (axisZ * Math.sin( angleInRadians/2 ));
Normalise();
}
}
I think you've overcomplicated your maths.
Given two unit vectors (you did say they were normalised) then the magnitude of the cross product is equal to sin(theta). There shouldn't be any need to invoke the dot product or atan2.
You possibly also need to normalise the cross product vector result too before you create the quaternion - it depends on your implementation of new Quaternion(x, y, z, theta) and whether it requires [x, y, z] to be normalised or not.
I think the problem is that you evaluate the angle in the wrong way.
If I understand correctly what are you trying to achieve, then you need the angle between 2 green lines. You correctly evaluate the dot product between 2 green lines using the definition:
(a, b) = a1*b1 + a2*b2 + a3*b3.
But dot product can also be evaluated like this:
(a, b) = |a|*|b|*cos(theta)
So you can evaluate cos(theta) - the cosine of angle between 2 green lines - like this:
cos(theta) = (a1*b1 + a2*b2 + a3*b3) / (|a|*|b|)
But I would use yet another approach. I would normalize both vectors at first (i.e. converted them to unit-vectors). You can do this by dividing each vector's component by the vector's length (sqrt(x1*x1 + y1*y1 + z1*z1)) Then you will have the following:
(aa, bb) = cos(theta)
where aa is normalized a and bb is normalized b.
I hope this helps.
The stated answers are correct for real numbers but can loose accuracy near certain angles when computed with floating point numbers. For arcos() when the angle is near zero or PI, and for arcsin() near pi/2 and –pi/2, as many a half the significant figures can be lost. A method that is more robust and only suffers a few rounding errors uniformly over the whole range from and including zero to and including PI, assuming the input vectors are unit length is:
public double AngleBetween(Vector3D a, Vector3D b)
{
return 2.0d * Math.atan((a-b).Length/(a+b).Length);
}
Note, this gives the unoriented angle between the two vectors. A reference for this and attributed to Kahan may be found at: http://www.cs.berkeley.edu/~wkahan/MathH110/Cross.pdf

Categories