Rotate Marker and Move Animation on Map like Uber Android - java

I am working on a project similar to UBER, Lyft or OLA ie. Map on the home with available moving Cars.
I'm looking for some kind of Library which can make Cars move and take turn smoothly just like UBER. For now I was able to move car smoothly from one lat-long to another with the below code. But tricky part is Taking turn and make sure the car face to front when moving to direction.
Smooth Moving Car Code:
final LatLng SomePos = new LatLng(12.7796354, 77.4159606);
try {
if (googleMap == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
}
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
googleMap.setTrafficEnabled(false);
googleMap.setIndoorEnabled(false);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(SomePos));
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
.target(googleMap.getCameraPosition().target)
.zoom(17)
.bearing(30)
.tilt(45)
.build()));
myMarker = googleMap.addMarker(new MarkerOptions()
.position(SomePos)
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher))
.title("Hello world"));
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker arg0) {
final LatLng startPosition = myMarker.getPosition();
final LatLng finalPosition = new LatLng(12.7801569, 77.4148528);
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final Interpolator interpolator = new AccelerateDecelerateInterpolator();
final float durationInMs = 3000;
final boolean hideMarker = false;
handler.post(new Runnable() {
long elapsed;
float t;
float v;
#Override
public void run() {
// Calculate progress using interpolator
elapsed = SystemClock.uptimeMillis() - start;
t = elapsed / durationInMs;
LatLng currentPosition = new LatLng(
startPosition.latitude * (1 - t) + finalPosition.latitude * t,
startPosition.longitude * (1 - t) + finalPosition.longitude * t);
myMarker.setPosition(currentPosition);
// Repeat till progress is complete.
if (t < 1) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
myMarker.setVisible(false);
} else {
myMarker.setVisible(true);
}
}
}
});
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}

I recently came across the same use-case. Here is my solution on it.
First, I would like to thank #VipiN for sharing "The Smooth Moving Car Code". It works smoothly.
The second part is to place car-marker in the right direction and rotate it according to turns. To achieve this I calculated the bearing or heading angle between two successive points(i.e. location updates you receive from device/server). This link will help you understand the maths behind it.
The following code will give you bearing between two locations:
private double bearingBetweenLocations(LatLng latLng1,LatLng latLng2) {
double PI = 3.14159;
double lat1 = latLng1.latitude * PI / 180;
double long1 = latLng1.longitude * PI / 180;
double lat2 = latLng2.latitude * PI / 180;
double long2 = latLng2.longitude * PI / 180;
double dLon = (long2 - long1);
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(dLon);
double brng = Math.atan2(y, x);
brng = Math.toDegrees(brng);
brng = (brng + 360) % 360;
return brng;
}
Finally, we need to rotate the car-marker by the angle that we get from above method.
private void rotateMarker(final Marker marker, final float toRotation) {
if(!isMarkerRotating) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = marker.getRotation();
final long duration = 1000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
isMarkerRotating = true;
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
marker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
isMarkerRotating = false;
}
}
});
}
}
Cheers!

