For context, I'm making a mod and I have been trying to make a wave of water blocks to damage entities. The way I'll be doing it is by tracking an invisible fireball and the fireball will go only 10 block away from the player before being killed. I can summon the fireball but I don't know how to kill it. Here's a snippet of the code, using Fabric 1.19.2 and IntelliJ
#Override
public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
if (!user.getWorld().isClient){
double xUser = user.getEyePos().getX();
double yUser = user.getEyeY();
double zUser = user.getEyePos().getZ();
double Pitch = user.getPitch();
Pitch = (Pitch+90) / 180 * Math.PI;
double BodyYaw = user.getHeadYaw();
//converting from [
BodyYaw = (BodyYaw + 90) / 180 * Math.PI;
double theta = BodyYaw;
double phi = Pitch;
double x = xUser + 10 * Math.sin(phi) * Math.cos(theta);
double z = zUser + 10 * Math.sin(phi) * Math.sin(theta);
double y = yUser + 10 * Math.cos(phi);
Vec3d vector = new Vec3d((x-xUser)/20,(y-yUser-0.5d)/20,(z-zUser)/20);
FireballEntity fireball = new FireballEntity(world, user, vector.x, vector.y, vector.z, 0);
fireball.setPitch((float)Pitch);
fireball.setPos(xUser, yUser, zUser);
fireball.setHeadYaw((float)BodyYaw);
fireball.setInvisible(false);
fireball.setNoGravity(true);
world.spawnEntity(fireball);
}
return super.use(world, user, hand);
}
I want to create 2 new longitude and 2 new latitudes based on a coordinate and a distance in meters, I want to create a nice bounding box around a certain point. It is for a part of a city and max ±1500 meters. I therefore don't think the curvature of earth has to be taken into account.
So I have 50.0452345 (x) and 4.3242234 (y) and I want to know x + 500 meters, x - 500 meters, y - 500 meters, y + 500 meters
I found many algorithms but almost all seem to deal with the distance between points.
The number of kilometers per degree of longitude is approximately
(pi/180) * r_earth * cos(theta*pi/180)
where theta is the latitude in degrees and r_earth is approximately 6378 km.
The number of kilometers per degree of latitude is approximately the same at all locations, approx
(pi/180) * r_earth = 111 km / degree
So you can do:
new_latitude = latitude + (dy / r_earth) * (180 / pi);
new_longitude = longitude + (dx / r_earth) * (180 / pi) / cos(latitude * pi/180);
As long as dx and dy are small compared to the radius of the earth and you don't get too close to the poles.
The accepted answer is perfectly right and works. I made some tweaks and turned into this:
double meters = 50;
// number of km per degree = ~111km (111.32 in google maps, but range varies
// between 110.567km at the equator and 111.699km at the poles)
//
// 111.32km = 111320.0m (".0" is used to make sure the result of division is
// double even if the "meters" variable can't be explicitly declared as double)
double coef = meters / 111320.0;
double new_lat = my_lat + coef;
// pi / 180 ~= 0.01745
double new_long = my_long + coef / Math.cos(my_lat * 0.01745);
Hope this helps too.
For latitude do:
var earth = 6378.137, //radius of the earth in kilometer
pi = Math.PI,
m = (1 / ((2 * pi / 360) * earth)) / 1000; //1 meter in degree
var new_latitude = latitude + (your_meters * m);
For longitude do:
var earth = 6378.137, //radius of the earth in kilometer
pi = Math.PI,
cos = Math.cos,
m = (1 / ((2 * pi / 360) * earth)) / 1000; //1 meter in degree
var new_longitude = longitude + (your_meters * m) / cos(latitude * (pi / 180));
The variable your_meters can contain a positive or a negative value.
I had to spend about two hours to work out the solution by #nibot , I simply needed a method to create a boundary box given its center point and width/height (or radius) in kilometers:
I don't fully understand the solution mathematically/ geographically.
I tweaked the solution (by trial and error) to get the four coordinates. Distances in km, given the current position and distance we shift to the new position in the four coordinates:
North:
private static Position ToNorthPosition(Position center, double northDistance)
{
double r_earth = 6378;
var pi = Math.PI;
var new_latitude = center.Lat + (northDistance / r_earth) * (180 / pi);
return new Position(new_latitude, center.Long);
}
East:
private static Position ToEastPosition(Position center, double eastDistance)
{
double r_earth = 6378;
var pi = Math.PI;
var new_longitude = center.Long + (eastDistance / r_earth) * (180 / pi) / Math.Cos(center.Lat * pi / 180);
return new Position(center.Lat, new_longitude);
}
South:
private static Position ToSouthPosition(Position center, double southDistance)
{
double r_earth = 6378;
var pi = Math.PI;
var new_latitude = center.Lat - (southDistance / r_earth) * (180 / pi);
return new Position(new_latitude, center.Long);
}
West:
private static Position ToWestPosition(Position center, double westDistance)
{
double r_earth = 6378;
var pi = Math.PI;
var new_longitude = center.Long - (westDistance / r_earth) * (180 / pi) / Math.Cos(center.Lat * pi / 180);
return new Position(center.Lat, new_longitude);
}
Have you checked out: How do I find the lat/long that is x km north of a given lat/long ?
These calculations are annoying at best, I've done many of them. The haversine formula will be your friend.
Some reference: http://www.movable-type.co.uk/scripts/latlong.html
Posting this method for sake of completeness.
Use this method "as it is" to:
Move any (lat,long) point by given meters in either axis.
Python method to move any point by defined meters.
def translate_latlong(lat,long,lat_translation_meters,long_translation_meters):
''' method to move any lat,long point by provided meters in lat and long direction.
params :
lat,long: lattitude and longitude in degrees as decimal values, e.g. 37.43609517497065, -122.17226450150885
lat_translation_meters: movement of point in meters in lattitude direction.
positive value: up move, negative value: down move
long_translation_meters: movement of point in meters in longitude direction.
positive value: left move, negative value: right move
'''
earth_radius = 6378.137
#Calculate top, which is lat_translation_meters above
m_lat = (1 / ((2 * math.pi / 360) * earth_radius)) / 1000;
lat_new = lat + (lat_translation_meters * m_lat)
#Calculate right, which is long_translation_meters right
m_long = (1 / ((2 * math.pi / 360) * earth_radius)) / 1000; # 1 meter in degree
long_new = long + (long_translation_meters * m_long) / math.cos(lat * (math.pi / 180));
return lat_new,long_new
Working Python code to offset coordinates by 10 metres.
def add_blur(lat, long):
meters = 10
blur_factor = meters * 0.000006279
new_lat = lat + blur_factor
new_long = long + blur_factor / math.cos(lat * 0.018)
return new_lat, new_long
if you don't have to be very exact then: each 10000 meters is about 0.1 for latitude and longitude.
for example I want to load locations 3000 meters around point_A from my database:
double newMeter = 3000 * 0.1 / 10000;
double lat1 = point_A.latitude - newMeter;
double lat2 = point_A.latitude + newMeter;
double lon1 = point_A.longitude - newMeter;
double lon1 = point_A.longitude + newMeter;
Cursor c = mDb.rawQuery("select * from TABLE1 where lat >= " + lat1 + " and lat <= " + lat2 + " and lon >= " + lon1 + " and lon <= " + lon2 + " order by id", null);
public double MeterToDegree(double meters, double latitude)
{
return meters / (111.32 * 1000 * Math.Cos(latitude * (Math.PI / 180)));
}
var meters = 50;
var coef = meters * 0.0000089;
var new_lat = map.getCenter().lat.apply() + coef;
var new_long = map.getCenter().lng.apply() + coef / Math.cos(new_lat * 0.018);
map.setCenter({lat:new_lat, lng:new_long});
See from Official Google Maps Documentation (link below) as they solve on easy/simple maps the problems with distance by countries :)
I recommended this solution to easy/simply solve issue with boundaries that you can know which area you're solving the problem with boundaries (not recommended globally)
Note:
Latitude lines run west-east and mark the position south-north of a point. Lines of latitude are called parallels and in total there are 180 degrees of latitude. The distance between each degree of latitude is about 69 miles (110 kilometers).
The distance between longitudes narrows the further away from the equator. The distance between longitudes at the equator is the same as latitude, roughly 69 miles (110 kilometers) . At 45 degrees north or south, the distance between is about 49 miles (79 kilometers). The distance between longitudes reaches zero at the poles as the lines of meridian converge at that point.
Original source 1
Original source 2
Official Google Maps Documentation: Code Example: Autocomplete Restricted to Multiple Countries
See the part of their code how they solve problem with distance center + 10 kilometers by +/- 0.1 degree
function initMap(): void {
const map = new google.maps.Map(
document.getElementById("map") as HTMLElement,
{
center: { lat: 50.064192, lng: -130.605469 },
zoom: 3,
}
);
const card = document.getElementById("pac-card") as HTMLElement;
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
const center = { lat: 50.064192, lng: -130.605469 };
// Create a bounding box with sides ~10km away from the center point
const defaultBounds = {
north: center.lat + 0.1,
south: center.lat - 0.1,
east: center.lng + 0.1,
west: center.lng - 0.1,
};
const input = document.getElementById("pac-input") as HTMLInputElement;
const options = {
bounds: defaultBounds,
componentRestrictions: { country: "us" },
fields: ["address_components", "geometry", "icon", "name"],
origin: center,
strictBounds: false,
types: ["establishment"],
};
This is what I did in VBA that seems to be working for me. Calculation is in feet not meters though
Public Function CalcLong(OrigLong As Double, OrigLat As Double, DirLong As String, DirLat As String, DistLong As Double, DistLat As Double)
Dim FT As Double
Dim NewLong, NewLat As Double
FT = 1 / ((2 * WorksheetFunction.Pi / 360) * 20902230.971129)
If DirLong = "W" Then
NewLat = CalcLat(OrigLong, OrigLat, DirLong, DirLat, DistLong, DistLat)
NewLong = OrigLong - ((FT * DistLong) / Cos(NewLat * (WorksheetFunction.Pi / 180)))
CalcLong = NewLong
Else
NewLong = OrigLong + ((FT * DistLong) / Math.Cos(CalcLat(OrigLong, OrigLat, DirLong, DirLat, DistLong, DistLat) * (WorksheetFunction.Pi / 180)))
CalcLong = NewLong
End If
End Function
Public Function CalcLat(OrigLong As Double, OrigLat As Double, DirLong As String, DirLat As String, DistLong As Double, DistLat As Double) As Double
Dim FT As Double
Dim NewLat As Double
FT = 1 / ((2 * WorksheetFunction.Pi / 360) * 20902230.971129)
If DirLat = "S" Then
NewLat = (OrigLat - (FT * DistLat))
CalcLat = NewLat
Else
NewLat = (OrigLat + (FT * DistLat))
CalcLat = NewLat
End If
End Function
Original poster said:
"So I have 50.0452345 (x) and 4.3242234 (y) and I want to know x + 500 meters..."
I will assume the units of the x and y values he gave there were in meters (and not degrees Longitude, Latitude). If so then he is stating measurements to 0.1 micrometer, so I will assume he needs similar accuracy for the translated output. I also will assume by "+500 meters" etc. he meant
the direction to be due North-South and due East-West.
He refers to a reference point:
"2 new latitudes based on a coordinate";
but he did not give the Longitude and Latitude,
so to explain the procedure concretely I will give
the Latitudes and Longitudes for the corners of the
500 meter box he requested around the point
[30 degrees Longitude,30 degrees Latitude].
The exact solution on the surface of the GRS80 Ellipsoid is
given with the following set of functions
(I wrote these for the free-open-source-mac-pc math program called "PARI"
which allows any number of digits precision to be setup):
\\=======Arc lengths along Latitude and Longitude and the respective scales:
dms(u)=[truncate(u),truncate((u-truncate(u))*60),((u-truncate(u))*60-truncate((u-truncate(u))*60))*60];
SpinEarthRadiansPerSec=7.292115e-5;\
GMearth=3986005e8;\
J2earth=108263e-8;\
re=6378137;\
ecc=solve(ecc=.0001,.9999,eccp=ecc/sqrt(1-ecc^2);qecc=(1+3/eccp^2)*atan(eccp)-3/eccp;ecc^2-(3*J2earth+4/15*SpinEarthRadiansPerSec^2*re^3/GMearth*ecc^3/qecc));\
e2=ecc^2;\
b2=1-e2;\
b=sqrt(b2);\
fl=1-b;\
rfl=1/fl;\
U0=GMearth/ecc/re*atan(eccp)+1/3*SpinEarthRadiansPerSec^2*re^2;\
HeightAboveEllipsoid=0;\
reh=re+HeightAboveEllipsoid;\
longscale(lat)=reh*Pi/648000/sqrt(1+b2*(tan(lat))^2);
latscale(lat)=reh*b*Pi/648000/(1-e2*(sin(lat))^2)^(3/2);
longarc(lat,long1,long2)=longscale(lat)*648000/Pi*(long2-long1);
latarc(lat1,lat2)=(intnum(th=lat1,lat2,sqrt(1-e2*(sin(th))^2))+e2/2*sin(2*lat1)/sqrt(1-e2*(sin(lat1))^2)-e2/2*sin(2*lat2)/sqrt(1-e2*(sin(lat2))^2))*reh;
\\=======
I then plugged the reference point [30,30]
into those functions at the PARI command prompt
and had PARI solve for the point +/- 500 meters away
from it, giving the two new Longitudes and
two new Latitudes that the original poster asked for.
Here is the input and output showing that:
? dms(solve(x=29,31,longarc(30*Pi/180,30*Pi/180,x*Pi/180)+500))
cpu time = 1 ms, real time = 1 ms.
%1172 = [29, 59, 41.3444979398934670450280297216509190843055]
? dms(solve(x=29,31,longarc(30*Pi/180,30*Pi/180,x*Pi/180)-500))
cpu time = 1 ms, real time = 1 ms.
%1173 = [30, 0, 18.6555020601065329549719702783490809156945]
? dms(solve(x=29,31,latarc(30*Pi/180,x*Pi/180)+500))
cpu time = 1,357 ms, real time = 1,358 ms.
%1174 = [29, 59, 43.7621925447500548285775757329518579545513]
? dms(solve(x=29,31,latarc(30*Pi/180,x*Pi/180)-500))
cpu time = 1,365 ms, real time = 1,368 ms.
%1175 = [30, 0, 16.2377963202802863245716034907838199823349]
?
i am using haversine formula to calculate distance but i am getting wrong distance actually google map distance is 8.1km but haversine formula is showing 4.06
private static final int EARTH_RADIUS = 6371; // Approx Earth radius in KM
public static double distance(double startLat, double startLong, double endLat, double endLong) {
double dLat = Math.toRadians((endLat - startLat));
double dLong = Math.toRadians((endLong - startLong));
startLat = Math.toRadians(startLat);
endLat = Math.toRadians(endLat);
double a = haversin(dLat) + Math.cos(startLat) * Math.cos(endLat) * haversin(dLong);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return EARTH_RADIUS * c; // <-- d
}
public static double haversin(double val) {
return Math.pow(Math.sin(val / 2), 2);
}
Your formula is correct, the problem come from bad use of google map
As suggested by Tim in comments, you need to see the point-to-point distance, not road distance
Using the two distance(17.451955, 78.478187, 17.442504, 78.441323) give 4.06km:
8.1km is probably the distance by road, and not point-to-point
I searched about a day now, but didnt find any example for my problem in Javacode.
I have a worldmap with a size of 2000*1400 Pixels with a 'Mollweide' projection.
How can I find out what is the longitude and laltitude of the point (500,300) in my map ?
I would like to code this in Java.
I tried to do this with the 'Java Map Projection Library' :
Point2D.Double pointonmap = null;
Point2D.Double latlon = null;
MolleweideProjection molproj=new MolleweideProjection();
pointonmap = new Point2D.Double (1400,1000);
latlon=molproj.inverseTransform(pointonmap,new Point2D.Double ());
System.out.println("latlon: " + latlon.getX() + ", " + latlon.getY());
Could anyone help me with that ? Codeexample or hint.
thanks and regards
Wikipedia has most of the information you need:
These formulas assume a few things, as usual.
They speak in projected dimension, which is smaller than the component.
[0,0] is at the centre, not top left.
Y coordinate goes up rather than goes down.
And the result is in radius instead of degree.
Fix these and they'll work for you.
Since you didn't provide a link, I assume you are using the Java Map Projection Library on GitHub.
Without documentation and with limited time, I can't understand inverseTransform well enough to fix your code; but the bundled MapComponent is simpler to code:
map.addMouseListener( new MouseAdapter() { #Override public void mouseClicked( MouseEvent e ) {
double x = e.getX() - map.getWidth() / 2, // Mouse X with [0,0] at centre.
y = e.getY() - map.getHeight() / 2, // Mouse Y with [0,0] at centre.
// Max Y of projected map, in pixel with [0,0] at centre.
maxY = map.getMapExtension().getMaxY() * map.getScaleToShowAll(),
sqrt2 = Math.sqrt( 2 ), // Can be optimised away, but let's be faithful.
R = maxY / sqrt2, // Radius of projection, in pixel.
theta = Math.asin( y / ( R * sqrt2 ) );
int delta_long = -lon0Slider.getValue(); // Longtitude shift from -180 to 180.
// Find lat long in radius and converts to degree.
double latInRad = Math.asin( -( 2 * theta + Math.sin( 2 * theta ) ) / Math.PI ),
latitude = Math.toDegrees( latInRad ),
longInRad = Math.PI * x / ( 2 * R * sqrt2 * Math.cos( theta ) ),
longitude = Math.toDegrees( longInRad ) + delta_long;
System.out.println( "Lat: " + latitude + ", Long: " + longitude );
}
You can paste this code into the constructor of ch.ethz.karto.gui.ProjectionSelectionPanel.
The IDE should reports that two methods of the map is private, and you need to change them to public first (or use reflection).
Then launch it, select Mollweide, click on the globe and watch the console. Feel free to resize the window.
This answer uses information from the English Wikipedia entry on Mollweide projection. I've pretty much transcribed the formula from there verbatim.
The short answer, so you can write your own code:
Get the map's radius, r:
projectionWidth /(2 * √2)
Get theta, the point's angle along the map:
arcsine(y / (r * √2))
Note: Arcsine is the inverse of sine. Use Math.asin(a) in java
Get the latitude:
arcsine((2 * theta + sine(2 * theta)) / PI)
Get the longitude:
PI * x / (2 * R * √2 * cosine(theta)) + central meridian.
Or you can copyPasta this.
It's not very efficient; x and y are spec as doubles becaus too lazy to write typecast avoid narrowing
no-setters no-getters all-vars public
all-world-one-love Dr. Bronner's TV-dinners solve your problems for you
and stuff
enoj
public class MolleweidePoint
{
public double x, y, latitude, longitude;
public MolleweidePoint(double projectionWidth, double x, double y)
{
double rootTwo = Math.sqrt(2);
double r = projectionWidth / 2 / rootTwo;
double theta = Math.asin(y / r / rootTwo);
this.x = x;
this.y = y;
longitude = Math.PI * x / 2 / r / rootTwo / Math.cos(theta);
latitude = Math.asin(2 * theta + Math.sin(2 * theta) / Math.PI);
}
}
After calling the constructor like
MolleweidePoint ted = new MolleweidePoint(projection.width, 300, 500)
you can get the latitude and longitude from ted.longitude and ted.latitude. Also, longitude may have to be adjusted based on where the central meridian is placed on your projection.
I have a task of being able to program a Class in Java to calculate the bearing from North to a point. The only objects that are known are 2 positions, both have a bearing from North and the distance from 0. So for example - position 1 - 30 degrees and 10m, position 2 - 190 degrees and 50m. How would you calculate the bearing if you wanted to travel from position 1 to position 2 for instance or from position 2 to 1? I can calculate the distance between the 2 positions using the cosine rule, but have no idea how to create a class that will accuratly calculate the bearing in different scenarios?
Any help or advise would be greatly appreciated.
From http://en.wikipedia.org/wiki/Law_of_cosines#Applications:
...once you have all three side lengths, this will give you the third angle of your triangle.
(The Haversine formula is for navigation on a sphere... I think we're just worried about vectors on a plane.)
I believe what you are looking for is the Haversine formula, googling it will yield implementations in various languages.
This is a java version ported from a javascript solution given here:
Using the Haversine Formula in Javascript by talkol
// this was a pojo class we used internally...
public class GisPostalCode {
private String country;
private String postalCode;
private double latitude;
private double longitude;
// getters/setters, etc.
}
public static double distanceBetweenCoordinatesInMiles2(GisPostalCode c1, GisPostalCode c2) {
double lat2 = c2.getLatitude();
double lon2 = c2.getLongitude();
double lat1 = c1.getLatitude();
double lon1 = c1.getLongitude();
double R = 6371; // km
double x1 = lat2 - lat1;
double dLat = x1 * Math.PI / 180;
double x2 = lon2 - lon1;
double dLon = x2 * Math.PI / 180;
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1*Math.PI/180) * Math.cos(lat2*Math.PI/180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;
// convert to miles
return d / 1.60934;
}