Find an object within an geographical area - java

I want a java function where if we pass the lat,long of a object, whether that object lies inside a area. Again this Area is defined by lat,long
for example I define a area with 3 lat/long positions.( a rectangle ) and if I pass a lat/long position it should return me whether its within the rectangle.

If the area is always a rectangle, the easiest way is to compare the coordinates.
Let's assume that your rectangle is defined by its upper left (r1x: lon and r1y: lat) and lower right (r2x and r2y) corners. Your object (a point) is defined by px: lon and py: lat.
So, your object is inside the area if
px > r1x and px < r2x
and
py < r1y and py > r2y
Programatically it would be something like:
boolean isPInR(double px, double py, double r1x, double r1y, double r2x, double r2y){
if(px > r1x && px < r2x && py < r1y && py > r2y){
//It is inside
return true;
}
return false;
}
EDIT
In the case where your polygon is not a rectangle, you can use the Java.awt.Polygon Class. In this class you will find the method contains(x,y) which return true if the point with x and y coordinates is inside the Polygon.
This method uses the Ray-casting algorithm. To simplify, this algorithm draw a segment in a random direction from your point. If the segment cross your polygon's boarder an odd number of times, then it is inside your polygon. If it crosses it an even number of times, then it is outside.
To use the polygon Class, you can do something like:
//This defines your polygon
int xCoord[] = {1,2,3,5,9,-5};
int yCoord[] = {18,-32,1,100,-100,0};
myPolygon = new Polygon(xCoord, yCoord, xCoord.length);
//This finds if the points defined by x and y coordinates is inside the polygon
Boolean isInside = myPolygon.contains(x,y);
And don't forget to
import java.awt.Polygon;
EDIT
Right coordinates are in Double !
So you need to use Path2D.Double !
Begin by import java.awt.geom.Path2D;
Let's say you start with similar arrays as before:
//This defines your polygon
Double xCoord[] = {1.00121,2,3.5464,5,9,-5};
Double yCoord[] = {18.147,-32,1,100,-100.32,0};
Path2D myPolygon = new Path2D.Double();
//Here you append all of your points to the polygon
for(int i = 0; i < xCoord.length; i++) {
myPolygon.moveTo(xCoord[i], yCoord[i]);
}
myPolygon.closePath();
//Now we want to know if the point x, y is inside the Polygon:
Double x; //The x coord
Double y; //The y coord
Boolean isInside = myPolygon.contains(x,y);
And here you go with Double !

Related

java find intersection of Line and Rectangle

So, i am programming a small game.
As the player, you fly a spaceship in 2d space.
I want to have a marker that points at a selected Object like a sun or a planet, if selected in the scanner.
Everything of that works fine except the drawing of the Marker at the screen border.
Here is my programm so far:
i first painted a Marker
Marker
In order to rotate the Marker, to let it point in direction of the object which is out of the screen, i use this Algorythm.
double Marker_vec = Math.toDegrees(Vector2F.getAngle( SolarSystem.object_vectors[marker],center,player.pos));
public static double getAngle(Vector2F v1, Vector2F v2, Vector2F fixed)
{
double angle1 = Math.atan2(v1.ypos - fixed.ypos, v1.xpos - fixed.xpos);
double angle2 = Math.atan2(v2.ypos - fixed.ypos, v2.xpos - fixed.xpos);
return angle1 - angle2;
}
Basically what i do is this, take a fixed point on the left side of the screen, the fixed point of the Players ship and the Object and get the Angle inbetween those two lines.
The resulting value is the degrees i have to turn my marker in.
And that works fine
Get angle
My problem is to display it on the edge of the screen.
My attempt to do so is that i create a Rectangle that fits the Screen:
screen_rec = new Rectangle(0,0,Main.width-1,Main.height-1);
Then i cut used the rectangles values of X,Y, width and height to create 4 Lines which together form the Rectangle around the screen.
Now i want to see if a line, drawn between the player and the selected Object intersects with any of the lines of the rectangle and get that point.
And finally display the rotated markerimage at those coordinates.
Here is my Code for that
marker_vec = Vector2F.getIntersectionPoint(line, Player.screen_rec);
public static Point intersection(Line2D lineA, Line2D lineB)
{
double x1 = lineA.getX1();
double y1 = lineA.getY1();
double x2 = lineA.getX2();
double y2 = lineA.getY2();
double x3 = lineB.getX1();
double y3 = lineB.getY1();
double x4 = lineB.getX2();
double y4 = lineB.getY2();
double d = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4);
if (d == 0) return null;
double xi = ((x3-x4)*(x1*y2-y1*x2)-(x1-x2)*(x3*y4-y3*x4))/d;
double yi = ((y3-y4)*(x1*y2-y1*x2)-(y1-y2)*(x3*y4-y3*x4))/d;
return new Point((int)xi,(int)yi);
}
public static Point[] getIntersectionPoint(Line2D line, Rectangle2D rectangle) {
Point[] p1 = new Point[4];
// Top line
p1[0] = intersection(line,
new Line2D.Double(
rectangle.getX(),
rectangle.getY(),
rectangle.getX() + rectangle.getWidth(),
rectangle.getY()));
// Bottom line
p1[1] = intersection(line,
new Line2D.Double(
rectangle.getX(),
rectangle.getY() + rectangle.getHeight(),
rectangle.getX() + rectangle.getWidth(),
rectangle.getY() + rectangle.getHeight()));
// Left side...
p1[2] = intersection(line,
new Line2D.Double(
rectangle.getX(),
rectangle.getY(),
rectangle.getX(),
rectangle.getY() + rectangle.getHeight()));
// Right side
p1[3] = intersection(line,
new Line2D.Double(
rectangle.getX() + rectangle.getWidth(),
rectangle.getY(),
rectangle.getX() + rectangle.getWidth(),
rectangle.getY() + rectangle.getHeight()));
return p1;
}
But somehow the Marker is displayed only at the upper and left sceenside.
I tried to solve it by subtracting the width in the xaxis in the drawing function, but that didnt work.
And those lines shouldnt have any intersectionpoints anyways, because the line between the player and the object does not intersect that rectangleline.
I will post images of how it looks in the comments
I just tried for serveral days and cant find any solution.
Thanks in advance
Spytrycer
I solved it. I got rid of the line:
if (d == 0) return null;
And the While where i drew the Markers was not going long enough.
Plus, i surrounded the draw functions with if and made sure the markers are only shown when the Angle is a specific value.