Here is my code to move marker like uber. i have shown two ways to move marker .
Important Note: To move car on proper road [like ola,uber] you need to use road api provided by google
1.By static latitude and longitude
2.By Real time Latitude and longitude
package com.gangsofcoder.googlemapdemo;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import cz.msebera.android.httpclient.Header;
public class MoveCar extends AppCompatActivity {
private GoogleMap googleMap;
SupportMapFragment mapFragment;
Marker marker;
private boolean isMarkerRotating = false;
ArrayList<LatLng> listOfPoints = new ArrayList<>();
int currentPt = 0;
LatLng finalPosition;
Marker mMarker;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
//new location details
listOfPoints.add(new LatLng(30.701623, 76.684220));
listOfPoints.add(new LatLng(30.702486, 76.685487));
listOfPoints.add(new LatLng(30.703135, 76.684891));
listOfPoints.add(new LatLng(30.703256, 76.685000));
listOfPoints.add(new LatLng(30.703883, 76.685941));
listOfPoints.add(new LatLng(30.703413, 76.685190));
}
private void setUpMapIfNeeded() {
if (mapFragment == null) {
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
if (mapFragment != null) {
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
loadMap(googleMap);
}
});
}
}
}
private void loadMap(GoogleMap map) {
googleMap = map;
mMarker = googleMap.addMarker(new MarkerOptions().position(new LatLng(30.701623, 76.684220)).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_car)));
final Handler handler = new Handler();
//Code to move car along static latitude and longitude
/* handler.postDelayed(new Runnable() {
#Override
public void run() {
if (currentPt < listOfPoints.size()) {
//post again
Log.d("tess", "inside run ");
Location targetLocation = new Location(LocationManager.GPS_PROVIDER);
targetLocation.setLatitude(listOfPoints.get(currentPt).latitude);
targetLocation.setLongitude(listOfPoints.get(currentPt).longitude);
animateMarkerNew(targetLocation, mMarker);
handler.postDelayed(this, 3000);
currentPt++;
} else {
Log.d("tess", "call back removed");
//removed callbacks
handler.removeCallbacks(this);
}
}
}, 3000);*/
//Here move marker along real time updates
final RequestParams params = new RequestParams();
params.put("source_lattitude", "lat");
params.put("source_longitude", "long");
params.put("date", "date");
//new handler
handler.postDelayed(new Runnable() {
#Override
public void run() {
LoopjHttpClient.post(getString(R.string.default_upload_website), params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
JSONObject jsonObject = new JSONObject(new String(responseBody));
String status = jsonObject.getString("status");
String text = jsonObject.getString("text");
//reading json array
JSONArray jsonArray = jsonObject.getJSONArray("result");
String source = jsonArray.getJSONObject(0).getString("source");
String[] latLong = source.split(",");
Location location = new Location(LocationManager.GPS_PROVIDER);
location.setLatitude(Double.parseDouble(latLong[0]));
location.setLongitude(Double.parseDouble(latLong[1]));
//calling method to animate marker
animateMarkerNew(location, mMarker);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("onFailure", "onFailure");
}
});
handler.postDelayed(this, 3000);
}
}, 3000);
}
private void animateMarkerNew(final Location destination, final Marker marker) {
if (marker != null) {
final LatLng startPosition = marker.getPosition();
final LatLng endPosition = new LatLng(destination.getLatitude(), destination.getLongitude());
final float startRotation = marker.getRotation();
final LatLngInterpolatorNew latLngInterpolator = new LatLngInterpolatorNew.LinearFixed();
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.setDuration(3000); // duration 3 second
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
try {
float v = animation.getAnimatedFraction();
LatLng newPosition = latLngInterpolator.interpolate(v, startPosition, endPosition);
marker.setPosition(newPosition);
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
.target(newPosition)
.zoom(15.5f)
.build()));
marker.setRotation(getBearing(startPosition, new LatLng(destination.getLatitude(), destination.getLongitude())));
} catch (Exception ex) {
//I don't care atm..
}
}
});
valueAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
// if (mMarker != null) {
// mMarker.remove();
// }
// mMarker = googleMap.addMarker(new MarkerOptions().position(endPosition).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_car)));
}
});
valueAnimator.start();
}
}
private interface LatLngInterpolatorNew {
LatLng interpolate(float fraction, LatLng a, LatLng b);
class LinearFixed implements LatLngInterpolatorNew {
#Override
public LatLng interpolate(float fraction, LatLng a, LatLng b) {
double lat = (b.latitude - a.latitude) * fraction + a.latitude;
double lngDelta = b.longitude - a.longitude;
// Take the shortest path across the 180th meridian.
if (Math.abs(lngDelta) > 180) {
lngDelta -= Math.signum(lngDelta) * 360;
}
double lng = lngDelta * fraction + a.longitude;
return new LatLng(lat, lng);
}
}
}
//Method for finding bearing between two points
private float getBearing(LatLng begin, LatLng end) {
double lat = Math.abs(begin.latitude - end.latitude);
double lng = Math.abs(begin.longitude - end.longitude);
if (begin.latitude < end.latitude && begin.longitude < end.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)));
else if (begin.latitude >= end.latitude && begin.longitude < end.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
else if (begin.latitude >= end.latitude && begin.longitude >= end.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
else if (begin.latitude < end.latitude && begin.longitude >= end.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
return -1;
}
}

Since its been bit confusing for SO users to look for working code in two different posts. Here is the working code for Rotate and Move Marker which seamlessly worked for me.
in MainActivity.java
public void rotateMarker(final Marker marker, final float toRotation, final float st) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = st;
final long duration = 1555;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
marker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
public void animateMarker(final LatLng toPosition,final boolean hideMarke) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = googleMap.getProjection();
Point startPoint = proj.toScreenLocation(m.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 5000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
double lng = t * toPosition.longitude + (1 - t)
* startLatLng.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startLatLng.latitude;
m.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarke) {
m.setVisible(false);
} else {
m.setVisible(true);
}
}
}
});
}

Finally wrote the code that works exactly in the similar manner that OLA CABS does...
Here it is -
Put your google maps fragment in a Relative layout and put the marker(as image view ) in the center -
In your fragment's code once you have setup all the google maps basic working write the following code for the onMapReady(GoogleMap googleMap) function-
My Code is as follows -
//Step 1 -
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity_for_request_pages" />
<ImageView
android:layout_width="30sp"
android:layout_height="30sp"
android:layout_centerInParent="true"
android:id="#+id/central_marker"
android:src="#drawable/marker_pic"/>
</RelativeLayout>
//Step 2 -
#Override
public void onMapReady(GoogleMap googleMap) {
central_marker = (ImageView)v.findViewById(R.id.central_marker);
int init_loc = 0,final_loc = -300;
mMap = googleMap;
final CountDownTimer timer = new CountDownTimer(300,300) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
init_loc = 0;
ObjectAnimator objectAnimatorY = ObjectAnimator.ofFloat(central_marker, "translationY", final_loc, init_loc);
objectAnimatorY.setDuration(200);
objectAnimatorY.start();
}
};
mMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
#Override
public void onCameraMoveStarted(int i) {
System.out.println("Camera started moving worked");
timer.cancel();
ObjectAnimator objectAnimatorY = ObjectAnimator.ofFloat(central_marker, "translationY", init_loc, final_loc);
objectAnimatorY.setDuration(200);
objectAnimatorY.start();
init_loc = -300;
}
});
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
System.out.println("Camera idle worked");
if(initial_flag!=0)
{
System.out.println("Camera Setting timer now");
timer.cancel();
timer.start();
}
initial_flag++;
System.out.println("Camera Value of initial_flag ="+initial_flag);
}
});
}

Firstly,I would like to thank you both #Vipin Negi & #Prasad for such a good & awesomely working code.Since there are many pending queries above, I want to make all the above stuff a little simpler. Guys, just follow the following steps to achieve the marker rotation.
1. Define below two methods in your MainActivity.java file
private double bearingBetweenLocations(LatLng latLng1, LatLng latLng2) {
double PI = 3.14159;
double lat1 = latLng1.latitude * PI / 180;
double long1 = latLng1.longitude * PI / 180;
double lat2 = latLng2.latitude * PI / 180;
double long2 = latLng2.longitude * PI / 180;
double dLon = (long2 - long1);
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(dLon);
double brng = Math.atan2(y, x);
brng = Math.toDegrees(brng);
brng = (brng + 360) % 360;
return brng;
}
&
private void rotateMarker(final Marker marker, final float toRotation) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = marker.getRotation();
final long duration = 1000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
marker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
2. After this, add the following lines to the code where you want your marker to rotate.
double bearing = bearingBetweenLocations(m.getPosition(), updatedLatLng);
rotateMarker(m, (float) bearing);
Note that "m" is your marker object that you want to rotate.
And, you're done!!!
If you want marker animation related help,you can use this code.

