I have searched for lot of threads but still I am facing the issue.
I have to find out if a lat/lng is inside or outside the polygon. I have used following method:
private boolean LineIntersect(LatLng tap, LatLng vertA, LatLng vertB) {
double aY = vertA.latitude;
double bY = vertB.latitude;
double aX = vertA.longitude;
double bX = vertB.longitude;
double pY = tap.latitude;
double pX = tap.longitude;
if ( (aY>pY && bY>pY) || (aY<pY && bY<pY) || (aX<pX && bX<pX) ) {
return false; }
double m = (aY-bY) / (aX-bX);
double bee = (-aX) * m + aY; // y = mx + b
double x = (pY - bee) / m;
return x > pX;
}
private boolean isPointInPolygon(LatLng tap, ArrayList<LatLng> vertices) {
int intersectCount = 0;
for(int j=0; j<vertices.size()-1; j++) {
if( LineIntersect(tap, vertices.get(j), vertices.get(j+1)) ) {
intersectCount++;
}
}
return ((intersectCount%2)==1); // odd = inside, even = outside;
}
I am calling it as:
if(isPointInPolygon(mLatLng, points))
{
Toast.makeText(getApplicationContext(), "inside",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "outside",
Toast.LENGTH_LONG).show();
}
The problem I am getting is, when I am inside the geofence I am getting both true and false. WHenever I am inside the geofence I am getting 2 toasts inside and outside both. Please let me know where I am wrong.
I have created geofence app that successfully worked
here is the code i used this https://github.com/sromku/polygon-contains-point to figure out our location inside or outside of polygon.
here is the code
public class MainActivity extends Activity {
private double Longitude, Latitude;
private LocationListener locListener;
private LocationManager lm;
private ProgressDialog gpsProgressDialog;
private Button button_gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_gps = (Button)findViewById(R.id.button_gps);
lm = (LocationManager) MainActivity.this.getSystemService(MainActivity.this.LOCATION_SERVICE);
button_gps.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
getLoction();
// testSimplePolygon();
// testPolygonWithHoles();
}
});
}
class GpsLogation implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
lm.removeUpdates(locListener);
Longitude = location.getLongitude();
Latitude = location.getLatitude();
/* Toast.makeText(MainActivity.this,
"Longitude :" + Longitude + " Latitude :" + Latitude,
Toast.LENGTH_LONG).show();*/
Polygon polygon = Polygon.Builder()
.addVertex(new Point(6.048857f, 80.211021f)) // change polygon according to your location
.addVertex(new Point(6.048137f, 80.210546f))
.addVertex(new Point(6.048590f, 80.210197f))
.addVertex(new Point(6.049163f, 80.211050f)).build();
// isInside(polygon, new Point((float)Latitude, (float)Longitude));
if( polygon.contains(new Point((float)Latitude, (float)Longitude))==true)
{
Toast.makeText(MainActivity.this, "You are inside", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this, "You are outside", Toast.LENGTH_LONG).show();
}
// /////////////do something//////////////
// insertSalesOrder();
Log.i("TTTAG", "Latitude:" + Latitude);
Log.i("TTTAG", "Longitude:" + Longitude);
if (gpsProgressDialog.isShowing()) {
gpsProgressDialog.dismiss();
}
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
public void getLoction() {
locListener = new GpsLogation();
boolean enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Toast.makeText(MainActivity.this, "Please switch on the GPS",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(intent);
return;
}
Log.i("GPS INFO", " OK Gps Is ON");
gpsProgressDialog = ProgressDialog.show(MainActivity.this, "", "Please wait ... ", true);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locListener);
}
// Here is the polygon java class and i'm not author of it
public class Polygon
{
private final BoundingBox _boundingBox;
private final List<Line> _sides;
private Polygon(List<Line> sides, BoundingBox boundingBox)
{
_sides = sides;
_boundingBox = boundingBox;
}
/**
* Get the builder of the polygon
*
* #return The builder
*/
public static Builder Builder()
{
return new Builder();
}
/**
* Builder of the polygon
*
* #author Roman Kushnarenko (sromku#gmail.com)
*/
public static class Builder
{
private List<Point> _vertexes = new ArrayList<Point>();
private List<Line> _sides = new ArrayList<Line>();
private BoundingBox _boundingBox = null;
private boolean _firstPoint = true;
private boolean _isClosed = false;
/**
* Add vertex points of the polygon.<br>
* It is very important to add the vertexes by order, like you were drawing them one by one.
*
* #param point
* The vertex point
* #return The builder
*/
public Builder addVertex(Point point)
{
if (_isClosed)
{
// each hole we start with the new array of vertex points
_vertexes = new ArrayList<Point>();
_isClosed = false;
}
updateBoundingBox(point);
_vertexes.add(point);
// add line (edge) to the polygon
if (_vertexes.size() > 1)
{
Line Line = new Line(_vertexes.get(_vertexes.size() - 2), point);
_sides.add(Line);
}
return this;
}
/**
* Close the polygon shape. This will create a new side (edge) from the <b>last</b> vertex point to the <b>first</b> vertex point.
*
* #return The builder
*/
public Builder close()
{
validate();
// add last Line
_sides.add(new Line(_vertexes.get(_vertexes.size() - 1), _vertexes.get(0)));
_isClosed = true;
return this;
}
/**
* Build the instance of the polygon shape.
*
* #return The polygon
*/
public Polygon build()
{
validate();
// in case you forgot to close
if (!_isClosed)
{
// add last Line
_sides.add(new Line(_vertexes.get(_vertexes.size() - 1), _vertexes.get(0)));
}
Polygon polygon = new Polygon(_sides, _boundingBox);
return polygon;
}
/**
* Update bounding box with a new point.<br>
*
* #param point
* New point
*/
private void updateBoundingBox(Point point)
{
if (_firstPoint)
{
_boundingBox = new BoundingBox();
_boundingBox.xMax = point.x;
_boundingBox.xMin = point.x;
_boundingBox.yMax = point.y;
_boundingBox.yMin = point.y;
_firstPoint = false;
}
else
{
// set bounding box
if (point.x > _boundingBox.xMax)
{
_boundingBox.xMax = point.x;
}
else if (point.x < _boundingBox.xMin)
{
_boundingBox.xMin = point.x;
}
if (point.y > _boundingBox.yMax)
{
_boundingBox.yMax = point.y;
}
else if (point.y < _boundingBox.yMin)
{
_boundingBox.yMin = point.y;
}
}
}
private void validate()
{
if (_vertexes.size() < 3)
{
throw new RuntimeException("Polygon must have at least 3 points");
}
}
}
/**
* Check if the the given point is inside of the polygon.<br>
*
* #param point
* The point to check
* #return <code>True</code> if the point is inside the polygon, otherwise return <code>False</code>
*/
public boolean contains(Point point)
{
if (inBoundingBox(point))
{
Line ray = createRay(point);
int intersection = 0;
for (Line side : _sides)
{
if (intersect(ray, side))
{
// System.out.println("intersection++");
intersection++;
}
}
/*
* If the number of intersections is odd, then the point is inside the polygon
*/
if (intersection % 2 == 1)
{
return true;
}
}
return false;
}
public List<Line> getSides()
{
return _sides;
}
/**
* By given ray and one side of the polygon, check if both lines intersect.
*
* #param ray
* #param side
* #return <code>True</code> if both lines intersect, otherwise return <code>False</code>
*/
private boolean intersect(Line ray, Line side)
{
Point intersectPoint = null;
// if both vectors aren't from the kind of x=1 lines then go into
if (!ray.isVertical() && !side.isVertical())
{
// check if both vectors are parallel. If they are parallel then no intersection point will exist
if (ray.getA() - side.getA() == 0)
{
return false;
}
float x = ((side.getB() - ray.getB()) / (ray.getA() - side.getA())); // x = (b2-b1)/(a1-a2)
float y = side.getA() * x + side.getB(); // y = a2*x+b2
intersectPoint = new Point(x, y);
}
else if (ray.isVertical() && !side.isVertical())
{
float x = ray.getStart().x;
float y = side.getA() * x + side.getB();
intersectPoint = new Point(x, y);
}
else if (!ray.isVertical() && side.isVertical())
{
float x = side.getStart().x;
float y = ray.getA() * x + ray.getB();
intersectPoint = new Point(x, y);
}
else
{
return false;
}
// System.out.println("Ray: " + ray.toString() + " ,Side: " + side);
// System.out.println("Intersect point: " + intersectPoint.toString());
if (side.isInside(intersectPoint) && ray.isInside(intersectPoint))
{
return true;
}
return false;
}
/**
* Create a ray. The ray will be created by given point and on point outside of the polygon.<br>
* The outside point is calculated automatically.
*
* #param point
* #return
*/
private Line createRay(Point point)
{
// create outside point
float epsilon = (_boundingBox.xMax - _boundingBox.xMin) / 100f;
Point outsidePoint = new Point(_boundingBox.xMin - epsilon, _boundingBox.yMin);
Line vector = new Line(outsidePoint, point);
return vector;
}
/**
* Check if the given point is in bounding box
*
* #param point
* #return <code>True</code> if the point in bounding box, otherwise return <code>False</code>
*/
private boolean inBoundingBox(Point point)
{
if (point.x < _boundingBox.xMin || point.x > _boundingBox.xMax || point.y < _boundingBox.yMin || point.y > _boundingBox.yMax)
{
return false;
}
return true;
}
private static class BoundingBox
{
public float xMax = Float.NEGATIVE_INFINITY;
public float xMin = Float.NEGATIVE_INFINITY;
public float yMax = Float.NEGATIVE_INFINITY;
public float yMin = Float.NEGATIVE_INFINITY;
}
}
//// Here is the Line java class and i'm not author of it
public class Line
{
private final Point _start;
private final Point _end;
private float _a = Float.NaN;
private float _b = Float.NaN;
private boolean _vertical = false;
public Line(Point start, Point end)
{
_start = start;
_end = end;
if (_end.x - _start.x != 0)
{
_a = ((_end.y - _start.y) / (_end.x - _start.x));
_b = _start.y - _a * _start.x;
}
else
{
_vertical = true;
}
}
/**
* Indicate whereas the point lays on the line.
*
* #param point
* - The point to check
* #return <code>True</code> if the point lays on the line, otherwise return <code>False</code>
*/
public boolean isInside(Point point)
{
float maxX = _start.x > _end.x ? _start.x : _end.x;
float minX = _start.x < _end.x ? _start.x : _end.x;
float maxY = _start.y > _end.y ? _start.y : _end.y;
float minY = _start.y < _end.y ? _start.y : _end.y;
if ((point.x >= minX && point.x <= maxX) && (point.y >= minY && point.y <= maxY))
{
return true;
}
return false;
}
/**
* Indicate whereas the line is vertical. <br>
* For example, line like x=1 is vertical, in other words parallel to axis Y. <br>
* In this case the A is (+/-)infinite.
*
* #return <code>True</code> if the line is vertical, otherwise return <code>False</code>
*/
public boolean isVertical()
{
return _vertical;
}
/**
* y = <b>A</b>x + B
*
* #return The <b>A</b>
*/
public float getA()
{
return _a;
}
/**
* y = Ax + <b>B</b>
*
* #return The <b>B</b>
*/
public float getB()
{
return _b;
}
/**
* Get start point
*
* #return The start point
*/
public Point getStart()
{
return _start;
}
/**
* Get end point
*
* #return The end point
*/
public Point getEnd()
{
return _end;
}
#Override
public String toString()
{
return String.format("%s-%s", _start.toString(), _end.toString());
}
}
//// Here is the point java class and i'm not author of it
public class Point
{
public Point(float x, float y)
{
this.x = x;
this.y = y;
}
public float x;
public float y;
#Override
public String toString()
{
return String.format("(%.2f,%.2f)", x, y);
}
}
/*I coded only Mainactivity class other owner of other classes is https://github.com/sromku and all credit goes to him*/
Related
I'm using google directions api to draw a polyline for a route. Does anyone have any examples of checking if current location is on/near a polyline? Trying to determine if users current location is within x meters of that line and if not i'll make a new request and redraw a new route.
Cheers!
Here is my solution: just add the bdccGeoDistanceAlgorithm class I have created to your project and use bdccGeoDistanceCheckWithRadius method to check if your current location is on or near polyline (polyline equals to a list of LatLng of points)
Your can also get the distance from the method
Class bdccGeoDistanceAlgorithm
import com.google.android.gms.maps.model.LatLng;
import java.util.List;
public class bdccGeoDistanceAlgorithm {
// distance in meters from GLatLng point to GPolyline or GPolygon poly
public static boolean bdccGeoDistanceCheckWithRadius(List<LatLng> poly, LatLng point, int radius)
{
int i;
bdccGeo p = new bdccGeo(point.latitude,point.longitude);
for(i=0; i < (poly.size()-1) ; i++)
{
LatLng p1 = poly.get(i);
bdccGeo l1 = new bdccGeo(p1.latitude,p1.longitude);
LatLng p2 = poly.get(i+1);
bdccGeo l2 = new bdccGeo(p2.latitude,p2.longitude);
double distance = p.function_distanceToLineSegMtrs(l1, l2);
if(distance < radius)
return true;
}
return false;
}
// object
public static class bdccGeo
{
public double lat;
public double lng;
public double x;
public double y;
public double z;
public bdccGeo(double lat, double lon) {
this.lat = lat;
this.lng = lng;
double theta = (lon * Math.PI / 180.0);
double rlat = function_bdccGeoGeocentricLatitude(lat * Math.PI / 180.0);
double c = Math.cos(rlat);
this.x = c * Math.cos(theta);
this.y = c * Math.sin(theta);
this.z = Math.sin(rlat);
}
//returns in meters the minimum of the perpendicular distance of this point from the line segment geo1-geo2
//and the distance from this point to the line segment ends in geo1 and geo2
public double function_distanceToLineSegMtrs(bdccGeo geo1,bdccGeo geo2)
{
//point on unit sphere above origin and normal to plane of geo1,geo2
//could be either side of the plane
bdccGeo p2 = geo1.function_crossNormalize(geo2);
// intersection of GC normal to geo1/geo2 passing through p with GC geo1/geo2
bdccGeo ip = function_bdccGeoGetIntersection(geo1,geo2,this,p2);
//need to check that ip or its antipode is between p1 and p2
double d = geo1.function_distance(geo2);
double d1p = geo1.function_distance(ip);
double d2p = geo2.function_distance(ip);
//window.status = d + ", " + d1p + ", " + d2p;
if ((d >= d1p) && (d >= d2p))
return function_bdccGeoRadiansToMeters(this.function_distance(ip));
else
{
ip = ip.function_antipode();
d1p = geo1.function_distance(ip);
d2p = geo2.function_distance(ip);
}
if ((d >= d1p) && (d >= d2p))
return function_bdccGeoRadiansToMeters(this.function_distance(ip));
else
return function_bdccGeoRadiansToMeters(Math.min(geo1.function_distance(this),geo2.function_distance(this)));
}
// More Maths
public bdccGeo function_crossNormalize(bdccGeo b)
{
double x = (this.y * b.z) - (this.z * b.y);
double y = (this.z * b.x) - (this.x * b.z);
double z = (this.x * b.y) - (this.y * b.x);
double L = Math.sqrt((x * x) + (y * y) + (z * z));
bdccGeo r = new bdccGeo(0,0);
r.x = x / L;
r.y = y / L;
r.z = z / L;
return r;
}
// Returns the two antipodal points of intersection of two great
// circles defined by the arcs geo1 to geo2 and
// geo3 to geo4. Returns a point as a Geo, use .antipode to get the other point
public bdccGeo function_bdccGeoGetIntersection(bdccGeo geo1,bdccGeo geo2, bdccGeo geo3,bdccGeo geo4)
{
bdccGeo geoCross1 = geo1.function_crossNormalize(geo2);
bdccGeo geoCross2 = geo3.function_crossNormalize(geo4);
return geoCross1.function_crossNormalize(geoCross2);
}
public double function_distance(bdccGeo v2)
{
return Math.atan2(v2.function_crossLength(this), v2.function_dot(this));
}
//More Maths
public double function_crossLength(bdccGeo b)
{
double x = (this.y * b.z) - (this.z * b.y);
double y = (this.z * b.x) - (this.x * b.z);
double z = (this.x * b.y) - (this.y * b.x);
return Math.sqrt((x * x) + (y * y) + (z * z));
}
//Maths
public double function_dot(bdccGeo b)
{
return ((this.x * b.x) + (this.y * b.y) + (this.z * b.z));
}
//from Radians to Meters
public double function_bdccGeoRadiansToMeters(double rad)
{
return rad * 6378137.0; // WGS84 Equatorial Radius in Meters
}
// point on opposite side of the world to this point
public bdccGeo function_antipode()
{
return this.function_scale(-1.0);
}
//More Maths
public bdccGeo function_scale(double s)
{
bdccGeo r = new bdccGeo(0,0);
r.x = this.x * s;
r.y = this.y * s;
r.z = this.z * s;
return r;
}
// Convert from geographic to geocentric latitude (radians).
public double function_bdccGeoGeocentricLatitude(double geographicLatitude)
{
double flattening = 1.0 / 298.257223563;//WGS84
double f = (1.0 - flattening) * (1.0 - flattening);
return Math.atan((Math.tan(geographicLatitude) * f));
}
}
}
I copy-pasted a basic android snake game code in android studio from here
But i get
java.lang.RuntimeException: Unable to start activity ComponentInfo..........Snake}:
android.view.InflateException: Binary XML file line #5: Error inflating class com.example.android.snake.SnakeView
and the line of error shows that setContentView(R.layout.activity_main); has the error.
I checked various similar questions in stackoverflow, but being an absolute beginner i couldnt figure out what the actual problem is.
EDIT:
heres the snake.java:
package com.example.bharatchamakuri.snakefinal;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
public class Snake extends Activity {
private SnakeView mSnakeView;
private static String ICICLE_KEY = "snake-view";
/**
* Called when Activity is first created. Turns off the title bar, sets up
* the content views, and fires up the SnakeView.
*
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// No Title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mSnakeView = (SnakeView) findViewById(R.id.snake);
mSnakeView.setTextView((TextView) findViewById(R.id.text));
// Register the listener
mSnakeView.setOnTouchListener((View.OnTouchListener) mSnakeView);
if (savedInstanceState == null) {
// We were just launched -- set up a new game
mSnakeView.setMode(SnakeView.READY);
} else {
// We are being restored
Bundle map = savedInstanceState.getBundle(ICICLE_KEY);
if (map != null) {
mSnakeView.restoreState(map);
} else {
mSnakeView.setMode(SnakeView.PAUSE);
}
}
}
#Override
protected void onPause() {
super.onPause();
// Pause the game along with the activity
mSnakeView.setMode(SnakeView.PAUSE);
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Store the game state
outState.putBundle(ICICLE_KEY, mSnakeView.saveState());
}
}
snakeview.java file :
package com.example.bharatchamakuri.snakefinal;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
/**
* Current mode of application: READY to run, RUNNING, or you have already
* lost. static final ints are used instead of an enum for performance
* reasons.
*/
public class SnakeView extends TileView {
private static final String TAG = "SnakeView";
private int mMode = READY;
public static final int PAUSE = 0;
public static final int READY = 1;
public static final int RUNNING = 2;
public static final int LOSE = 3;
/**
* Current direction the snake is headed.
*/
private int mDirection = NORTH;
private int mNextDirection = NORTH;
private static final int NORTH = 1;
private static final int SOUTH = 2;
private static final int EAST = 3;
private static final int WEST = 4;
/**
* Labels for the drawables that will be loaded into the TileView class
*/
private static final int RED_STAR = 1;
private static final int YELLOW_STAR = 2;
private static final int GREEN_STAR = 3;
/**
* mScore: used to track the number of apples captured mMoveDelay: number of
* milliseconds between snake movements. This will decrease as apples are
* captured.
*/
private long mScore = 0;
private long mMoveDelay = 600;
/**
* mLastMove: tracks the absolute time when the snake last moved, and is
* used to determine if a move should be made based on mMoveDelay.
*/
private long mLastMove;
/**
* mStatusText: text shows to the user in some run states
*/
private TextView mStatusText;
/**
* mSnakeTrail: a list of Coordinates that make up the snake's body
* mAppleList: the secret location of the juicy apples the snake craves.
*/
private ArrayList<Coordinate> mSnakeTrail = new ArrayList<Coordinate>();
private ArrayList<Coordinate> mAppleList = new ArrayList<Coordinate>();
/**
* Everyone needs a little randomness in their life
*/
private static final Random RNG = new Random();
/**
* Create a simple handler that we can use to cause animation to happen. We
* set ourselves as a target and we can use the sleep() function to cause an
* update/invalidate to occur at a later date.
*/
private RefreshHandler mRedrawHandler = new RefreshHandler();
class RefreshHandler extends Handler {
#Override
public void handleMessage(Message msg) {
SnakeView.this.update();
SnakeView.this.invalidate();
}
public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
};
/**
* Constructs a SnakeView based on inflation from XML
*
* #param context
* #param attrs
*/
public SnakeView(Context context, AttributeSet attrs) {
super(context, attrs);
initSnakeView();
}
public SnakeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initSnakeView();
}
private void initSnakeView() {
setFocusable(true);
Resources r = this.getContext().getResources();
resetTiles(4);
loadTile(RED_STAR, r.getDrawable(R.drawable.redstar));
loadTile(YELLOW_STAR, r.getDrawable(R.drawable.yellowstar));
loadTile(GREEN_STAR, r.getDrawable(R.drawable.bluestar));
}
private void initNewGame() {
mSnakeTrail.clear();
mAppleList.clear();
// For now we're just going to load up a short default eastbound snake
// that's just turned north
mSnakeTrail.add(new Coordinate(7, 7));
mSnakeTrail.add(new Coordinate(6, 7));
mSnakeTrail.add(new Coordinate(5, 7));
mSnakeTrail.add(new Coordinate(4, 7));
mSnakeTrail.add(new Coordinate(3, 7));
mSnakeTrail.add(new Coordinate(2, 7));
mNextDirection = NORTH;
// Two apples to start with
addRandomApple();
addRandomApple();
mMoveDelay = 600;
mScore = 0;
}
/**
* Given a ArrayList of coordinates, we need to flatten them into an array
* of ints before we can stuff them into a map for flattening and storage.
*
* #param cvec
* : a ArrayList of Coordinate objects
* #return : a simple array containing the x/y values of the coordinates as
* [x1,y1,x2,y2,x3,y3...]
*/
private int[] coordArrayListToArray(ArrayList<Coordinate> cvec) {
int count = cvec.size();
int[] rawArray = new int[count * 2];
for (int index = 0; index < count; index++) {
Coordinate c = cvec.get(index);
rawArray[2 * index] = c.x;
rawArray[2 * index + 1] = c.y;
}
return rawArray;
}
/**
* Save game state so that the user does not lose anything if the game
* process is killed while we are in the background.
*
* #return a Bundle with this view's state
*/
public Bundle saveState() {
Bundle map = new Bundle();
map.putIntArray("mAppleList", coordArrayListToArray(mAppleList));
map.putInt("mDirection", mDirection);
map.putInt("mNextDirection", mNextDirection);
map.putLong("mMoveDelay", mMoveDelay);
map.putLong("mScore", mScore);
map.putIntArray("mSnakeTrail", coordArrayListToArray(mSnakeTrail));
return map;
}
/**
* Given a flattened array of ordinate pairs, we reconstitute them into a
* ArrayList of Coordinate objects
*
* #param rawArray
* : [x1,y1,x2,y2,...]
* #return a ArrayList of Coordinates
*/
private ArrayList<Coordinate> coordArrayToArrayList(int[] rawArray) {
ArrayList<Coordinate> coordArrayList = new ArrayList<Coordinate>();
int coordCount = rawArray.length;
for (int index = 0; index < coordCount; index += 2) {
Coordinate c = new Coordinate(rawArray[index], rawArray[index + 1]);
coordArrayList.add(c);
}
return coordArrayList;
}
/**
* Restore game state if our process is being relaunched
*
* #param icicle
* a Bundle containing the game state
*/
public void restoreState(Bundle icicle) {
setMode(PAUSE);
mAppleList = coordArrayToArrayList(icicle.getIntArray("mAppleList"));
mDirection = icicle.getInt("mDirection");
mNextDirection = icicle.getInt("mNextDirection");
mMoveDelay = icicle.getLong("mMoveDelay");
mScore = icicle.getLong("mScore");
mSnakeTrail = coordArrayToArrayList(icicle.getIntArray("mSnakeTrail"));
}
/*
* handles key events in the game. Update the direction our snake is
* traveling based on the DPAD. Ignore events that would cause the snake to
* immediately turn back on itself.
*
* (non-Javadoc)
*
* #see android.view.View#onKeyDown(int, android.os.KeyEvent)
*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent msg) {
if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
if (mMode == READY | mMode == LOSE) {
/*
* At the beginning of the game, or the end of a previous one,
* we should start a new game.
*/
initNewGame();
setMode(RUNNING);
update();
return (true);
}
if (mMode == PAUSE) {
/*
* If the game is merely paused, we should just continue where
* we left off.
*/
setMode(RUNNING);
update();
return (true);
}
if (mDirection != SOUTH) {
mNextDirection = NORTH;
}
return (true);
}
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
if (mDirection != NORTH) {
mNextDirection = SOUTH;
}
return (true);
}
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
if (mDirection != EAST) {
mNextDirection = WEST;
}
return (true);
}
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
if (mDirection != WEST) {
mNextDirection = EAST;
}
return (true);
}
return super.onKeyDown(keyCode, msg);
}
public boolean onTouch (View v, MotionEvent event)
{
float x = event.getX();
float y = event.getY();
float height = this.getHeight();
float width = this.getWidth();
float slope = height/width;
// Only process DOWN action, so it responds as soon as the
// screen is touched.
if (event.getAction()==MotionEvent.ACTION_DOWN)
{
// Touch event UP
if ((y < slope*x) && (y < -slope*x + height)) {
if (mMode == READY | mMode == LOSE) {
// At the beginning of the game, or the end of a previous one,
// we should start a new game.
initNewGame();
setMode(RUNNING);
update();
return (true);
}
if (mMode == PAUSE) {
// If the game is merely paused, we should just continue where
// we left off.
setMode(RUNNING);
update();
return (true);
}
if (mDirection != SOUTH) {
mNextDirection = NORTH;
}
return (true);
}
// Touch event DOWN
if ((y > slope*x) && (y > -slope*x + height)) {
if (mDirection != NORTH) {
mNextDirection = SOUTH;
}
return (true);
}
// Touch event LEFT
if ((y > slope*x) && (y < (-slope*x + height))) {
if (mDirection != EAST) {
mNextDirection = WEST;
}
return (true);
}
// Touch event RIGHT
if ((y < slope*x) && (y > -slope*x + height)) {
if (mDirection != WEST) {
mNextDirection = EAST;
}
return (true);
}
}
return false;
}
/**
* Sets the TextView that will be used to give information (such as "Game
* Over" to the user.
*
* #param newView
*/
public void setTextView(TextView newView) {
mStatusText = newView;
}
/**
* Updates the current mode of the application (RUNNING or PAUSED or the
* like) as well as sets the visibility of textview for notification
*
* #param newMode
*/
public void setMode(int newMode) {
int oldMode = mMode;
mMode = newMode;
if (newMode == RUNNING & oldMode != RUNNING) {
mStatusText.setVisibility(View.INVISIBLE);
update();
return;
}
Resources res = getContext().getResources();
CharSequence str = "";
if (newMode == PAUSE) {
str = res.getText(R.string.mode_pause);
}
if (newMode == READY) {
str = res.getText(R.string.mode_ready);
}
if (newMode == LOSE) {
str = res.getString(R.string.mode_lose_prefix) + mScore
+ res.getString(R.string.mode_lose_suffix);
}
mStatusText.setText(str);
mStatusText.setVisibility(View.VISIBLE);
}
/**
* Selects a random location within the garden that is not currently covered
* by the snake. Currently _could_ go into an infinite loop if the snake
* currently fills the garden, but we'll leave discovery of this prize to a
* truly excellent snake-player.
*
*/
private void addRandomApple() {
Coordinate newCoord = null;
boolean found = false;
while (!found) {
// Choose a new location for our apple
int newX = 1 + RNG.nextInt(mXTileCount - 2);
int newY = 1 + RNG.nextInt(mYTileCount - 2);
newCoord = new Coordinate(newX, newY);
// Make sure it's not already under the snake
boolean collision = false;
int snakelength = mSnakeTrail.size();
for (int index = 0; index < snakelength; index++) {
if (mSnakeTrail.get(index).equals(newCoord)) {
collision = true;
}
}
// if we're here and there's been no collision, then we have
// a good location for an apple. Otherwise, we'll circle back
// and try again
found = !collision;
}
if (newCoord == null) {
Log.e(TAG, "Somehow ended up with a null newCoord!");
}
mAppleList.add(newCoord);
}
/**
* Handles the basic update loop, checking to see if we are in the running
* state, determining if a move should be made, updating the snake's
* location.
*/
public void update() {
if (mMode == RUNNING) {
long now = System.currentTimeMillis();
if (now - mLastMove > mMoveDelay) {
clearTiles();
updateWalls();
updateSnake();
updateApples();
mLastMove = now;
}
mRedrawHandler.sleep(mMoveDelay);
}
}
/**
* Draws some walls.
*
*/
private void updateWalls() {
for (int x = 0; x < mXTileCount; x++) {
setTile(GREEN_STAR, x, 0);
setTile(GREEN_STAR, x, mYTileCount - 1);
}
for (int y = 1; y < mYTileCount - 1; y++) {
setTile(GREEN_STAR, 0, y);
setTile(GREEN_STAR, mXTileCount - 1, y);
}
}
/**
* Draws some apples.
*
*/
private void updateApples() {
for (Coordinate c : mAppleList) {
setTile(YELLOW_STAR, c.x, c.y);
}
}
/**
* Figure out which way the snake is going, see if he's run into anything
* (the walls, himself, or an apple). If he's not going to die, we then add
* to the front and subtract from the rear in order to simulate motion. If
* we want to grow him, we don't subtract from the rear.
*
*/
private void updateSnake() {
boolean growSnake = false;
// grab the snake by the head
Coordinate head = mSnakeTrail.get(0);
Coordinate newHead = new Coordinate(1, 1);
mDirection = mNextDirection;
switch (mDirection) {
case EAST: {
newHead = new Coordinate(head.x + 1, head.y);
break;
}
case WEST: {
newHead = new Coordinate(head.x - 1, head.y);
break;
}
case NORTH: {
newHead = new Coordinate(head.x, head.y - 1);
break;
}
case SOUTH: {
newHead = new Coordinate(head.x, head.y + 1);
break;
}
}
// Collision detection
// For now we have a 1-square wall around the entire arena
if ((newHead.x < 1) || (newHead.y < 1) || (newHead.x > mXTileCount - 2)
|| (newHead.y > mYTileCount - 2)) {
setMode(LOSE);
return;
}
// Look for collisions with itself
int snakelength = mSnakeTrail.size();
for (int snakeindex = 0; snakeindex < snakelength; snakeindex++) {
Coordinate c = mSnakeTrail.get(snakeindex);
if (c.equals(newHead)) {
setMode(LOSE);
return;
}
}
// Look for apples
int applecount = mAppleList.size();
for (int appleindex = 0; appleindex < applecount; appleindex++) {
Coordinate c = mAppleList.get(appleindex);
if (c.equals(newHead)) {
mAppleList.remove(c);
addRandomApple();
mScore++;
mMoveDelay *= 0.9;
growSnake = true;
}
}
// push a new head onto the ArrayList and pull off the tail
mSnakeTrail.add(0, newHead);
// except if we want the snake to grow
if (!growSnake) {
mSnakeTrail.remove(mSnakeTrail.size() - 1);
}
int index = 0;
for (Coordinate c : mSnakeTrail) {
if (index == 0) {
setTile(YELLOW_STAR, c.x, c.y);
} else {
setTile(RED_STAR, c.x, c.y);
}
index++;
}
}
/**
* Simple class containing two integer values and a comparison function.
* There's probably something I should use instead, but this was quick and
* easy to build.
*
*/
private class Coordinate {
public int x;
public int y;
public Coordinate(int newX, int newY) {
x = newX;
y = newY;
}
public boolean equals(Coordinate other) {
if (x == other.x && y == other.y) {
return true;
}
return false;
}
#Override
public String toString() {
return "Coordinate: [" + x + "," + y + "]";
}
}
}
tileview.java :
package com.example.bharatchamakuri.snakenewww;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
/**
* TileView: a View-variant designed for handling arrays of "icons" or other
* drawables.
*
*/
class TileView extends View {
/**
* Parameters controlling the size of the tiles and their range within view.
* Width/Height are in pixels, and Drawables will be scaled to fit to these
* dimensions. X/Y Tile Counts are the number of tiles that will be drawn.
*/
protected static int mTileSize;
protected static int mXTileCount;
protected static int mYTileCount;
private static int mXOffset;
private static int mYOffset;
/**
* A hash that maps integer handles specified by the subclasser to the
* drawable that will be used for that reference
*/
private Bitmap[] mTileArray;
/**
* A two-dimensional array of integers in which the number represents the
* index of the tile that should be drawn at that locations
*/
private int[][] mTileGrid;
private final Paint mPaint = new Paint();
public TileView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.TileView);
mTileSize = a.getInt(R.styleable.TileView_tileSize, 12);
a.recycle();
}
public TileView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.TileView);
mTileSize = a.getInt(R.styleable.TileView_tileSize, 12);
a.recycle();
}
/**
* Rests the internal array of Bitmaps used for drawing tiles, and sets the
* maximum index of tiles to be inserted
*
* #param tilecount
*/
public void resetTiles(int tilecount) {
mTileArray = new Bitmap[tilecount];
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mXTileCount = (int) Math.floor(w / mTileSize);
mYTileCount = (int) Math.floor(h / mTileSize);
mXOffset = ((w - (mTileSize * mXTileCount)) / 2);
mYOffset = ((h - (mTileSize * mYTileCount)) / 2);
mTileGrid = new int[mXTileCount][mYTileCount];
clearTiles();
}
/**
* Function to set the specified Drawable as the tile for a particular
* integer key.
*
* #param key
* #param tile
*/
public void loadTile(int key, Drawable tile) {
Bitmap bitmap = Bitmap.createBitmap(mTileSize, mTileSize,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
tile.setBounds(0, 0, mTileSize, mTileSize);
tile.draw(canvas);
mTileArray[key] = bitmap;
}
/**
* Resets all tiles to 0 (empty)
*
*/
public void clearTiles() {
for (int x = 0; x < mXTileCount; x++) {
for (int y = 0; y < mYTileCount; y++) {
setTile(0, x, y);
}
}
}
/**
* Used to indicate that a particular tile (set with loadTile and referenced
* by an integer) should be drawn at the given x/y coordinates during the
* next invalidate/draw cycle.
*
* #param tileindex
* #param x
* #param y
*/
public void setTile(int tileindex, int x, int y) {
mTileGrid[x][y] = tileindex;
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int x = 0; x < mXTileCount; x += 1) {
for (int y = 0; y < mYTileCount; y += 1) {
if (mTileGrid[x][y] > 0) {
canvas.drawBitmap(mTileArray[mTileGrid[x][y]], mXOffset + x
* mTileSize, mYOffset + y * mTileSize, mPaint);
}
}
}
}
}
and the logcat :
> 11-13 00:38:43.336 29231-29231/com.example.bharatchamakuri.snakefinal
> E/AndroidRuntime﹕ FATAL EXCEPTION: main
> Process: com.example.bharatchamakuri.snakefinal, PID: 29231
> java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bharatchamakuri.snakefinal/com.example.bharatchamakuri.snakefinal.Snake}:
> android.view.InflateException: Binary XML file line #5: Error
> inflating class com.example.android.snake.SnakeView
> at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
> at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
> at android.app.ActivityThread.access$800(ActivityThread.java:151)
> at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
> at android.os.Handler.dispatchMessage(Handler.java:110)
> at android.os.Looper.loop(Looper.java:193)
> at android.app.ActivityThread.main(ActivityThread.java:5292)
> at java.lang.reflect.Method.invokeNative(Native Method)
> at java.lang.reflect.Method.invoke(Method.java:515)
> at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
> at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
> at dalvik.system.NativeStart.main(Native Method)
> Caused by: android.view.InflateException: Binary XML file line #5: Error inflating class com.example.android.snake.SnakeView
> at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:707)
> at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
> at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
> at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native
> Method)
> at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:631)
> at android.view.LayoutInflater.inflate(Native Method)
> at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
> at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
> at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:305)
> at android.app.Activity.setContentView(Activity.java:1944)
> at com.example.bharatchamakuri.snakefinal.Snake.onCreate(Snake.java:55)
> at android.app.Activity.performCreate(Activity.java:5264)
> at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
> at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
> at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
> at android.app.ActivityThread.access$800(ActivityThread.java:151)
> at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
> at android.os.Handler.dispatchMessage(Handler.java:110)
> at android.os.Looper.loop(Looper.java:193)
> at android.app.ActivityThread.main(ActivityThread.java:5292)
> at java.lang.reflect.Method.invokeNative(Native Method)
> at java.lang.reflect.Method.invoke(Method.java:515)
> at
The error says "Error inflating class com.example.android.snake.SnakeView" but your SnakeView class is "com.example.bharatchamakuri.snakefinal.SnakeView". Those are different, which is why it can't load the class.
Did you forget to change the name of the SnakeView class in your layout file perhaps?
Im using Graphview and work fine, but now i have a problem.
I would like to have a background for each series that is added to the graph, and not for all series
Is this possible?
This is currently (5 August 2014) not possible on the original GraphView library.
I needed this functionality, so I forked the library and implemented the functionality myself. You can find the updated code on the feature/series_specific_styles branch of my fork:
https://github.com/mobiRic/GraphView/tree/feature/series_specific_styles
Hopefully in future these changes will be pulled into the original library.
The actual code changes are relatively simple.
Added required background fields to GraphViewSeries.GraphViewSeriesStyle
Updated LineGraphView.drawSeries() to look for these fields instead of relying on its own internal values.
I have included full updates below, but the easiest way to view them is on the commit page:
allow different background for each series
Here is the updated GraphViewSeriesStyle class:
static public class GraphViewSeriesStyle {
public int color = 0xff0077cc;
public int thickness = 3;
private ValueDependentColor valueDependentColor;
private final Paint paintBackground;
private boolean drawBackground;
private boolean drawDataPoints;
private float dataPointsRadius = 10f;
public GraphViewSeriesStyle() {
super();
paintBackground = new Paint();
paintBackground.setColor(Color.rgb(20, 40, 60));
paintBackground.setStrokeWidth(4);
paintBackground.setAlpha(128);
}
public GraphViewSeriesStyle(int color, int thickness) {
super();
this.color = color;
this.thickness = thickness;
paintBackground = new Paint();
paintBackground.setColor(Color.rgb(20, 40, 60));
paintBackground.setStrokeWidth(4);
paintBackground.setAlpha(128);
}
public ValueDependentColor getValueDependentColor() {
return valueDependentColor;
}
/**
* the color depends on the value of the data.
* only possible in BarGraphView
* #param valueDependentColor
*/
public void setValueDependentColor(ValueDependentColor valueDependentColor) {
this.valueDependentColor = valueDependentColor;
}
public boolean getDrawBackground() {
return drawBackground;
}
public void setDrawBackground(boolean drawBackground) {
this.drawBackground = drawBackground;
}
public Paint getPaintBackground() {
return paintBackground;
}
public int getBackgroundColor() {
return paintBackground.getColor();
}
/**
* sets the background colour for the series. This is not the background
* colour of the whole graph.
*/
public void setBackgroundColor(int color) {
paintBackground.setColor(color);
}
public float getDataPointsRadius() {
return dataPointsRadius;
}
public boolean getDrawDataPoints() {
return drawDataPoints;
}
/**
* sets the radius of the circles at the data points.
* #see #setDrawDataPoints(boolean)
* #param dataPointsRadius
*/
public void setDataPointsRadius(float dataPointsRadius) {
this.dataPointsRadius = dataPointsRadius;
}
/**
* You can set the flag to let the GraphView draw circles at the data points
* #see #setDataPointsRadius(float)
* #param drawDataPoints
*/
public void setDrawDataPoints(boolean drawDataPoints) {
this.drawDataPoints = drawDataPoints;
}
}
Here is the updated LineGraphView.drawSeries() method:
public void drawSeries(Canvas canvas, GraphViewDataInterface[] values, float graphwidth, float graphheight, float border, double minX, double minY, double diffX, double diffY, float horstart, GraphViewSeriesStyle style) {
// draw background
double lastEndY = 0;
double lastEndX = 0;
// draw data
paint.setStrokeWidth(style.thickness);
paint.setColor(style.color);
Path bgPath = null;
if ((drawBackground) || (style.getDrawBackground())) {
bgPath = new Path();
}
lastEndY = 0;
lastEndX = 0;
float firstX = 0;
for (int i = 0; i < values.length; i++) {
double valY = values[i].getY() - minY;
double ratY = valY / diffY;
double y = graphheight * ratY;
double valX = values[i].getX() - minX;
double ratX = valX / diffX;
double x = graphwidth * ratX;
if (i > 0) {
float startX = (float) lastEndX + (horstart + 1);
float startY = (float) (border - lastEndY) + graphheight;
float endX = (float) x + (horstart + 1);
float endY = (float) (border - y) + graphheight;
// draw data point
if (drawDataPoints) {
//fix: last value was not drawn. Draw here now the end values
canvas.drawCircle(endX, endY, dataPointsRadius, paint);
} else if (style.getDrawDataPoints()) {
canvas.drawCircle(endX, endY, style.getDataPointsRadius(), paint);
}
canvas.drawLine(startX, startY, endX, endY, paint);
if (bgPath != null) {
if (i==1) {
firstX = startX;
bgPath.moveTo(startX, startY);
}
bgPath.lineTo(endX, endY);
}
} else if ((drawDataPoints) || (style.getDrawDataPoints())) {
//fix: last value not drawn as datapoint. Draw first point here, and then on every step the end values (above)
float first_X = (float) x + (horstart + 1);
float first_Y = (float) (border - y) + graphheight;
if (drawDataPoints) {
canvas.drawCircle(first_X, first_Y, dataPointsRadius, paint);
} else if (style.getDrawDataPoints()) {
canvas.drawCircle(first_X, first_Y, style.getDataPointsRadius(), paint);
}
}
lastEndY = y;
lastEndX = x;
}
if (bgPath != null) {
// end / close path
bgPath.lineTo((float) lastEndX, graphheight + border);
bgPath.lineTo(firstX, graphheight + border);
bgPath.close();
if (style.getDrawBackground()) {
canvas.drawPath(bgPath, style.getPaintBackground());
} else {
canvas.drawPath(bgPath, paintBackground);
}
}
}
For interest, that branch also allows data points to be configured for each series - code changes visible here:
allow datapoint styling for each series
I have to get distance from different markers on the map to the current location of the device and the pick up the shortest one. I have the lat and long for the markers and the current location lat and long can be fetched dynamically.
Suppose I have 5 markers on the map, Bangalore (Lat : 12.971599, Long : 77.594563), Delhi (Lat : 28.635308, Long : 77.224960), Mumbai (Lat : 19.075984, Long : 72.877656), Chennai (Lat : 13.052414, Long : 80.250825), Kolkata (Lat : 22.572646, Long : 88.363895).
Now suppose the user is standing somewhere near Hyderabad (Lat : 17.385044, Long : 78.486671). When the user clicks the button, the app should calculate distance from each marker and pick up and return the shortest one, that will be Bangalore here.
There is a way possible to do it with help of local databases. Can anyone help on that please.?
Can anyone suggest me a nice way to do this, or come up with a good code if you please can. Thanx in advance.
from your comment I see that you expect a maximum of 70-80 locations.
This is not much.
You can simply do a brute force search over all markers and take the minimum.
Iterate over all markers, and search min distance:
List<Marker> markers = createMarkers(); // returns an ArrayList<Markers> from your data source
int minIndex = -1;
double minDist = 1E38; // initialize with a huge value that will be overwritten
int size = markers.size();
for (int i = 0; i < size; i++) {
Marker marker = markers.get(i);
double curDistance = calcDistance(curLatitude, curLongitude, marker.latitude, marker.longitude);
if (curDistance < minDist) {
minDist = curDistance; // update neares
minIndex = i; // store index of nearest marker in minIndex
}
}
if (minIndex >= 0) {
// now nearest maker found:
Marker nearestMarker = markers.get(minIndex);
// TODO do something with nearesr marker
} else {
// list of markers was empty
}
For calcDistance, use the distance calculation method provided by android. (e.g Location.distanceTo() )
For 70-80 markers there is no need to make it faster and much more complex.
If you have some thousands points then it is worth to invest in a faster solution (using a spatial index, and an own distance calculation which avoids the sqrt calc).
Just print out the current time in milli seconds at the begin and at the end of the nearest maker search, and you will see, that it is fast enough.
If you want to find the shortest one not list the closest and you want the process to scale to a large amount of locations, you can do some filtering before you calculate distances and you can simplify the formula to speed it up as you don't care about actual distances (i.e. remove the multiplication by the radius of the earth).
Filtering algorithm, looping through each location :
Calculate the difference in lat and long.
If both differences are larger then a previously processed pair, discard it.
Calculate distance, keep smallest.
You can further help the algorithm by feeding it with what might be close locations first. For example if you know one of the points is in the same country or state.
Here is some Python code to do that, use it as pseudocode for your solution :
locations = {
'Bangalore' : (12.971599, 77.594563),
'Delhi' : (28.635308, 77.224960),
'Mumbai' : (19.075984, 72.877656),
'Chennai' : (13.052414, 80.250825),
'Kolkata' : (22.572646, 88.363895)
}
from math import sin, cos, atan2, sqrt
EARTH_RADIUS = 6373 # km
def distance(a, b): # pass tuples
(lat1, lon1) = a
(lat2, lon2) = b
dlon = lon2 - lon1
dlat = lat2 - lat1
a = (sin(dlat/2))**2 + cos(lat1) * cos(lat2) * (sin(dlon/2))**2
c = 2 * atan2( sqrt(a), sqrt(1-a) )
return EARTH_RADIUS * c
current = (17.385044, 78.486671) # current lat & lng
closest = None
closest_name = None
for name, cordinates in locations.iteritems():
d = distance(current, cordinates)
if closest is None or d < closest:
closest = d
closest_name = name
print "~%dkm (%s)" % (distance(current, cordinates), name)
print "\nClosest location is %s, %d km away." % (closest_name, closest)
Output :
~5700km (Kolkata)
~13219km (Chennai)
~12159km (Bangalore)
~7928km (Delhi)
~10921km (Mumbai)
Closest location is Kolkata, 5700 km away.
How about looping over all markers and checking the distance using Location.distanceBetween? There is no magic involved ;)
List<Marker> markers;
LatLng currentPosition;
float minDistance = Float.MAX_VALUE;
Marker closest = null;
float[] currentDistance = new float[1];
for (Marker marker : markers) {
LatLng markerPosition = marker.getPosition();
Location.distanceBetween(currentPosition.latitude, currentPosition.longitude, markerPosition.latitude, markerPosition.longitude, currentDistance);
if (minDistance > currentDistance[0]) {
minDistance = currentDistance[0];
closest = marker;
}
}
Although there has already been posted some answer, I thought I would present my implementation in java. This has been used with 4000+ markers wrapped in an AsyncTask and has been working with no problems.
First, the logic to calculate distance (assuming you only have the markers and not Location objects, as those gives the possibility to do loc1.distanceTo(loc2)):
private float distBetween(LatLng pos1, LatLng pos2) {
return distBetween(pos1.latitude, pos1.longitude, pos2.latitude,
pos2.longitude);
}
/** distance in meters **/
private float distBetween(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
int meterConversion = 1609;
return (float) (dist * meterConversion);
}
Next, the code for selecting the nearest marker:
private Marker getNearestMarker(List<Marker> markers,
LatLng origin) {
Marker nearestMarker = null;
double lowestDistance = Double.MAX_VALUE;
if (markers != null) {
for (Marker marker : markers) {
double dist = distBetween(origin, marker.getPosition());
if (dist < lowestDistance) {
nearestMarker = marker;
lowestDistance = dist;
}
}
}
return nearestMarker;
}
Perhaps not relevant for your use case but I use the algorithm to select the nearest markers based on a predefined distance. This way I weed out a lot of unnecessary markers:
private List<Marker> getSurroundingMarkers(List<Marker> markers,
LatLng origin, int maxDistanceMeters) {
List<Marker> surroundingMarkers = null;
if (markers != null) {
surroundingMarkers = new ArrayList<Marker>();
for (Marker marker : markers) {
double dist = distBetween(origin, marker.getPosition());
if (dist < maxDistanceMeters) {
surroundingMarkers.add(marker);
}
}
}
return surroundingMarkers;
}
Hope this helps you
This code could help you getting the distances: https://github.com/BeyondAR/beyondar/blob/master/android/BeyondAR_Framework/src/com/beyondar/android/util/math/Distance.java
Here is my implementation of a so called KDTree, consisting of 3 classes: KDTree, KDTNode and KDTResult.
What you finally need is to create the KDTree using KDTree.createTree(), which returns the rootNode of the tree and gets all your fixed points passed in.
Then use KDTree.findNearestWp() to find the nearest Waypoint to the given location.
KDTree:
public class KDTree {
private Comparator<LatLng> latComparator = new LatLonComparator(true);
private Comparator<LatLng> lonComparator = new LatLonComparator(false);;
/**
* Create a KDTree from a list of Destinations. Returns the root-node of the
* tree.
*/
public KDTNode createTree(List<LatLng> recList) {
return createTreeRecursive(0, recList);
}
/**
* Traverse the tree and find the nearest WP.
*
* #param root
* #param wp
* #return
*/
static public LatLng findNearestWp(KDTNode root, LatLng wp) {
KDTResult result = new KDTResult();
findNearestWpRecursive(root, wp, result);
return result.nearestDest;
}
private static void findNearestWpRecursive(KDTNode node, LatLng wp,
KDTResult result) {
double lat = wp.latitude;
double lon = wp.longitude;
/* If a leaf node, calculate distance and return. */
if (node.isLeaf) {
LatLng dest = node.wp;
double latDiff = dest.latitude - lat;
double lonDiff = dest.longitude - lon;
double squareDist = latDiff * latDiff + lonDiff * lonDiff;
// Replace a previously found nearestDest only if the new one is
// nearer.
if (result.nearestDest == null
|| result.squareDistance > squareDist) {
result.nearestDest = dest;
result.squareDistance = squareDist;
}
return;
}
boolean devidedByLat = node.depth % 2 == 0;
boolean goLeft;
/* Check whether left or right is more promising. */
if (devidedByLat) {
goLeft = lat < node.splitValue;
} else {
goLeft = lon < node.splitValue;
}
KDTNode child = goLeft ? node.left : node.right;
findNearestWpRecursive(child, wp, result);
/*
* Check whether result needs to be checked also against the less
* promising side.
*/
if (result.squareDistance > node.minSquareDistance) {
KDTNode otherChild = goLeft ? node.right : node.left;
findNearestWpRecursive(otherChild, wp, result);
}
}
private KDTNode createTreeRecursive(int depth, List<LatLng> recList) {
KDTNode node = new KDTNode();
node.depth = depth;
if (recList.size() == 1) {
// Leafnode found
node.isLeaf = true;
node.wp = recList.get(0);
return node;
}
boolean divideByLat = node.depth % 2 == 0;
sortRecListByDimension(recList, divideByLat);
List<LatLng> leftList = getHalfOf(recList, true);
List<LatLng> rightList = getHalfOf(recList, false);
// Get split point and distance to last left and first right point.
LatLng lastLeft = leftList.get(leftList.size() - 1);
LatLng firstRight = rightList.get(0);
double minDistanceToSplitValue;
double splitValue;
if (divideByLat) {
minDistanceToSplitValue = (firstRight.latitude - lastLeft.latitude) / 2;
splitValue = lastLeft.latitude + Math.abs(minDistanceToSplitValue);
} else {
minDistanceToSplitValue = (firstRight.longitude - lastLeft.longitude) / 2;
splitValue = lastLeft.longitude + Math.abs(minDistanceToSplitValue);
}
node.splitValue = splitValue;
node.minSquareDistance = minDistanceToSplitValue
* minDistanceToSplitValue;
/** Call next level */
depth++;
node.left = createTreeRecursive(depth, leftList);
node.right = createTreeRecursive(depth, rightList);
return node;
}
/**
* Return a sublist representing the left or right half of a List. Size of
* recList must be at least 2 !
*
* IMPORTANT !!!!! Note: The original list must not be modified after
* extracting this sublist, as the returned subList is still backed by the
* original list.
*/
List<LatLng> getHalfOf(List<LatLng> recList, boolean leftHalf) {
int mid = recList.size() / 2;
if (leftHalf) {
return recList.subList(0, mid);
} else {
return recList.subList(mid, recList.size());
}
}
private void sortRecListByDimension(List<LatLng> recList, boolean sortByLat) {
Comparator<LatLng> comparator = sortByLat ? latComparator
: lonComparator;
Collections.sort(recList, comparator);
}
class LatLonComparator implements Comparator<LatLng> {
private boolean byLat;
public LatLonComparator(boolean sortByLat) {
this.byLat = sortByLat;
}
#Override
public int compare(LatLng lhs, LatLng rhs) {
double diff;
if (byLat) {
diff = lhs.latitude - rhs.latitude;
} else {
diff = lhs.longitude - rhs.longitude;
}
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
return 0;
}
}
}
}
KDTNode:
/** Node of the KDTree */
public class KDTNode {
KDTNode left;
KDTNode right;
boolean isLeaf;
/** latitude or longitude of the nodes division line. */
double splitValue;
/** Distance between division line and first point. */
double minSquareDistance;
/**
* Depth of the node in the tree. An even depth devides the tree in the
* latitude-axis, an odd depth devides the tree in the longitude-axis.
*/
int depth;
/** The Waypoint in case the node is a leaf node. */
LatLng wp;
}
KDTResult:
/** Holds the result of a tree traversal. */
public class KDTResult {
LatLng nearestDest;
// I use the square of the distance to avoid square-root operations.
double squareDistance;
}
Please note, that I am using a simplified distance calculation, which works in my case, as I am only interested in very nearby waypoints. For points further apart, this may result in getting not exactly the nearest point. The absolute difference of two longitudes expressed as east-west distance in meters, depends on the latitude, where this difference is measured. This is not taken into account in my algorithm and I am not sure about the relevance of this effect in your case.
An efficient way to search for the smallest distance between a single point (that may change frequently), and a large set of points, in two dimensions is to use a QuadTree. There is a cost to initially build the QuadTree (i.e., add your marker locations to the data structure), so you only want to do this once (or as infrequently as possible). But, once constructed, searches for the closest point will typically be faster than a brute force comparison against all points in the large set.
BBN's OpenMap project has an open-source QuadTree Java implementation that I believe should work on Android that has a get(float lat, float lon) method to return the closest point.
Google's android-maps-utils library also has an open-source implementation of a QuadTree intended to run on Android, but as it is currently written it only supports a search(Bounds bounds) operation to return a set of points in a given bounding box, and not the point closest to an input point. But, it could be modified to perform the closest point search.
If you have a relatively small number of points (70-80 may be sufficiently small), then in real-world performance a brute-force comparison may execute in a similar amount of time to the QuadTree solution. But, it also depends on how frequently you intended on re-calculating the closest point - if frequent, a QuadTree may be a better choice.
I thought it should not be too difficult to extend my KDTree (see my other answer) also to a 3 dimensional version, and here is the result.
But as I do not use this version myself so far, take it with care. I added a unit-test, which shows that it works at least for your example.
/** 3 dimensional implementation of a KDTree for LatLng coordinates. */
public class KDTree {
private XYZComparator xComparator = new XYZComparator(0);
private XYZComparator yComparator = new XYZComparator(1);
private XYZComparator zComparator = new XYZComparator(2);
private XYZComparator[] comparators = { xComparator, yComparator,
zComparator };
/**
* Create a KDTree from a list of lat/lon coordinates. Returns the root-node
* of the tree.
*/
public KDTNode createTree(List<LatLng> recList) {
List<XYZ> xyzList = convertTo3Dimensions(recList);
return createTreeRecursive(0, xyzList);
}
/**
* Traverse the tree and find the point nearest to wp.
*/
static public LatLng findNearestWp(KDTNode root, LatLng wp) {
KDTResult result = new KDTResult();
XYZ xyz = convertTo3Dimensions(wp);
findNearestWpRecursive(root, xyz, result);
return result.nearestWp;
}
/** Convert lat/lon coordinates into a 3 dimensional xyz system. */
private static XYZ convertTo3Dimensions(LatLng wp) {
// See e.g.
// http://stackoverflow.com/questions/8981943/lat-long-to-x-y-z-position-in-js-not-working
double cosLat = Math.cos(wp.latitude * Math.PI / 180.0);
double sinLat = Math.sin(wp.latitude * Math.PI / 180.0);
double cosLon = Math.cos(wp.longitude * Math.PI / 180.0);
double sinLon = Math.sin(wp.longitude * Math.PI / 180.0);
double rad = 6378137.0;
double f = 1.0 / 298.257224;
double C = 1.0 / Math.sqrt(cosLat * cosLat + (1 - f) * (1 - f) * sinLat
* sinLat);
double S = (1.0 - f) * (1.0 - f) * C;
XYZ result = new XYZ();
result.x = (rad * C) * cosLat * cosLon;
result.y = (rad * C) * cosLat * sinLon;
result.z = (rad * S) * sinLat;
result.wp = wp;
return result;
}
private List<XYZ> convertTo3Dimensions(List<LatLng> recList) {
List<XYZ> result = new ArrayList<KDTree.XYZ>();
for (LatLng latLng : recList) {
XYZ xyz = convertTo3Dimensions(latLng);
result.add(xyz);
}
return result;
}
private static void findNearestWpRecursive(KDTNode node, XYZ wp,
KDTResult result) {
/* If a leaf node, calculate distance and return. */
if (node.isLeaf) {
double xDiff = node.xyz.x - wp.x;
double yDiff = node.xyz.y - wp.y;
double zDiff = node.xyz.z - wp.z;
double squareDist = xDiff * xDiff + yDiff * yDiff + zDiff * zDiff;
// Replace a previously found nearestDest only if the new one is
// nearer.
if (result.nearestWp == null || result.squareDistance > squareDist) {
result.nearestWp = node.xyz.wp;
result.squareDistance = squareDist;
}
return;
}
int devidedByDimension = node.depth % 3;
boolean goLeft;
/* Check whether left or right is more promising. */
if (devidedByDimension == 0) {
goLeft = wp.x < node.splitValue;
} else if (devidedByDimension == 1) {
goLeft = wp.y < node.splitValue;
} else {
goLeft = wp.z < node.splitValue;
}
KDTNode child = goLeft ? node.left : node.right;
findNearestWpRecursive(child, wp, result);
/*
* Check whether result needs to be checked also against the less
* promising side.
*/
if (result.squareDistance > node.minSquareDistance) {
KDTNode otherChild = goLeft ? node.right : node.left;
findNearestWpRecursive(otherChild, wp, result);
}
}
private KDTNode createTreeRecursive(int depth, List<XYZ> recList) {
KDTNode node = new KDTNode();
node.depth = depth;
if (recList.size() == 1) {
// Leafnode found
node.isLeaf = true;
node.xyz = recList.get(0);
return node;
}
int dimension = node.depth % 3;
sortWayPointListByDimension(recList, dimension);
List<XYZ> leftList = getHalfOf(recList, true);
List<XYZ> rightList = getHalfOf(recList, false);
// Get split point and distance to last left and first right point.
XYZ lastLeft = leftList.get(leftList.size() - 1);
XYZ firstRight = rightList.get(0);
double minDistanceToSplitValue;
double splitValue;
if (dimension == 0) {
minDistanceToSplitValue = (firstRight.x - lastLeft.x) / 2;
splitValue = lastLeft.x + Math.abs(minDistanceToSplitValue);
} else if (dimension == 1) {
minDistanceToSplitValue = (firstRight.y - lastLeft.y) / 2;
splitValue = lastLeft.y + Math.abs(minDistanceToSplitValue);
} else {
minDistanceToSplitValue = (firstRight.z - lastLeft.z) / 2;
splitValue = lastLeft.z + Math.abs(minDistanceToSplitValue);
}
node.splitValue = splitValue;
node.minSquareDistance = minDistanceToSplitValue
* minDistanceToSplitValue;
/** Call next level */
depth++;
node.left = createTreeRecursive(depth, leftList);
node.right = createTreeRecursive(depth, rightList);
return node;
}
/**
* Return a sublist representing the left or right half of a List. Size of
* recList must be at least 2 !
*
* IMPORTANT !!!!! Note: The original list must not be modified after
* extracting this sublist, as the returned subList is still backed by the
* original list.
*/
List<XYZ> getHalfOf(List<XYZ> xyzList, boolean leftHalf) {
int mid = xyzList.size() / 2;
if (leftHalf) {
return xyzList.subList(0, mid);
} else {
return xyzList.subList(mid, xyzList.size());
}
}
private void sortWayPointListByDimension(List<XYZ> wayPointList, int sortBy) {
XYZComparator comparator = comparators[sortBy];
Collections.sort(wayPointList, comparator);
}
class XYZComparator implements Comparator<XYZ> {
private int sortBy;
public XYZComparator(int sortBy) {
this.sortBy = sortBy;
}
#Override
public int compare(XYZ lhs, XYZ rhs) {
double diff;
if (sortBy == 0) {
diff = lhs.x - rhs.x;
} else if (sortBy == 1) {
diff = lhs.y - rhs.y;
} else {
diff = lhs.z - rhs.z;
}
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
return 0;
}
}
}
/** 3 Dimensional coordinates of a waypoint. */
static class XYZ {
double x;
double y;
double z;
// Keep also the original waypoint
LatLng wp;
}
/** Node of the KDTree */
public static class KDTNode {
KDTNode left;
KDTNode right;
boolean isLeaf;
/** latitude or longitude of the nodes division line. */
double splitValue;
/** Distance between division line and first point. */
double minSquareDistance;
/**
* Depth of the node in the tree. Depth 0,3,6.. devides the tree in the
* x-axis, depth 1,4,7,.. devides the tree in the y-axis and depth
* 2,5,8... devides the tree in the z axis.
*/
int depth;
/** The Waypoint in case the node is a leaf node. */
XYZ xyz;
}
/** Holds the result of a tree traversal. */
static class KDTResult {
LatLng nearestWp;
// We use the square of the distance to avoid square-root operations.
double squareDistance;
}
}
And here is the unit test:
public void testSOExample() {
KDTree tree = new KDTree();
LatLng Bangalore = new LatLng(12.971599, 77.594563);
LatLng Delhi = new LatLng(28.635308, 77.224960);
LatLng Mumbai = new LatLng(19.075984, 72.877656);
LatLng Chennai = new LatLng(13.052414, 80.250825);
LatLng Kolkata = new LatLng(22.572646, 88.363895);
List<LatLng> cities = Arrays.asList(new LatLng[] { Bangalore, Delhi,
Mumbai, Chennai, Kolkata });
KDTree.KDTNode root = tree.createTree(cities);
LatLng Hyderabad = new LatLng(17.385044, 78.486671);
LatLng nearestWp = tree.findNearestWp(root, Hyderabad);
assertEquals(nearestWp, Bangalore);
}
Here, I got a way to do that Using databases.
This is a calculate distance function:
public void calculateDistance() {
if (latitude != 0.0 && longitude != 0.0) {
for(int i=0;i<97;i++) {
Location myTargetLocation=new Location("");
myTargetLocation.setLatitude(targetLatitude[i]);
myTargetLocation.setLongitude(targetLongitude[i]);
distance[i]=myCurrentLocation.distanceTo(myTargetLocation);
distance[i]=distance[i]/1000;
mdb.insertDetails(name[i],targetLatitude[i], targetLongitude[i], distance[i]);
}
Cursor c1= mdb.getallDetail();
while (c1.moveToNext()) {
String station_name=c1.getString(1);
double latitude=c1.getDouble(2);
double longitude=c1.getDouble(3);
double dis=c1.getDouble(4);
//Toast.makeText(getApplicationContext(),station_name+" & "+latitude+" & "+longitude+" & "+dis,1).show();
}
Arrays.sort(distance);
double nearest_distance=distance[0];
Cursor c2=mdb.getNearestStationName();
{
while (c2.moveToNext()) {
double min_dis=c2.getDouble(4);
if(min_dis==nearest_distance)
{
String nearest_stationName=c2.getString(1);
if(btn_clicked.equals("source"))
{
source.setText(nearest_stationName);
break;
}
else if(btn_clicked.equals("dest"))
{
destination.setText(nearest_stationName);
break;
}
else
{
}
}
}
}
}
else
{
Toast.makeText(this, "GPS is Not Working Properly,, please check Gps and Wait for few second", 1).show();
}
}
All we have to do is Create an array named targetLatitude[i] and targetLongitude[i] containing Lats and Longs of all the places you want to calculate distance from.
Then create a database as shown below:
public class MyDataBase {
SQLiteDatabase sdb;
MyHelper mh;
MyDataBase(Context con)
{
mh = new MyHelper(con, "Metro",null, 1);
}
public void open() {
try
{
sdb=mh.getWritableDatabase();
}
catch(Exception e)
{
}
}
public void insertDetails(String name,double latitude,double longitude,double distance) {
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("latitude", latitude);
cv.put("longitude",longitude);
cv.put("distance", distance);
sdb.insert("stations", null, cv);
}
public void insertStops(String stop,double latitude,double logitude)
{
ContentValues cv=new ContentValues();
cv.put("stop", stop);
cv.put("latitude", latitude);
cv.put("logitude", logitude);
sdb.insert("stops", null, cv);
}
public Cursor getallDetail()
{
Cursor c=sdb.query("stations",null,null,null,null,null,null);
return c;
}
public Cursor getNearestStationName() {
Cursor c=sdb.query("stations",null,null,null,null,null,null);
return c;
}
public Cursor getStops(String stop)
{
Cursor c;
c=sdb.query("stops",null,"stop=?",new String[]{stop},null, null, null);
return c;
}
class MyHelper extends SQLiteOpenHelper
{
public MyHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("Create table stations(_id integer primary key,name text," +
" latitude double, longitude double, distance double );");
db.execSQL("Create table stops(_id integer primary key,stop text," +
"latitude double,logitude double);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public void deleteDetail() {
sdb.delete("stations",null,null);
sdb.delete("stops",null,null);
}
public void close() {
sdb.close();
}
}
Then execute the CalculateDistance function wherever you want and you can get the nearest station name.
I have drawn a Cubic Curve on canvas using
myPath.cubicTo(10, 10, w, h/2, 10, h-10);
I have four ImageView on that screen and I want to move that ImageViews on the drawn curve when I drag that image with touch.
I have referred the links :
Move Image on Curve Path
Move object on Curve
Move imageview on curve
What I get is, Animation to move the Image on Curve with the duration defined by t.
But I want to move that ImageView on touch in direction of that curve area only.
Following is my Screen :
So, I want all the (x,y) co-ordinates of the curve to move ImageView on that curve only.
Else I want an equation to draw a curve so that I can interpolate x value for the touched y value.
I have goggled a lot but didn't succeed.
Any advice or guidance will help me a lot.
Approach
I would suggest a different approach than using bezier as you would need to reproduce the math for it in order to get the positions.
By using simple trigonometry you can achieve the same visual result but in addition have full control of the positions.
Trigonometry
For example:
THIS ONLINE DEMO produces this result (simplified version for sake of demo):
Define an array with the circles and angle positions instead of y and x positions. You can filter angles later if they (e.g. only show angles between -90 and 90 degrees).
Using angles will make sure they stay ordered when moved.
var balls = [-90, -45, 0, 45]; // example "positions"
To replace the Bezier curve you can do this instead:
/// some setup variables
var xCenter = -80, /// X center of circle
yCenter = canvas.height * 0.5, /// Y center of circle
radius = 220, /// radius of circle
x, y; /// to calculate line position
/// draw half circle
ctx.arc(xCenter, yCenter, radius, 0, 2 * Math.PI);
ctx.stroke();
Now we can use an Y value from mouse move/touch etc. to move around the circles:
/// for demo, mousemove - adopt as needed for touch
canvas.onmousemove = function(e) {
/// get Y position which is used as delta to angle
var rect = demo.getBoundingClientRect();
dlt = e.clientY - rect.top;
/// render the circles in new positions
render();
}
The rendering iterates through the balls array and render them in their angle + delta:
for(var i = 0, angle; i < balls.length; i++) {
angle = balls[i];
pos = getPosfromAngle(angle);
/// draw circles etc. here
}
The magic function is this:
function getPosfromAngle(a) {
/// get angle from circle and add delta
var angle = Math.atan2(delta - yCenter, radius) + a * Math.PI / 180;
return [xCenter + radius * Math.cos(angle),
yCenter + radius * Math.sin(angle)];
}
radius is used as a pseudo position. You can replace this with an actual X position but is frankly not needed.
In this demo, to keep it simple, I have only attached mouse move. Move the mouse over the canvas to see the effect.
As this is demo code it's not structured optimal (separate render of background and the circles etc.).
Feel free to adopt and modify to suit your needs.
This code I have used to achieve this functionality and it works perfect as per your requirement...
public class YourActivity extends Activity {
private class ButtonInfo {
public Button btnObj;
public PointF OrigPos;
public double origAngle;
public double currentAngle;
public double minAngle;
public double maxAngle;
boolean isOnClick = false;
}
private int height;
private double radius;
private PointF centerPoint;
private final int NUM_BUTTONS = 4;
private final int FIRST_INDEX = 0;
private final int SECOND_INDEX = 1;
private final int THIRD_INDEX = 2;
private final int FORTH_INDEX = 3;
private final String FIRST_TAG = "FiRST_BUTTON";
private final String SECOND_TAG = "SECOND_BUTTON";
private final String THIRD_TAG = "THIRD_BUTTON";
private final String FORTH_TAG = "FORTH_BUTTON";
private boolean animInProgress = false;
private int currentButton = -1;
private ButtonInfo[] buttonInfoArray = new ButtonInfo[NUM_BUTTONS];
private int curveImageResource = -1;
private RelativeLayout parentContainer;
private int slop;
private boolean initFlag = false;
private int touchDownY = -1;
private int touchDownX = -1;
private int animCount;
private Context context;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.fadeinleft, R.anim.fadeoutleft);
// hide action bar in view
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
Thread.setDefaultUncaughtExceptionHandler(
new MyDefaultExceptionHandler(this, getLocalClassName()));
setContentView(R.layout.your_layout);
context = this;
final ImageView curve_image = (ImageView) findViewById(R.id.imageView1);
parentContainer = (RelativeLayout) findViewById(R.id.llView);
// Set buttons on their location
for (int i = 0; i < NUM_BUTTONS; i++) {
buttonInfoArray[i] = new ButtonInfo();
}
Button img1 = (Button) findViewById(R.id.button_option1);
Button img2 = (Button) findViewById(R.id.button_option2);
Button img3 = (Button) findViewById(R.id.button_option3);
Button img4 = (Button) findViewById(R.id.button_option4);
//1st button
buttonInfoArray[FIRST_INDEX].btnObj = (Button) this
.findViewById(R.id.setting_button_option);
buttonInfoArray[FIRST_INDEX].btnObj.setTag(FIRST_TAG);
// 2nd button
buttonInfoArray[SECOND_INDEX].btnObj = (Button) this
.findViewById(R.id.scanning_button_option);
buttonInfoArray[SECOND_INDEX].btnObj.setTag(SECOND_TAG);
// 3rd button
buttonInfoArray[THIRD_INDEX].btnObj = (Button) this
.findViewById(R.id.manual_button_option);
buttonInfoArray[THIRD_INDEX].btnObj.setTag(THIRD_TAG);
// 4th button
buttonInfoArray[FORTH_INDEX].btnObj = (Button) this
.findViewById(R.id.logout_button_option);
buttonInfoArray[FORTH_INDEX].btnObj.setTag(FORTH_TAG);
for (ButtonInfo currentButtonInfo : buttonInfoArray) {
currentButtonInfo.btnObj.setClickable(false);
}
for (ButtonInfo currentButtonInfo : buttonInfoArray) {
currentButtonInfo.btnObj.bringToFront();
}
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
ViewTreeObserver vtoLayout = parentContainer.getViewTreeObserver();
vtoLayout.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (initFlag == true)
return;
centerPoint = new PointF(0, (parentContainer.getHeight()) / 2);
curve_image.setImageResource(curveImageResource);
ViewTreeObserver vtoCurveImage = curve_image
.getViewTreeObserver();
vtoCurveImage
.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (initFlag == true)
return;
ViewConfiguration vc = ViewConfiguration.get(parentContainer
.getContext());
slop = vc.getScaledTouchSlop();
parentContainer.setOnTouchListener(tlobj);
height = curve_image.getMeasuredHeight();
curve_image.getMeasuredWidth();
radius = (height / 2);
double angleDiff = Math.PI / (NUM_BUTTONS + 1);
double initialAngle = (Math.PI / 2 - angleDiff);
for (ButtonInfo currentButtonInfo : buttonInfoArray) {
currentButtonInfo.origAngle = initialAngle;
initialAngle -= angleDiff;
}
double tempCurrentAngle;
double maxAngle = (-1 * Math.PI / 2);
tempCurrentAngle = maxAngle;
for (int i = NUM_BUTTONS - 1; i >= 0; i--) {
buttonInfoArray[i].maxAngle = tempCurrentAngle;
int buttonHeight = buttonInfoArray[i].btnObj
.getHeight();
if (buttonHeight < 30) {
buttonHeight = 80;
}
tempCurrentAngle = findNextMaxAngle(
tempCurrentAngle,
(buttonHeight + 5));
}
double minAngle = (Math.PI / 2);
tempCurrentAngle = minAngle;
for (int i = 0; i < NUM_BUTTONS; i++) {
buttonInfoArray[i].minAngle = tempCurrentAngle;
int buttonHeight = buttonInfoArray[i].btnObj
.getHeight();
if (buttonHeight < 30) {
buttonHeight = 80;
}
tempCurrentAngle = findNextMinAngle(
tempCurrentAngle, (buttonHeight + 5));
}
for (ButtonInfo currentButtonInfo : buttonInfoArray) {
PointF newPos = getPointByAngle(currentButtonInfo.origAngle);
currentButtonInfo.OrigPos = newPos;
currentButtonInfo.currentAngle = currentButtonInfo.origAngle;
setTranslationX(
currentButtonInfo.btnObj,
(int) currentButtonInfo.OrigPos.x - 50);
setTranslationY(
currentButtonInfo.btnObj,
(int) currentButtonInfo.OrigPos.y - 50);
currentButtonInfo.btnObj.requestLayout();
}
initFlag = true;
}
});
}
});
}
/**
* Find next max angle
* #param inputAngle
* #param yDist
* #return
*/
private double findNextMaxAngle(double inputAngle, int yDist) {
float initYPos = (float) (centerPoint.y - (Math.sin(inputAngle) * radius));
float finalYPos = initYPos - yDist;
float finalXPos = getXPos(finalYPos);
double newAngle = getNewAngle(new PointF(finalXPos, finalYPos));
return newAngle;
}
/**
* Find next min angle
* #param inputAngle
* #param yDist
* #return
*/
private double findNextMinAngle(double inputAngle, int yDist) {
float initYPos = (int) (centerPoint.y - (Math.sin(inputAngle) * radius));
float finalYPos = initYPos + yDist;
float finalXPos = getXPos(finalYPos);
double newAngle = getNewAngle(new PointF(finalXPos, finalYPos));
return newAngle;
}
/**
* Apply reset transformation when user release touch
* #param buttonInfoObj
*/
public void applyResetAnimation(final ButtonInfo buttonInfoObj) {
ValueAnimator animator = ValueAnimator.ofFloat(0, 1); // values from 0
// to 1
animator.setDuration(1000); // 5 seconds duration from 0 to 1
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = ((Float) (animation.getAnimatedValue()))
.floatValue();
// Set translation of your view here. Position can be calculated
// out of value. This code should move the view in a half
// circle.
double effectiveAngle = buttonInfoObj.origAngle
+ ((buttonInfoObj.currentAngle - buttonInfoObj.origAngle) * (1.0 - value));
PointF newPos = getPointByAngle(effectiveAngle);
setTranslationX(buttonInfoObj.btnObj, newPos.x - 50);
setTranslationY(buttonInfoObj.btnObj, newPos.y - 50);
}
});
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
animCount++;
if (animCount == NUM_BUTTONS) {
animCount = 0;
currentButton = -1;
animInProgress = false;
for (ButtonInfo currentButtonInfo : buttonInfoArray) {
setTranslationX(currentButtonInfo.btnObj,
currentButtonInfo.OrigPos.x - 50);
setTranslationY(currentButtonInfo.btnObj,
currentButtonInfo.OrigPos.y - 50);
currentButtonInfo.isOnClick = false;
currentButtonInfo.currentAngle = currentButtonInfo.origAngle;
currentButtonInfo.btnObj.setPressed(false);
currentButtonInfo.btnObj.requestLayout();
}
}
}
});
animator.start();
}
/**
* On Touch start animation
*/
private OnTouchListener tlobj = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent motionEvent) {
switch (MotionEventCompat.getActionMasked(motionEvent)) {
case MotionEvent.ACTION_MOVE:
if (currentButton < 0) {
return false;
}
if (animInProgress == true) {
return true;
}
float delta_y = motionEvent.getRawY() - touchDownY;
float delta_x = motionEvent.getRawX() - touchDownX;
updateButtonPos(new PointF((int) delta_x, (int) delta_y));
if (Math.abs(delta_x) > slop || Math.abs(delta_y) > slop) {
buttonInfoArray[currentButton].isOnClick = false;
parentContainer.requestDisallowInterceptTouchEvent(true);
}
return true;
case MotionEvent.ACTION_UP:
animCount = 0;
if (currentButton < 0) {
return false;
}
if(animInProgress == true) {
return true;
}
animInProgress = true;
for (ButtonInfo currentButtonInfo : buttonInfoArray) {
applyResetAnimation(currentButtonInfo);
if (currentButtonInfo.isOnClick) {
// TODO onClick code
String currentTag = (String) currentButtonInfo.btnObj.getTag();
if(currentTag.equalsIgnoreCase(FIRST_TAG)) {
//handle first button click
} else if(currentTag.equalsIgnoreCase(SECOND_TAG)) {
//handle second button click
} else if(currentTag.equalsIgnoreCase(THIRD_TAG)) {
//handle third button click
} else if(currentTag.equalsIgnoreCase(FORTH_TAG)) {
//handle forth button click
}
}
}
return true;
case MotionEvent.ACTION_DOWN:
if (currentButton >= 0) {
return false;
}
if (animInProgress == true) {
return true;
}
animCount = 0;
int buttonIndex = 0;
for (buttonIndex = 0; buttonIndex < NUM_BUTTONS; buttonIndex++) {
final ButtonInfo currentButtonInfo = buttonInfoArray[buttonIndex];
if (isRectHit(currentButtonInfo.btnObj, motionEvent,
currentButtonInfo.OrigPos)) {
currentButton = buttonIndex;
touchDownX = (int) motionEvent.getRawX();
touchDownY = (int) motionEvent.getRawY();
currentButtonInfo.isOnClick = true;
currentButtonInfo.btnObj.setPressed(true);
break;
}
}
if (buttonIndex == NUM_BUTTONS) {
currentButton = -1;
}
break;
default:
break;
}
return false;
}
};
/**
* Get X POS
* #param yPos
* #return
*/
public float getXPos(float yPos) {
float xPos = (float) (centerPoint.x
+ Math.sqrt((radius * radius)
- ((yPos - centerPoint.y) * (yPos - centerPoint.y))));
return xPos;
}
/**
* Get YPos based on X
* #param xPos
* #param isPositive
* #return
*/
public float getYPos(float xPos, boolean isPositive) {
if (isPositive)
return (float) (centerPoint.y - Math.sqrt((radius * radius)
- ((xPos - centerPoint.x) * (xPos - centerPoint.x))));
else
return (float) (centerPoint.y + Math.sqrt((radius * radius)
- ((xPos - centerPoint.x) * (xPos - centerPoint.x))));
}
/**
* Get New angle from define point
* #param newPoint
* #return
*/
private double getNewAngle(PointF newPoint) {
double deltaY = newPoint.y - centerPoint.y;
double deltaX = newPoint.x - centerPoint.x;
double newPointAngle = Math.atan(-1.0 * deltaY / deltaX);
return newPointAngle;
}
/**
* get Point By Angle
* #param angle
* #return
*/
private PointF getPointByAngle(double angle) {
PointF newPos;
double newX = centerPoint.x + Math.cos(angle) * radius;
double newY = (centerPoint.y) - (Math.sin(angle) * radius);
newPos = new PointF((int) newX, (int) newY);
return newPos;
}
/**
* Set new location for passed button
* #param currentButtonIndex
* #param effectiveDelta
* #param percentageCompleted
* #return
*/
private double updateControl(int currentButtonIndex, PointF effectiveDelta,
double percentageCompleted) {
PointF newPos = new PointF();
StringBuilder s1 = new StringBuilder();
double maxAngleForCurrentButton = buttonInfoArray[currentButtonIndex].maxAngle;
double minAngleForCurrentButton = buttonInfoArray[currentButtonIndex].minAngle;
double targetAngleForCurrentButton;
if (effectiveDelta.y > 0) {
targetAngleForCurrentButton = maxAngleForCurrentButton;
} else {
targetAngleForCurrentButton = minAngleForCurrentButton;
}
if (percentageCompleted == -1) {
boolean isYDisplacement = effectiveDelta.y > effectiveDelta.x ? true
: false;
isYDisplacement = true;
if (isYDisplacement) {
float newY = buttonInfoArray[currentButtonIndex].OrigPos.y
+ effectiveDelta.y;
if (newY > (centerPoint.y) + (int) radius) {
newY = (centerPoint.y) + (int) radius;
} else if (newY < (centerPoint.y) - (int) radius) {
newY = (centerPoint.y) - (int) radius;
}
float newX = getXPos(newY);
newPos = new PointF(newX, newY);
s1.append("isYDisplacement true : ");
}
} else {
double effectiveAngle = buttonInfoArray[currentButtonIndex].origAngle
+ ((targetAngleForCurrentButton - buttonInfoArray[currentButtonIndex].origAngle) * percentageCompleted);
newPos = getPointByAngle(effectiveAngle);
s1.append("percentage completed : " + percentageCompleted + " : "
+ effectiveAngle);
}
double newAngle = getNewAngle(newPos);
// For angle, reverse condition, because in 1st quarter, it is +ve, in
// 4th quarter, it is -ve.
if (newAngle < maxAngleForCurrentButton) {
newAngle = maxAngleForCurrentButton;
newPos = getPointByAngle(newAngle);
s1.append("max angle : " + newAngle);
}
if (newAngle > minAngleForCurrentButton) {
newAngle = minAngleForCurrentButton;
newPos = getPointByAngle(newAngle);
s1.append("min angle : " + newAngle);
}
setTranslationX(buttonInfoArray[currentButtonIndex].btnObj,
newPos.x - 50);
setTranslationY(buttonInfoArray[currentButtonIndex].btnObj,
newPos.y - 50);
return newAngle;
}
/**
* Set button Position
* #param deltaPoint
*/
public void updateButtonPos(PointF deltaPoint) {
for (int buttonIndex = 0; buttonIndex < NUM_BUTTONS; buttonIndex++) {
if (currentButton == buttonIndex) {
buttonInfoArray[buttonIndex].currentAngle = updateControl(
buttonIndex, deltaPoint, -1);
double targetAngleForCurrentButton;
if (deltaPoint.y > 0) {
targetAngleForCurrentButton = buttonInfoArray[buttonIndex].maxAngle;
} else {
targetAngleForCurrentButton = buttonInfoArray[buttonIndex].minAngle;
}
double percentageCompleted = (1.0 * (buttonInfoArray[buttonIndex].currentAngle - buttonInfoArray[buttonIndex].origAngle))
/ (targetAngleForCurrentButton - buttonInfoArray[buttonIndex].origAngle);
for (int innerButtonIndex = 0; innerButtonIndex < NUM_BUTTONS; innerButtonIndex++) {
if (innerButtonIndex == buttonIndex)
continue;
buttonInfoArray[innerButtonIndex].currentAngle = updateControl(
innerButtonIndex, deltaPoint, percentageCompleted);
}
break;
}
}
}
/**
* Find whether touch in button's rectanlge or not
* #param v
* #param rect
*/
private static void getHitRect(View v, Rect rect) {
rect.left = (int) com.nineoldandroids.view.ViewHelper.getX(v);
rect.top = (int) com.nineoldandroids.view.ViewHelper.getY(v);
rect.right = rect.left + v.getWidth();
rect.bottom = rect.top + v.getHeight();
}
private boolean isRectHit(View viewObj, MotionEvent motionEvent,
PointF viewOrigPos) {
Rect outRect = new Rect();
int x = (int) motionEvent.getX();
int y = (int) motionEvent.getY();
getHitRect(viewObj, outRect);
if (outRect.contains(x, y)) {
return true;
} else {
return false;
}
}
/**
* On Finish update transition
*/
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.activityfinishin, R.anim.activityfinishout);
}
/**
* On Native Back Pressed
*/
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}