Java - How to check of a point is inside a sliceof a circle

I have a circle drawn, and I want to make it so I can have more slices than four. I can easily do four quadrants because I just check if the mouse in in the circle and inside a box.
This is how I am checking if the point is in the circle.
if( Math.sqrt((xx-x)*(xx-x) + (yy-y)*(yy-y)) <= radius)
{
return true;
}
else
{
return false;
}
How can I modify this if the circle is divided into more than 4 regions?
For radial slices (circular sectors), you have a couple of alternatives:
Use Math.atan2 to calculate the 4-quadrant angle of the line from the circle center to the point. Compare to the slice angles to determine the slice index.
For a particular slice, you can test which side of each slice edge the point falls. Classify the point accordingly. This is more complicated to calculate but probably faster (for a single slice) than calling Math.atan2.
The following sample code calculates the slice index for a particular point:
int sliceIndex(double xx, double yy, double x, double y, int nSlices) {
double angle = Math.atan2(yy - y, xx - x);
double sliceAngle = 2.0 * Math.PI / nSlices;
return (int) (angle / sliceAngle);
}
The above code makes the following assumptions:
slices are all the same (angular) width
slices are indexed counter-clockwise
slice 0 starts at the +x axis
slices own their right edge but not their left edge
You can adjust the calculations if these assumptions do not apply. (For instance, you can subtract the start angle from angle to eliminate assumption 3.)
First we can check that the point is within the circle as you did. But I woudln't combine this with a check for which quadrant (is that why you have radius/2 ?)
if( (xx-x)*(xx-x) + (yy-y)*(yy-y) > radius*radius)
return false;
Now we can look to see which region the point is in by using the atan2 function. atan2 is like Arctan except the Arctangent function always returns a value between -pi/2 and pi/2 (-90 and +90 degrees). We need the actual angle in polar coordinate fashion. Now assuming that (x,y) is the center of your circle and we are interested in the location of the point (xx,yy) we have
double theta = Math.atan2(yy-y,xx-x);
//theta is now in the range -Math.PI to Math.PI
if(theta<0)
theta = Math.PI - theta;
//Now theta is in the range [0, 2*pi]
//Use this value to determine which slice of the circle the point resides in.
//For example:
int numSlices = 8;
int whichSlice = 0;
double sliceSize = Math.PI*2 / numSlices;
double sliceStart;
for(int i=1; i<=numSlices; i++) {
sliceStart = i*sliceSize;
if(theta < sliceStart) {
whichSlice = i;
break;
}
}
//whichSlice should now be a number from 1 to 8 representing which part of the circle
// the point is in, where the slices are numbered 1 to numSlices starting with
// the right middle (positive x-axis if the center is (0,0).
It is more a trig problem Try something like this.
int numberOfSlices=8;
double angleInDegrees=(Math.toDegrees(Math.atan2(xx-x ,yy-y)));
long slice= Math.round(( numberOfSlices*angleInDegrees )/360 );

Flipping a polygon that contains many polygons to create an upside down mirror of everything