Try google default rotation or see the detail explanation Markers Rotation
private void updateCamera(LatLng currentLatLng, Location location) {
//googleMap.clear();
if (marker == null) {
MarkerOptions options = new MarkerOptions();
options.position(currentLatLng);
options.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_driver_car_pin_v));
options.flat(true);
options.anchor(0.5f, 0.5f);
marker = googleMap.addMarker(options);
} else {
marker.setPosition(currentLatLng);
marker.setRotation(location.getBearing());
}
CameraPosition cameraPosition = new CameraPosition.Builder(googleMap.getCameraPosition())
.target(currentLatLng).zoom(18).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}

Related

Is there a better way to get this value from compass?

I need to get values from a compass and do it in rxJava.
So I've made this code:
private void goCompass()
{
Observable.create(new Observable.OnSubscribe<SensorEventListener>()
{
SensorEventListener listener = null;
#Override
public void call(final Subscriber<? super SensorEventListener> subscriber)
{
Sensor gsensor;
Sensor msensor;
final float[] mGravity = new float[3];
final float[] mGeomagnetic = new float[3];
listener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
final float alpha = 0.97f;
Float azimuth = 0f;
synchronized (this) {
if(switchChecked == false) {
subscriber.onNext(listener);
subscriber.onCompleted();
}
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mGravity[0] = alpha * mGravity[0] + (1 - alpha)
* event.values[0];
mGravity[1] = alpha * mGravity[1] + (1 - alpha)
* event.values[1];
mGravity[2] = alpha * mGravity[2] + (1 - alpha)
* event.values[2];
// mGravity = event.values;
// Log.e(TAG, Float.toString(mGravity[0]));
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
// mGeomagnetic = event.values;
mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha)
* event.values[0];
mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha)
* event.values[1];
mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha)
* event.values[2];
// Log.e(TAG, Float.toString(event.values[0]));
}
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
azimuth = (float) Math.toDegrees(orientation[0]); // orientation
azimuth = (azimuth + 360) % 360;
Log.d("obs", "azimuth (rad): " + azimuth);
layout.setRotation(azimuth);
imageView.setRotation(-azimuth);
contlayout.setRotation(azimuth);
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
sensorManager = (SensorManager) getActivity()
.getSystemService(Context.SENSOR_SERVICE);
gsensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
msensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
sensorManager.registerListener(listener, gsensor,
SensorManager.SENSOR_DELAY_FASTEST);
sensorManager.registerListener(listener, msensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
}).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<SensorEventListener>() {
#Override
public void onCompleted()
{
}
#Override
public void onError(Throwable e)
{
}
#Override
public void onNext(SensorEventListener listener)
{
sensorManager.unregisterListener(listener);
}
});
}
and it works. However, I'm at the beginning of rxJava and I want to know if there are better ways to do this things:
I've tried to get the azimuth value in onNext() method any times, but it doesn't work
I want to make it asynchronously but I couldn't because registerListener works only in the mainThread() and so if I use Schedulers.io() I need also to do runOnUiThread() method.
There are other ways to do it?
Thank you for help

ImageView still visible after setVisibility(View.INVISIBLE)

I am trying to make a camera app that shows an overlay when a picture is taken.
When this overlay is shown the other UI components (except for the FrameLayout that shows the picture) should go invisible.
But it seems that while my 2 imagebuttons go invisble, my imageview(ivCompass) doesn't.
Here is the code that gets called when a picture is taken
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//create a new intent...
String path = createFile(data);
intent = new Intent();
intent.putExtra("path", path);
mBearingProvider.updateBearing();
bearing = mBearingProvider.getBearing();
cardinalDirection = bearingToString(bearing);
//((TextView) findViewById(R.id.tvPicDirection)).setText(cardinalDirection);
Log.e("Direction", cardinalDirection + "," + bearing);
findViewById(R.id.btnFlash).setVisibility(View.INVISIBLE);
findViewById(R.id.btnCapture).setVisibility(View.INVISIBLE);
findViewById(R.id.ivCompass).setVisibility(View.INVISIBLE);
findViewById(R.id.pictureOverlay).setVisibility(View.VISIBLE);
}
};
And here is the layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ImageButton
android:id="#+id/btnFlash"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:layout_margin="10dp"
android:src="#drawable/camera_flash_on"
android:background="#drawable/circle_flash"
android:onClick="changeFlashMode"/>
<ImageButton
android:id="#+id/btnCapture"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_margin="10dp"
android:src="#drawable/icon_camera"
android:background="#drawable/circle_camera"/>
<ImageView
android:id="#+id/ivCompass"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentRight="true"
android:src="#drawable/camera_compass"
android:background="#android:color/transparent"/>
<RelativeLayout
android:id="#+id/pictureOverlay"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:background="#color/alphaBlack"
android:visibility="invisible">
</RelativeLayout>
I think It's just a mistake with naming, syntax or something like that, but I can't seem to find it.
EDIT:
Here is the entire Activity
public class CameraActivity extends AppCompatActivity implements BearingToNorthProvider.ChangeEventListener {
private Camera mCamera;
private CameraView mCameraView;
private float mDist = 0f;
private String flashMode;
private ImageButton flashButton;
private Intent intent;
private BearingToNorthProvider mBearingProvider;
private double bearing;
private double currentBearing = 0d;
private String cardinalDirection = "?";
private final int REQUEST_CODE_ASK_PERMISSIONS = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mCamera = getCameraInstance();
mCameraView = new CameraView(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraView);
ImageButton captureButton = (ImageButton) findViewById(R.id.btnCapture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Camera.Parameters params = mCamera.getParameters();
params.setFlashMode(flashMode);
mCamera.setParameters(params);
mCamera.takePicture(null, null, mPicture);
}
});
SharedPreferences sharedPref = this.getSharedPreferences(getString(R.string.apiKey), Context.MODE_PRIVATE);
flashMode = sharedPref.getString(getString(R.string.flashMode), Camera.Parameters.FLASH_MODE_OFF);
flashButton = (ImageButton) findViewById(R.id.btnFlash);
setFlashButton();
mBearingProvider = new BearingToNorthProvider(this,this);
mBearingProvider.setChangeEventListener(this);
mBearingProvider.start();
}
#Override
protected void onPause() {
super.onPause();
mBearingProvider.stop();
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* #return the instance of the camera
*/
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
Log.e("CamException", e.toString());
}
return camera;
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//create a new intent...
String path = createFile(data);
intent = new Intent();
intent.putExtra("path", path);
mBearingProvider.updateBearing();
bearing = mBearingProvider.getBearing();
cardinalDirection = bearingToString(bearing);
//((TextView) findViewById(R.id.tvPicDirection)).setText(cardinalDirection);
Log.e("Direction", cardinalDirection + "," + bearing);
findViewById(R.id.btnFlash).setVisibility(View.INVISIBLE);
findViewById(R.id.btnCapture).setVisibility(View.INVISIBLE);
findViewById(R.id.ivCompass).setVisibility(View.INVISIBLE);
findViewById(R.id.pictureOverlay).setVisibility(View.VISIBLE);
}
};
private void confirmPicture(View v) {
/*String direction = String.valueOf(((TextView) findViewById(R.id.tvPicDirection)).getText());
String description = String.valueOf(((EditText) findViewById(R.id.tvPicDescription)).getText());
intent.putExtra("direction", direction);
intent.putExtra("description", description);*/
//close this Activity...
setResult(Activity.RESULT_OK, intent);
finish();
}
//region File Methods
/**
* Method that creates a file from the given byte array and saves the file in the Pictures Directory
* #param data is the array of bytes that represent the picture taken by the camera
* #return the path of created file
*/
private String createFile(byte[] data){
checkFilePermissions();
File picFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "tempPic.jpg" + File.separator);
String path = picFile.getPath();
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(picFile));
bos.write(data);
bos.flush();
bos.close();
return path;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
/**
* Checks the permission for reading to and writing from the external storage
*/
private void checkFilePermissions() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
int hasWriteExternalStoragePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
return;
}
}
}
//endregion
//region Zoom Methods
#Override
public boolean onTouchEvent(MotionEvent event) {
// Get the pointer ID
Camera.Parameters params = mCamera.getParameters();
int action = event.getAction();
if (event.getPointerCount() > 1) {
// handle multi-touch events
if (action == MotionEvent.ACTION_POINTER_DOWN) {
mDist = getFingerSpacing(event);
} else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported()) {
mCamera.cancelAutoFocus();
handleZoom(event, params);
}
} else {
// handle single touch events
if (action == MotionEvent.ACTION_UP) {
handleFocus(event, params);
}
}
return true;
}
private void handleZoom(MotionEvent event, Camera.Parameters params) {
int maxZoom = params.getMaxZoom();
int zoom = params.getZoom();
float newDist = getFingerSpacing(event);
if (newDist > mDist) {
//zoom in
if (zoom < maxZoom)
zoom++;
} else if (newDist < mDist) {
//zoom out
if (zoom > 0)
zoom--;
}
mDist = newDist;
params.setZoom(zoom);
mCamera.setParameters(params);
}
public void handleFocus(MotionEvent event, Camera.Parameters params) {
int pointerId = event.getPointerId(0);
int pointerIndex = event.findPointerIndex(pointerId);
// Get the pointer's current position
float x = event.getX(pointerIndex);
float y = event.getY(pointerIndex);
List<String> supportedFocusModes = params.getSupportedFocusModes();
if (supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
mCamera.autoFocus(new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean b, Camera camera) {
// currently set to auto-focus on single touch
}
});
}
}
/** Determine the space between the first two fingers */
private float getFingerSpacing(MotionEvent event) {
double x = event.getX(0) - event.getX(1);
double y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
//endregion
//region Flash Methods
public void changeFlashMode(View v) {
switch (flashMode) {
case Camera.Parameters.FLASH_MODE_ON :
flashMode = Camera.Parameters.FLASH_MODE_AUTO;
break;
case Camera.Parameters.FLASH_MODE_AUTO :
flashMode = Camera.Parameters.FLASH_MODE_OFF;
break;
case Camera.Parameters.FLASH_MODE_OFF :
flashMode = Camera.Parameters.FLASH_MODE_ON;;
break;
}
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.flashMode), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(getString(R.string.flashMode), flashMode);
editor.commit();
setFlashButton();
}
public void setFlashButton() {
switch (flashMode) {
case Camera.Parameters.FLASH_MODE_ON :
flashButton.setImageDrawable(getResources().getDrawable(R.drawable.camera_flash_on));
break;
case Camera.Parameters.FLASH_MODE_AUTO :
flashButton.setImageDrawable(getResources().getDrawable(R.drawable.camera_flash_auto));
break;
case Camera.Parameters.FLASH_MODE_OFF :
flashButton.setImageDrawable(getResources().getDrawable(R.drawable.camera_flash_off));
break;
}
}
//endregion
//region Bearing Methods
/**
* Method that gives a cardinal direction based on the current bearing to the true north
* #param bearing is the bearing to the true north
* #return cardinal direction that belongs to the bearing
*/
private String bearingToString(Double bearing) {
String strHeading = "?";
if (isBetween(bearing,-180.0,-157.5)) { strHeading = "South"; }
else if (isBetween(bearing,-157.5,-112.5)) { strHeading = "SouthWest"; }
else if (isBetween(bearing,-112.5,-67.5)) { strHeading = "West"; }
else if (isBetween(bearing,-67.5,-22.5)) { strHeading = "NorthWest"; }
else if (isBetween(bearing,-22.5,22.5)) { strHeading = "North"; }
else if (isBetween(bearing,22.5,67.5)) { strHeading = "NorthEast"; }
else if (isBetween(bearing,67.5,112.5)) { strHeading = "East"; }
else if (isBetween(bearing,112.5,157.5)) { strHeading = "SouthEast"; }
else if (isBetween(bearing,157.5,180.0)) { strHeading = "South"; }
return strHeading;
}
/**
* Method that checks if a certain number is in a certain range of numbers
* #param x is the number to check
* #param lower is the number that defines the lower boundary of the number range
* #param upper is the number that defines the upper boundary of the number range
* #return true if the number is between the other numbers, false otherwise
*/
private boolean isBetween(double x, double lower, double upper) {
return lower <= x && x <= upper;
}
/*
Method that triggers when the bearing changes, it sets the current bearing and sends an updated context to the provider
*/
#Override
public void onBearingChanged(double bearing) {
this.bearing = bearing;
mBearingProvider.setContext(this);
ImageView image = (ImageView) findViewById(R.id.ivCompass);
// create a rotation animation (reverse turn degree degrees)
if (bearing < 0) {
bearing += 360;
}
RotateAnimation ra = new RotateAnimation((float)currentBearing,(float)-bearing, Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF,0.5f);
// how long the animation will take place
ra.setDuration(210);
// set the animation after the end of the reservation status
ra.setFillAfter(true);
// Start the animation
image.startAnimation(ra);
currentBearing = -bearing;
mBearingProvider.setContext(this);
}
//endregion
}
EDIT 2:
I have made a small change to the onBearingChanged Method and now the compass is still visible, but thinks it's invisible and isn't moving because of my new if statement
#Override
public void onBearingChanged(double bearing) {
this.bearing = bearing;
mBearingProvider.setContext(this);
ImageView image = (ImageView) findViewById(R.id.ivCompass);
if (image.getVisibility() == View.VISIBLE) {
// create a rotation animation (reverse turn degree degrees)
if (bearing < 0) {
bearing += 360;
}
RotateAnimation ra = new RotateAnimation((float) currentBearing, (float) -bearing, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// how long the animation will take place
ra.setDuration(210);
// set the animation after the end of the reservation status
ra.setFillAfter(true);
// Start the animation
image.startAnimation(ra);
currentBearing = -bearing;
}
mBearingProvider.setContext(this);
}
If you have some kind of animation, the animation probably intefieres on the calling to invisibility. Try with this just before calling INVISIBLE:
findViewById(R.id.ivCompass).clearAnimation();

Latitude and longitude per pixel Google static maps

I have a static map, i know center coordinates in latitude and longitude, zoom level and image dimensions.
I don't understood if google static maps are already flattened and latitude and longitude per pixel are the same anywhere. If it's not like that i whant to know how can i calculate latidude and longitude per pixel and then meters per pixel , and how does that values vary with latitude .
P.S. I'm developing an android application that download an static map and computes distance between 2 points , but i've done that asuming the lat and long per pixel are the same ...and doesn't depend on latitude(position on globe)
Here is my mainactivity
package com.mnav.nav;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.view.View.*;
import java.net.*;
import org.apache.http.*;
import android.graphics.*;
import java.io.*;
import android.graphics.drawable.*;
public class MainActivity extends Activity
{ Button start, dist;
TextView txt;
EditText lat, longit, zoom;
ImageView img;
Handler mhandler ;
Bitmap bit, original;
Boolean run = false, firstpoint = false, secondpoint = false;
String z, latitude, longitude;
int level;
int[] pointa = new int[2];
int[] pointb = new int[2];
double unit;
int maxx, maxy, minx, miny, distx, disty, distance1;
double distance;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start=(Button)findViewById(R.id.button);
lat = (EditText)findViewById(R.id.latitude);
longit = (EditText)findViewById(R.id.longitude);
img = (ImageView)findViewById(R.id.img);
zoom =(EditText)findViewById(R.id.zoom);
dist = (Button)findViewById(R.id.dist);
txt = (TextView)findViewById(R.id.txt);
mhandler = new Handler();
start.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{ z = zoom.getText().toString();
latitude = lat.getText().toString();
longitude = longit.getText().toString();
Thread thr = new Thread(new GetImage());
thr.start();
}
});
img.setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{ int i, j;
int x = (int)event.getX();
int vertical = (int)event.getY();
if(secondpoint==true)
{ bit = original.copy(Bitmap.Config.ARGB_4444, true);
img.setImageBitmap(bit);
secondpoint = false;
}
txt.setText(Integer.toString(x)+ " "+Integer.toString(vertical));
for (i = x-2; i < x+3; i++)
{
for(j=vertical-2; j<vertical+3; j++)
{
bit.setPixel(i,j, Color.WHITE);
}
}
bit.setPixel(x,vertical,Color.GREEN);
img.setImageBitmap(bit);
if(firstpoint)
{
pointb[0] = x; pointb[1]=vertical;
secondpoint = true;
firstpoint = false;
}
else
{
pointa[0]=x; pointa[1]=vertical;
firstpoint=true;
}
return false;
}
});
dist.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View p1)
{
unit = 0.1412/800;
unit = unit*500;
level = Integer.parseInt(z);
if(level == 20)
{
unit = unit;
}
else
if(level == 19)
{
unit = unit*2;
}
else
if(level==18)
{
unit = unit*4;
}
else
if(level == 17)
{
unit =unit*8;
}
else
if(level==16)
{
unit = unit*16;
}
else
if(level==15)
{
unit = unit*32;
}
else
if(level==14)
{
unit = unit*64;
}
else
if(level==13)
{
unit = unit*128;
}
else
if(level == 12)
{
unit = unit*256;
}
else
if(level==11)
{
unit = unit*512;
}
else
if(level==10)
{
unit = unit*1024;
}
distx = Math.abs(pointa[0]-pointb[0]);
disty= Math.abs(pointa[1]-pointb[1]);
distance1 = distx*distx+disty*disty;
distance = Math.sqrt(distance1);
distance = unit*distance;
txt.setText(Double.toString(distance)+" meters");
}
});
}
public class GetImage implements Runnable
{
String Url = "http://maps.google.com/staticmap?center=" + latitude+","+longitude+"&format=png&zoom="+ z +"&size=500x500&scale=1&maptype=hybrid&key=ABQIAAAA-O3c-Om9OcvXMOJXreXHAxRexG7zW5nSjltmIc1ZE-b8yotBWhQYQEU3J87QIBc4nfuySpoW_K6woA";
Bitmap bmp;
#Override
public void run()
{
try
{ mhandler.post(new Runnable()
{
#Override
public void run()
{
txt.setText("Wait...file is downloading...");
}
});
bmp = BitmapFactory.decodeStream((InputStream)new URL(Url).getContent());
}
catch (IOException e)
{ mhandler.post(new Runnable()
{
#Override
public void run()
{
// TODO: Implement this method
Toast.makeText(getApplicationContext(), "Something wrong just happend", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
mhandler.post(new Runnable()
{
#Override
public void run()
{
if (bmp!=null)
{ txt.setText("Map downloaded..");
img.setImageBitmap(bmp);
bit = ((BitmapDrawable)img.getDrawable()).getBitmap();
bit = bit.copy(Bitmap.Config.ARGB_4444, true);
original = bit.copy(Bitmap.Config.ARGB_4444, true);
}
else
{
mhandler.post(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), "null bitmap, sorry", Toast.LENGTH_LONG).show();
}
});
}
}
});
}
}
}