I have created a polygon with 6 vertices. Lets call this one, outside polygon. Inside the outside polygon I created smaller polygons. I want to flip all of it vertically one point at the time.
I know the vertices of the outside polygon and I have an ArrayList<Polygon> for the inner polygons. I was able to flip the outside polygon. but how do I flipped the inner polygons keeping their relative positions in the new one? I know the center of the outside polygon and the flipped version.
correction: I needed to flip horizontal.
I flipped the outer polygon (triangle shape), and I was able to move the inner polygons. but the distance is incorrect. this is a picture of what I have done,
(https://docs.google.com/drawings/d/1cPYJqxTWVu5gSHFQyHxHWSTysNzxJvNuJIwsgCQInfc/edit) https://docs.google.com/drawings/d/1cPYJqxTWVu5gSHFQyHxHWSTysNzxJvNuJIwsgCQInfc/edit
I tried this:
for (Polygon p : polygonList) {
Polygon tempP = new Polygon(p.xpoints, p.ypoints, p.npoints);
firstPointinPolygon = new Point(p.xpoints[0], p.ypoints[0]);
// find frist point in the polygon
float adjacent = (float) firstPointinPolygon.getX() - 400;
float opposite = (float) firstPointinPolygon.getY() - 400;
float hypotenuse = (float) Math.sqrt(opposite * opposite + adjacent * adjacent);
float cosine = adjacent / hypotenuse;
float sine = opposite / hypotenuse;
float endX = 400 * cosine;
float endY = 400 * sine;
float endXDelta =400-endX;
float endYDelta=400-endY;
Polygon pM = move(tempP, endX, endY);
polygonListMirror.add(pM);
tempP = new Polygon();
}
public Polygon move(Polygon p, double xMove, double yMove) {
// Change the values of the points for the Polygon
for (int i = 0; i < p.xpoints.length; i++) {
p.xpoints[i] += xMove;
p.ypoints[i] += yMove;
}
return p;
}
But did not get the result, I expected. What am I doing wrong? The end result should be like the picture in this link:
(https://docs.google.com/drawings/d/1vYdWkCelWW1_NUypNhtmckBYfEMzCf6bMVtoB-AyPkw/edit) https://docs.google.com/drawings/d/1vYdWkCelWW1_NUypNhtmckBYfEMzCf6bMVtoB-AyPkw/edit
I think something like this will do it:
Polygon outerPolygon, oldOuterPolygon;
ArrayList<Polygon> innerPolygons;
// set up objects
for (Polygon polygon: innerPolygons)
{
for (int i = 0; i < polygon.ypoints.length; i++)
{
polygon.ypoints[i] = center(outerPolygon) - polygon.ypoints[i] + center(oldOuterPolygon);
}
}
If you just to flip it vertically where it stands, such that the y-coordinate of top-most and bottom-most points just switch around, center for both should be the same (thus you can just say 2*center).
I'm pretty sure you can replace center(outerPolygon) and center(oldOuterPolygon) with any point from the applicable Polygon, as long as both use the same point.

How to check route by coordinates

I've got a problem: I have two coordinates (start and end point positions) and a polygon. I want to check whether this route is (1) from outside to inside of the polygon, (2) from inside to outside, (3) only inside, or (4) only outside.
I would really appreciate any help.
You are lucky! Java contains a Polygon class which has a method contains(double x, double y). Use it!
See this page:
http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
This function is taken from there.
It is based on the observation that a test point is within a polygon if when projected on the y-axis it's x value is below odd number of polygon edges. Works for both convex and concave polygons.
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
int i, j, c = 0;
for (i = 0, j = nvert-1; i < nvert; j = i++) {
if ( ((verty[i]>testy) != (verty[j]>testy)) &&
(testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
c = !c;
}
return c;
}

Put points round into circular arc used in java

I have me math question: I have known a circle center and radius, and have some uncertain number of points called N, my question is how to put the points on the circular arc, I cannot like put the points around the whole circumference, other as this link: http://i.6.cn/cvbnm/2c/93/b8/05543abdd33b198146d473a43e1049e6.png
in this link, you can read point is circle center, other color is some points, you can see these points around the arc.
Edit - in short: I have known a circle center and radius, so I want to generate some point around the circle center
I am not sure, but I checked this with simple Swing JComponent and seems ok.
Point center = new Point(100, 100); // circle center
int n = 5; // N
int r = 20; // radius
for (int i = 0; i < n; i++)
{
double fi = 2*Math.PI*i/n;
double x = r*Math.sin(fi + Math.PI) + center.getX();
double y = r*Math.cos(fi + Math.PI) + center.getY();
//g2.draw(new Line2D.Double(x, y, x, y));
}
It's not entirely clear what you're trying to accomplish here. The general idea of most of it is fairly simple though. There are 2*Pi radians in a circle, so once you've decided what part of a circle you want to arrange your points over, you multiply that percentage by 2*pi, and divide that result by the number of points to get the angle (in radians) between the points.
To get from angular distances to positions, you take the cosine and sine of the angle, and multiply each by the radius of the circle to get the x and y coordinate of the point relative to the center of the circle. For this purpose, an angle of 0 radians goes directly to the right from the center, and angles progress counter-clockwise from there.

Categories

Resources