Google Maps android IndexOutOfBoundsException

I am trying to get markers placed on the map and fly to their destination. within a forloop i have an if statement, i wish it to do this:
for(i loop){
If (array(i) == null{ spawn plane code}
else {move plane code}
here is the code:
package com.fly.plane;
import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.fly.plane.R;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.R.array;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;
public class MyMapActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get data JSON
private static String url = "http://edmundgentle.com/snippets/flights/api.php";
// JSON Node speeds
private static final String TAG_data = "data";
private static final String TAG_BEARING = "bearing";
private static final String TAG_SPEED = "speed";
private static final String TAG_ARR = "arr";
private static final String TAG_ARR_TIME = "time";
private static final String TAG_ARR_LAT = "lat";
private static final String TAG_ARR_LON = "lon";
private static final String TAG_DEP = "dep";
private static final String TAG_DEP_TIME = "time";
private static final String TAG_DEP_LAT = "lat";
private static final String TAG_DEP_LON = "lon";
// data JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, Double>> contactList;
// Hashmap for ListView
ArrayList<Double> ct;
List<Marker> markers = new ArrayList<Marker>();
//final Handler handler;
private GoogleMap mMap;
public static final LatLng dest(Double alt,Double aln, int i){
//final double latitude = Double.parseDouble(alt);
//final double longitude = Double.parseDouble(aln);
return new LatLng(alt, aln);
}
public double latt = -15.48169437461;
public double lng = -15.48169437461;
public ArrayList<Integer> dLat;
public String[] markerList;
public String dlat;
public String dlon;
public String alat;
public String alon;
private int count;
public boolean wait = true;
//private Button startB;
public TextView text;
Timer timing;
double time = 600;
double timm = 1;
long timer = 18000000;
long newTime;
TextView tv, test;
Thread t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_map);
contactList = new ArrayList<HashMap<String, Double>>();
ct = new ArrayList<Double>();
//ListView lv = getListView();
//create markers
new Getdata().execute();
// timer showing time of day in fast time
t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(600);
runOnUiThread(new Runnable() {
#Override
public void run() {
timer = timer +60000;
if (timer >= 64000000) timer = 18000000;
newTime = timer;
// update TextView here!
//String time = "HH:mm:ss";
//tv.setText(DateFormat.format(time , timer));
tv.setText(Double.toString(time));
test.setText(Double.toString(timm));
//tv.setText(Double.toString(contactList.get(20).get("time")));
//Timer();
}
});
}
} catch (InterruptedException e) {
}
}
};
tv = new TextView(this);
test = new TextView(this);
tv=(TextView)findViewById(R.id.timer);
test=(TextView)findViewById(R.id.test);
// run the mUpdateUITimerTask's run() method in 10 seconds from now
}
// animate each plane
public void animateMarker(final Marker marker , final LatLng toPosition,
final boolean hideMarker, final double spd) {
float speed = (float) spd;// Float.parseFloat(spd);
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final float duration = 10 * speed;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) ((float) elapsed
/ duration));
double lng = t * toPosition.longitude + (1 - t)
* startLatLng.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
handler.postDelayed(this, 16);
if (hideMarker) {
marker.setVisible(false);
} else {
marker.setVisible(true);
}
}
}
});
}
public void Timer(){
//TimerTask tasknew = new TimerTask();
timing = new Timer();
timing.schedule(new CreateMarker(), 1000, 1000);
}
public String calcCurPos(double curlat, double curlon, double deslat, double deslon, double avgSpd, double bearing){
double distance = avgSpd * 0.0167;
// check if degrees or radians
//deslat = distance * Math.cosh(bearing);
//double retLat = curlat + deslat;
//double dPhi = Math.log(Math.tan(retLat/2+Math.PI/4)/Math.tan(curlat/2+Math.PI/4));
//double q = deslat/dPhi deslat/dPhi : Math.cos(curlat);
bearing = bearing * Math.PI / 180;
int radius = 6371;
double nextLat = Math.asin(Math.sin(curlat)* Math.cos(distance/radius)
+ Math.cos(curlat)*Math.sin(distance/radius)*Math.cos(bearing));
double nextLon = curlon + Math.atan2(Math.sin(bearing)* Math.sin(distance/ radius)
* Math.cos(curlat), Math.cos(distance/radius)-Math.sin(curlat) * Math.sin(nextLat));
nextLat = (nextLat * 180) / Math.PI;
nextLon = (nextLon * 180) / Math.PI;
/**
* Warning might want to convert them to string prior to return.
*/
return nextLat + ";" + nextLon;
}
public class CreateMarker extends TimerTask{
#Override
public void run() {
// TODO Auto-generated method stub
// print test
//tv.setText(Double.toString(time));
//tv.setText(Double.toString(time));
if (time >= 2400){
time=0;
}
time += 1;
//mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
for (int i =0; i < 100;i++){
// get data from array list
final double depLat = contactList.get(i).get("dlat");
final double depLon = contactList.get(i).get("dlon");
final double arLat = contactList.get(i).get("alat");
final double arLon = contactList.get(i).get("alon");
final double spd = contactList.get(i).get("speed");
final double dTime = contactList.get(i).get("time");
double curLat = contactList.get(i).get("clat");
double curLon = contactList.get(i).get("clon");
final double bearing = contactList.get(i).get("bearing");
final int j = i;
//int dTime = Integer.parseInt(dtime);
double oldLat = curLat;
if (time >= dTime)
{
if (curLat < arLat || curLat > 0){
String latlng = calcCurPos(curLat, curLon, arLat, arLon ,spd, bearing );
String[] values = latlng.split(";");
curLat = Double.parseDouble(values[0]);
curLon = Double.parseDouble(values[1]);
final double crLat = curLat;
final double crLon = curLon;
final LatLng position = new LatLng(crLat,crLon);
/*Marker mo = mMap.addMarker(new MarkerOptions()
.position(new LatLng(depLat, depLon))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));*/
//DrawMarker();
//animateMarker(markers.get(i), position , true, spd);
try{
if (markers.get(i) == null){
//timm += 1;
timm += 1;
runOnUiThread(new Runnable() {
#Override
public void run() {
final Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(depLat, depLon))
.title("Hello world")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));
markers.add(marker);
//marker.setVisible(false);
//animateMarker(markers.get(j), new LatLng(arLat,arLon) , true, spd);
//Marker marker = markers.get(i);
//marker.setPosition(position);
}
});
}
else //(markers.get(i) != null){
{
Marker marker = markers.get(i);
marker.setPosition(position);
marker.setVisible(false);
//animateMarker(markers.get(i), position , true, spd);
}
}
catch(NullPointerException npe)
{
//do something else
}
}
}
}
//return null;
}
}
/**
* Async task class to get json by making HTTP call
* */
private class Getdata extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MyMapActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
HTTPHandler sh = new HTTPHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, HTTPHandler.GET);
Log.d("Response: ", "> " + jsonStr);
boolean limit = false;
if (jsonStr != null || limit == false) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_data);
// looping through All data
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String bearing = c.getString(TAG_BEARING);
String spd = c.getString(TAG_SPEED);
// departure node is JSON Object
JSONObject dep = c.getJSONObject(TAG_DEP);
String dtime = dep.getString(TAG_DEP_TIME);
//String dlat = dep.getString(TAG_DEP_LAT);
//String dlon = dep.getString(TAG_DEP_LON);
dlat = dep.getString(TAG_DEP_LAT);
dlon = dep.getString(TAG_DEP_LON);
// replace : and last 2 0's from departure time
dtime = dtime.replaceAll(":","");
//dtime.replaceAll(";","");
dtime = dtime.substring(0,dtime.length()-2);
// arrival node is JSON Object
JSONObject arr = c.getJSONObject(TAG_ARR);
String alt = arr.getString(TAG_ARR_LAT);
String aln = arr.getString(TAG_ARR_LON);
// convert data positions to doubles for Google Maps + stuff
double brng = Double.parseDouble(bearing);
brng = brng * Math.PI / 180;
double speed = Double.parseDouble(spd);
//double brng = Double.parseDouble(bearing);
double dLatitude = Double.parseDouble(dlat);
double dLongitude = Double.parseDouble(dlon);
double aLatitude = Double.parseDouble(alt);
double aLongitude = Double.parseDouble(aln);
double cLatitude = Double.parseDouble(dlat);
double cLongitude = Double.parseDouble(dlon);
double dtme = Double.parseDouble(dtime);
// tmp hashmap for single contact
HashMap<String, Double> contact = new HashMap<String, Double>();
contact.put("bearing", brng);
contact.put("speed", speed);
contact.put("time", dtme);
contact.put("alat", aLatitude);
contact.put("alon", aLongitude);
contact.put("dlat", dLatitude);
contact.put("dlon", dLongitude);
contact.put("clat", cLatitude);
contact.put("clon", cLongitude);
// adding contact to contact list
contactList.add(contact);
if (i== data.length()){
wait = false;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
// spawns planes when json loaded
#Override
protected void onPostExecute(Void result) {
Timer();
t.start();
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// use plane api for latlon
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
//for (int i = 0; i < contactList.size() ; i++)
}}
}
and here is the error message:
02-26 21:53:42.031: E/AndroidRuntime(14970): FATAL EXCEPTION: Timer-0
02-26 21:53:42.031: E/AndroidRuntime(14970): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
02-26 21:53:42.031: E/AndroidRuntime(14970): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
02-26 21:53:42.031: E/AndroidRuntime(14970): at java.util.ArrayList.get(ArrayList.java:308)
02-26 21:53:42.031: E/AndroidRuntime(14970): at com.fly.plane.MyMapActivity$CreateMarker.run(MyMapActivity.java:395)
02-26 21:53:42.031: E/AndroidRuntime(14970): at java.util.Timer$TimerImpl.run(Timer.java:284)
i understand that the markers.get(i) is causing the problem, but i dont know how to check if the markers array is null without it throwing this error.
Any help would be appreciated.
You can use Map<Integer, Marker> (Integer are keys and Marker are values). Then you can leverage Map.get() which don't throws Exception if key is Integer and not null (your i will not be null in your code).
Declare markers as Map:
Map<Integer, Marker> markers = new HashMap<Integer, Marker>();
Inside CreateMarker.run() after final LatLng position = new LatLng(crLat,crLon); change as follows:
//implicit boxing to use int in Map
Integer ii = Integer.valueOf(i);
//try to get marker by index from map (index is the key)
Marker markerByIndex = markers.get(ii);
//Map.get() returns null if object by specified key is not in map
if (markerByIndex == null){
//marker doesn't exists - create it, add to Google Map and to Map by key
timm += 1;
runOnUiThread(new Runnable() {
#Override
public void run() {
final Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(depLat, depLon))
.title("Hello world")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));
//put marker to map using i as a key
markers.put(ii, marker);
}
});
} else {
//marker exists, mutate it
markerByIndex.setPosition(position);
markerByIndex.setVisible(false);
//...replace the marker in map
markers.put(ii, markerByIndex);
//animate the marker
animateMarker(markerByIndex, position , true, spd);
}
You wrote:
i understand that the markers.get(i) is causing the problem, but i dont know how to check if the markers array is null without it throwing this error.
==> you can check it this way:
if (markers != null && markers.size() > 0) {
//there are actually markers. Calling markers.get(i) should work!
//...as long as i is smaller than markers.size()
} else {
//sorry, no markers! Don't call markers.get(i) here...
}

Android - Calculate Distance Using Haversine Formula (Using GPS , Lat and Long)

I need some help :) I am assign with a project to come out with the distance / speed and time. I have already come out with the Timer. However, the distance is giving me some problem. The distance does not changed at all from I travel from one place to another.
//GPS
private static Double EARTH_RADIUS = 6371.00; // Radius in Kilometers default
private static final String DEBUG_TAG = "GPS";
private String[] location;
private double[] coordinates;
private double[] gpsOrg;
private double[] gpsEnd;
private LocationManager lm;
private LocationListener locationListener;
private double totalDistanceTravel;
private boolean mPreviewRunning;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waterspill);
/*getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);*/
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
distanceCal=new LocationUtil(EARTH_RADIUS);
totalDistanceTravel=0;
// ---Additional---
//mapView = (MapView) findViewById(R.id.mapview1);
//mc = mapView.getController();
// ----------------
txtTimer = (TextView) findViewById(R.id.Timer);
gpsOnOff = (TextView) findViewById(R.id.gpsOnOff);
disTrav = (TextView) findViewById(R.id.disTrav);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(startButtonClickListener);
stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(stopButtonClickListener);
testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(testButtonClickListener);
startButton.setEnabled(false);
stopButton.setEnabled(false);
getLocation();
}
public void getLocation()
{
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0,locationListener);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,locationListener);
}
private OnClickListener startButtonClickListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
gpsOrg=coordinates;
totalDistanceTravel=0;
Toast.makeText(getBaseContext(),
"Start Location locked : Lat: " + gpsOrg[0] +
" Lng: " + gpsOrg[1],
Toast.LENGTH_SHORT).show();
if (!isTimerStarted)
{
startTimer();
isTimerStarted = true;
}
stopButton.setEnabled(true);
}
};
private OnClickListener stopButtonClickListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
gpsEnd=coordinates;
//gpsEnd = new double[2];
//gpsEnd[0]=1.457899;
//gpsEnd[1]=103.828659;
Toast.makeText(getBaseContext(),
"End Location locked : Lat: " + gpsEnd[0] +
" Lng: " + gpsEnd[1],
Toast.LENGTH_SHORT).show();
double d = distFrom(gpsOrg[0],gpsOrg[1],gpsEnd[0],gpsEnd[1]);
totalDistanceTravel+=d;
disTrav.setText(Double.toString(d));
}
};
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = EARTH_RADIUS;
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;
return new Float(dist).floatValue();
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
if(coordinates!=null)
{
double[] coordinatesPrev=coordinates;
double d = distFrom(coordinatesPrev[0],coordinatesPrev[1],coordinates[0],coordinates[1]);
totalDistanceTravel+=d;
}
else
{
coordinates = getGPS();
}
startButton.setEnabled(true);
}
private double[] getGPS() {
List<String> providers = lm.getProviders(true);
double[] gps = new double[2];
//Loop over the array backwards, and if you get an accurate location, then break out the loop
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
String s = providers.get(i);
Log.d("LocServ",String.format("provider (%d) is %s",i,s));
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
Log.d("LocServ",String.format("Lat %f, Long %f accuracy=%f",gps[0],gps[1],l.getAccuracy()));
gpsOnOff.setText("On");
}
}
return gps;
}
Is there anything wrong with my codes. Please advice and Thanks a lot for your help :)
Test your formula with this: The distance between {-73.995008, 40.752842}, and {-73.994905, 40.752798} should be 0.011532248670891638 km.

Categories

Resources