Get LatLon from current Position to Marker - android

i try to put a Polyline on my Map from the current Location to a Marker.
If i put the Lat und Longitude directly in the code, the Polyline is drawing.
But if i try to take the Lat and Lon from the Locationlistener, it doesnt work and the googlemaps link looks like this: http://maps.googleapis.com/maps/api/directions/xml?origin=0.0, 0.0&destination=0.0, 0.0...
here is the code:
private GoogleMap myMap;
private final long zero = 0;
private HashMap<String, Spot> spots = null;
private Dialog dialog;
private double sourceLatitude;
private double sourceLongitude;
private double destLatitude;
private double destLongitude;
Button buttonRequest;
GoogleDirection gd;
Document mDoc;
LatLng start = new LatLng(sourceLatitude, sourceLongitude);
LatLng end = new LatLng(destLatitude, destLongitude);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.karte);
Dialog b = new Dialog(this);
dialog = b;
SupportMapFragment mySupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
myMap = mySupportMapFragment.getMap();
myMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
myMap.setMyLocationEnabled(true);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 0,
mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 0,
mlocListener);
SharedPreferences settings = getSharedPreferences("cityhallprefs", 0);
moveCamera(Double.longBitsToDouble(settings.getLong("camlat", zero)),
Double.longBitsToDouble(settings.getLong("camlng", zero)));
gd = new GoogleDirection(this);
gd.setOnDirectionResponseListener(new OnDirectionResponseListener() {
public void onResponse(String status, Document doc, GoogleDirection gd) {
mDoc = doc;
myMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
myMap.addMarker(new MarkerOptions().position(start)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
myMap.addMarker(new MarkerOptions().position(end)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
}
});
buttonRequest = (Button)findViewById(R.id.routereq);
buttonRequest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setVisibility(View.GONE);
gd.setLogging(true);
gd.request(start, end, GoogleDirection.MODE_DRIVING);
}
});
new QuerySpotsOperation().execute("");
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences settings = getSharedPreferences("cityhallprefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("camlat", Double.doubleToLongBits(myMap.getCameraPosition().target.latitude));
editor.putLong("camlng", Double.doubleToLongBits(myMap.getCameraPosition().target.longitude));
editor.commit();
}
private void moveCamera(double latit, double longit) {
if(latit!= 0 || longit != 0) {
LatLng coordinate = new LatLng(latit, longit);
CameraUpdate updt = CameraUpdateFactory.newLatLngZoom(coordinate, 6);
myMap.animateCamera(updt);
}
}
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
sourceLatitude = loc.getLatitude();
sourceLongitude = loc.getLongitude();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
to get the Lat Lon of the marker who was clicked:
#Override
public View getInfoWindow(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.infowindow,null);
Spot markerSpot = spots.get(arg0.getPosition().toString());
double Lat = markerSpot.getLatitude();
double Lon = markerSpot.getLongitude();
destLatitude = Lat;
destLongitude = Lon;
return v;
} else {
return null;
}
"LatLng start" and "LatLng end" are everytime 0 if i try to get it with sourceLatitude, sourceLongitude.
i hope anyone can help me to solve the problem and sorry for my bad english :)

You can get your current location LatLon:
....
myMap.setMyLocationEnabled(true);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = mlocManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = mlocManager.getLastKnownLocation(provider);
//get Lat Lon
Double lat = myLocation.getLatitude();
Double lon = myLocation.getLongitude();
....

i found a solution for my problem.
i set LatLng start and LatLng end in onResponse and onClick and now it works :)
gd = new GoogleDirection(this);
gd.setOnDirectionResponseListener(new OnDirectionResponseListener() {
public void onResponse(String status, Document doc, GoogleDirection gd) {
LatLng start = new LatLng(sourceLatitude, sourceLongitude);
LatLng end = new LatLng(destLatitude, destLongitude);
mDoc = doc;
myMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
myMap.addMarker(new MarkerOptions().position(start)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
myMap.addMarker(new MarkerOptions().position(end)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
}
});
buttonRequest = (Button)findViewById(R.id.routereq);
buttonRequest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LatLng start = new LatLng(sourceLatitude, sourceLongitude);
LatLng end = new LatLng(destLatitude, destLongitude);
v.setVisibility(View.GONE);
gd.setLogging(true);
gd.request(start, end, GoogleDirection.MODE_DRIVING);
}
});

Related

showing google maps on android wear devices

I have developed an app to show ATM machines in your area. It works on my android phone but when I try to launch it on my android wearable watch it crashes. With the error "Binary XML File line #2 Error inflating class fragment" Any help is much appreciated.
Here is my xml code
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"/>
and my activity:
public class MainActivity extends Activity {
private final String TAG = getClass().getSimpleName();
private GoogleMap mMap;
private String[] places;
private LocationManager locationManager;
private Location loc;
SharedPreferences sp;
static String distance;
public static final String PREF = "MyPrefs";
public static final String DISTANCE = "distance";
#Override
public void onResume() {
super.onResume();
sp = this.getSharedPreferences(PREF, Context.MODE_PRIVATE);
distance = sp.getString(DISTANCE, "1000");
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
currentLocation();
places=new String[1];
places[0]="ATM";
mMap.setMyLocationEnabled(true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private class GetPlaces extends AsyncTask<Void, Void, ArrayList<Place>> {
private ProgressDialog dialog;
private Context context;
private String places;
private double longitude;
private double latitude;
public GetPlaces(Context context, String places) {
this.context = context;
this.places = places;
}
#Override
protected void onPostExecute(ArrayList<Place> result) {
super.onPostExecute(result);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
if (dialog.isShowing()) {
dialog.dismiss();
}
for (int i = 0; i < result.size(); i++) {
mMap.addMarker(new MarkerOptions()
.title(result.get(i).getName())
.position(
new LatLng(result.get(i).getLatitude(), result
.get(i).getLongitude()))
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.pin))
.snippet(result.get(i).getVicinity()));
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)) // Sets the center of the map to
// Mountain View
.zoom(14) // Sets the zoom
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
#Override
protected ArrayList<Place> doInBackground(Void... arg0) {
PlacesService service = new PlacesService(
"xxxxxxxxxxxxx");
ArrayList<Place> findPlaces = service.findPlaces(loc.getLatitude(),
loc.getLongitude(), places, distance);
for (int i = 0; i < findPlaces.size(); i++) {
Place placeDetail = findPlaces.get(i);
Log.e(TAG, "places : " + placeDetail.getName());
}
return findPlaces;
}
}
private void currentLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager
.getBestProvider(new Criteria(), false);
Location location = locationManager.getLastKnownLocation(provider);
if (location == null) {
locationManager.requestLocationUpdates(provider, 0, 0, listener);
} else {
loc = location;
new GetPlaces(MainActivity.this, places[0].toLowerCase().replace(
"-", "_")).execute();
Log.e(TAG, "location : " + location);
}
}
private LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "location update : " + location);
loc = location;
locationManager.removeUpdates(listener);
}
};
}
Unfortunately, MapFragment and GoogleMap (along with the entirely of the Google Maps Android API) is currently not supported on Android Wear devices.

wrong location on Google Map. cannot retrieve correct distance to next Activity

My android app is to track user location on a map and calculate the distance and duration he has walked or run. Then when i press stop, pass it over to the next page.
My distance and duration calculation should be correct, but the location is wrong. whether i don't move or move a few meters in my house, it sometimes never change or change a lot, result in the distance being inaccurate. how do i ensure accuracy for when i walked, even a few meters, because when i present i will be walking for a short distance.
second, i can pass my duration data over to the next page, but when i pass my distance it is 0.0 but the value shown is not 0.0 at all(got value although inaccurate). i pass my information when i press Stop button.
My MainActivity Java Code, display map, distance, duration.
protected LocationManager locationManager;
private GoogleMap googleMap;
Button btnStartMove,btnPause,btnResume,btnStop;
static double n=0;
Long s1,r1;
double dis=0.0;
Thread t1;
EditText userNumberInput;
boolean bool=false;
int count=0;
double speed = 1.6;
double lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4;
double dist = 0.0;
double time = 0.0;
TextView distance;
Button btnDuration;
float[] result;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES =1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 4000; //in milliseconds
boolean startDistance = false;
boolean startButtonClicked = false;
MyCount counter;
int timer = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
if(isGooglePlay())
{
setUpMapIfNeeded();
}
distance=(TextView)findViewById(R.id.Distance);
btnDuration=(Button)findViewById(R.id.Duration);
btnStartMove=(Button)findViewById(R.id.Start);//start moving
btnStop=(Button)findViewById(R.id.Stop);
//prepare distance...........
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
btnStartMove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
lat3 = location.getLatitude();
lon3 = location.getLongitude();
startButtonClicked=true;
startDistance=true;
counter= new MyCount(30000,1000);
counter.start();
Toast.makeText(MainActivity.this,
"Pressed Start",
Toast.LENGTH_LONG).show();
}
});
btnStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
startButtonClicked=false;
startDistance=false;
//Double.valueOf(distance.getText().toString()
Double value=dist;
Double durationValue=time;
Intent intent = new Intent(MainActivity.this, FinishActivity.class);
intent.putExtra("dist", "value");
intent.putExtra("time",durationValue);
startActivity(intent);
finish();
}
});
btnDuration.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(startButtonClicked=true)
{
time=n*30+r1;
Toast.makeText(MainActivity.this,"Duration :"+String.valueOf(time),Toast.LENGTH_LONG).show();
}
}
});
if(location!= null)
{
//Display current location in Toast
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
}
else if(location == null)
{
Toast.makeText(MainActivity.this,
"Location is null",
Toast.LENGTH_LONG).show();
}
}
private void setUpMapIfNeeded() {
if(googleMap == null)
{
Toast.makeText(MainActivity.this, "Getting map",
Toast.LENGTH_LONG).show();
googleMap =((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.displayMap)).getMap();
if(googleMap != null)
{
setUpMap();
}
}
}
private void setUpMap()
{
//Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
//Get locationManager object from System Service LOCATION_SERVICE
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
if(provider == null)
{
onProviderDisabled(provider);
}
//set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Get current location
Location myLocation = locationManager.getLastKnownLocation(provider);
if(myLocation != null)
{
onLocationChanged(myLocation);
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
private boolean isGooglePlay()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS)
{
Toast.makeText(MainActivity.this, "Google Play Services is available",
Toast.LENGTH_LONG).show();
return(true);
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
}
return (false);
}
#Override
public void onLocationChanged(Location myLocation) {
System.out.println("speed " + myLocation.getSpeed());
//show location on map.................
//Get latitude of the current location
double latitude = myLocation.getLatitude();
//Get longitude of the current location
double longitude = myLocation.getLongitude();
//Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
//show distance............................
if(startDistance == true)
{
Toast.makeText(MainActivity.this,
"Location has changed",
Toast.LENGTH_LONG).show();
if(myLocation != null)
{
//latitude.setText("Current Latitude: " + String.valueOf(loc2.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(loc2.getLongitude()));
float[] results = new float[1];
Location.distanceBetween(lat3, lon3, myLocation.getLatitude(), myLocation.getLongitude(), results);
System.out.println("Distance is: " + results[0]);
dist += results[0];
DecimalFormat df = new DecimalFormat("#.##"); // adjust this as appropriate
if(count==1)
{
distance.setText(df.format(dist) + "meters");
}
lat3=myLocation.getLatitude();
lon3=myLocation.getLongitude();
count=1;
}
}
if(startButtonClicked == true)
{
startDistance=true;
}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
counter= new MyCount(30000,1000);
counter.start();
n=n+1;
}
#Override
public void onTick(long millisUntilFinished) {
s1=millisUntilFinished;
r1=(30000-s1)/1000;
}
}}
pass information to this page,distance 0.0(inaccurate) duration is ok
public class FinishActivity extends Activity {
TextView displayDistance;
TextView displayDuration;
TextView displaySports;
TextView userID;
TextView sportID;
TextView caloriesBurned;
Button back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finish);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
Double value = extras.getDouble("dist");
Double durationValue = extras.getDouble("time");
displayDistance=(TextView)findViewById(R.id.finishDistance);
displayDistance.setText("Distance: " + value);
displayDuration=(TextView)findViewById(R.id.finishDuration);
displayDuration.setText("Duration: " + durationValue + " seconds");
}
back=(Button)findViewById(R.id.Back);
back.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent(FinishActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});}
My output for my map, inaccurate location. i search for long but there seem to be no solution for this..please help..thanks. the starting location, speed where it change location, all seem to be different each time i run. it appear to be out of my control(or i can but i do not know..i'm a beginner at gps... most of the time it needs to wait a while before displaying the distance.
Gps may not work well under the roof. So try it outside the house.
Also you have
intent.putExtra("dist", "value")
key is dist
value is a string not a double
SO you are passing string
But when you get you get the double
Double value = extras.getDouble("dist"); // wrong
If you pass a double value then you can get the double in the next activity. But you pass string and then you try to get the double value and that is wrong.
What you need
public Intent putExtra (String name, double value)
and
public double getDoubleExtra (String name, double defaultValue)

android gps distance shows previous record while restart

I have an android application which calculate distance from GPS while walking. First time distance calculation correct. But when I restart application, it shows the previous distance initially, it should be 0.
Here is my activity:
public class Gps extends Activity {
TextView display;
Button start;
boolean doubleclick = false;
AnimationDrawable AppNameAnimation;
private boolean enabled;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance;
Animation animRotate;
TextView startStop;
LocationManager lm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_test);
startStop = (TextView) findViewById(R.id.textView2);
display = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
animRotate = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!doubleclick) {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
enabled = lm
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
}
} else {
lm.removeUpdates(Loclist);
startStop.setText("Start");
v.clearAnimation();
doubleclick = false;
Intent in = new Intent(Gps.this, NextActivity.class);
// in.putExtra("distance", display.toString());
startActivity(in);
finish();
}
}
});
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
// Get last location
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// Request new location
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
if (lastLat != 0 || lastLon != 0) {
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km", distanceKm));
Constant.distance = (String.format("%.2f Km", distanceKm));
start.startAnimation(animRotate);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}
Please help me. It is very important to me.
Edited Code
public class Gps extends Activity {
TextView display;
Button start;
boolean doubleclick = false;
AnimationDrawable AppNameAnimation;
private boolean enabled;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance;
Animation animRotate;
TextView startStop;
LocationManager lm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_test);
startStop = (TextView) findViewById(R.id.textView2);
display = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
animRotate = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!doubleclick) {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
enabled = lm
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
Log.e("successss", "111111111111");
}
} else {
lm.removeUpdates(Loclist);
startStop.setText("Start");
v.clearAnimation();
doubleclick = false;
Intent in = new Intent(Gps.this, NextActivity.class);
// in.putExtra("distance", display.toString());
startActivity(in);
finish();
}
}
});
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("successss", "2222222222222");
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get last location
if(!doubleclick){
Location loc1 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
Log.e("successss", "33333333333333333");
if (loc1 == null) {
display.setText("No GPS location found");
} else {
Log.e("successss", "444444444444");
// set Current latitude and longitude
currentLon = loc1.getLongitude();
currentLat = loc1.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
Log.e("successss", "5555555555555");
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
}
Log.e("successss", "66666666666");
Log.e("Location", "lastLat:" + lastLat);
Log.e("Location", "currentLat:" + currentLat);
//Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// Request new location
//lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// get the current lat and long
currentLat = loc2.getLatitude();
currentLon = loc2.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
if (lastLat != 0 || lastLon != 0) {
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km", distanceKm));
Constant.distance = (String.format("%.2f Km", distanceKm));
start.startAnimation(animRotate);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}
Because you use:
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
set it to null if you want to wait for actual position. then start your jobs from OnLocationChangedListener
that method retreives the last position of the user... GPS takes some time to get the actual position.
EDIT
remove this code from the else:
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
and just wait for the position instead..display a toast for example, telling the user that you are waiting for the position.
then, when you have the position, do this stuff in the
public void onLocationChanged(Location location) {}
method..
I don't know what you're code exactly do...I'm just trying to explain you how I would to this..you have to wait and don't start your operations at the creation of the view, but you have to start everything when you have the position
when you restart your app, it takes some time for the GPS to get the new location coordinates.
in your code you have this
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
so, loc is having the lastKnownLocationValues from the last run and hence displaying them.
if you dont want to display the last known location values, assign loc = null on every restart, but then it will take some time to fetch the first location.
this peculiar behavior is implemented because generally it may happen that your GPS connectivity is lost for a few moments, in that short span you don't want to show the user that the location is null or could not be found, because probably in this small span they haven't travelled too far, and so you display the last known location instead.
EDIT:
remove this code from your else
and do this is your locationListener
instead of
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
}
change to
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
display.setText("searching for location...");
}
and then update your textboxes in your locationListener's onLocationChanged() method
EDIT:
declare two more variables and a flag
private boolean enabled;
double currentLon = 0;
double currentLat = 0;
double prevLon = 0;
double prevLat = 0;
bool firstTime = true;
in your onLocationChanged()
public void onLocationChanged(Location location) {
if(!firstTime){
prevLon = currentLon;
prevLat = currentLat;
currentLat = location.getLatitude();
currentLon = location.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(prevLat);
locationA.setLongitude(prevLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
...
}
else{
firstTime = false;
currentLat = location.getLatitude();
currentLon = location.getLongitude();
}
}

Android GPS: measured distance between locations continiously

I want to create an application of distance tracker in android. I have a Spinner, button and a TextView.Initially text view will be 0.00km.When I click the button (GPS tracking start) and start walking in the text view it will show the distance continuously. When I click the button again(GPS tracking terminate) and show the full distance between clicking button.
Here is the screenshot that the application will look like:
Here is My Code:
public class Gps extends Activity {
TextView display;
double currentLon=0 ;
double currentLat=0 ;
double lastLon = 0;
double lastLat = 0;
double distance;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
display = (TextView) findViewById(R.id.textView1);
LocationManager lm =(LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if(loc==null){
display.setText("No GPS location found");
}
else{
//set Current latitude and longitude
currentLon=loc.getLongitude();
currentLat=loc.getLatitude();
}
//Set the last latitude and longitude
lastLat=currentLat;
lastLon=currentLon ;
}
LocationListener Loclist = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//start location manager
LocationManager lm =(LocationManager) getSystemService(LOCATION_SERVICE);
//Get last location
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
//Request new location
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
//Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
//get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km",distanceKm ));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}
Please help me. Thanks.
You should register a listener on the GPS when the location changed. You basically have to store the previous known location and compare it with the new one.
The simplest way to get the distance between two points would be to use:
sqrt( (x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2 )
X may be the latitude
Y may be the longitude
Z may be the altitude
Here is a pseudo code sample to help you
public class GpsCalculator
{
private LocationManager locationManager = null;
private Location previousLocation = null;
private double totalDistance = 0D;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 100; // 100 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minutes
public void run(Context context)
{
// Get the location manager
locationManager = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
// Add new listeners with the given params
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); // Network location
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); // Gps location
}
public void stop()
{
locationManager.removeUpdates(locationListener);
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location newLocation)
{
if (previousLocation != null)
{
double latitude = newLocation.getLatitude() + previousLocation.getLatitude();
latitude *= latitude;
double longitude = newLocation.getLongitude() + previousLocation.getLongitude();
longitude *= longitude;
double altitude = newLocation.getAltitude() + previousLocation.getAltitude();
altitude *= altitude;
GpsCalculator.this.totalDistance += Math.sqrt(latitude + longitude + altitude);
}
// Update stored location
GpsCalculator.this.previousLocation = newLocation;
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
}
And the Activty should look like that:
public class MainActivity extends Activity
{
private Button mainButton = null;
private boolean isButtonPressed = false;
private GpsCalculator gpsCalculator = null;
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
// Create a new GpsCalculator instance
this.gpsCalculator = new GpsCalculator();
// Get your layout + buttons
this.mainButton = (Button) findViewById(R.id.main_button);
this.mainButton.addOnClickListener(new OnClickListener() {
#Override
public void onClick()
{
// Enable or diable gps
if (MainActivity.this.isButtonPressed) gpsCalculator.run(this);
else gpsCalculator.stop();
// Change button state
MainActivity.this.isButtonPressed = !MainActivity.this.isButtonPressed;
}
});
}
}

move marker on google maps api 2

How do I move marker on Google maps api V2 ? I am using below code but it does not move marker on the map. What am I doing wrong here ? This should work when location changes, so I have added onLocationChanged method and in that, am getting location details and trying to move marker on new details, but this doesn't work.
Here is my code:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
public class MapViewActivity extends Activity implements LocationListener,
SensorEventListener, OnClickListener {
GoogleMap googleMap;
private boolean started = false;
private ArrayList<AccelLocData> sensorData;
private SensorManager sensorManager;
private Button btnStart, btnStop;
private String provider;
// File root, dir, sensorFile;
FileOutputStream fOut;
private Sensor mAccelerometer;
private FileWriter writer;
private DatabaseHelper databaseHelper;
private BroadcastReceiver alarmReceiver;
private PendingIntent pendingIntentSender, pendingIntentReceiver;
private AlarmManager alarmManager;
private Intent alarmIntent,alarmIntent2;
// private Button btnUpload;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
databaseHelper = new DatabaseHelper(this);
databaseHelper.removeAll();
Log.v("datacount",
Integer.toString(databaseHelper.getLocDataCount()));
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services
// are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
this, requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment of
// activity_main.xml
// SupportMapFragment supportMapFragment = (MapFragment)
// getFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// can use for overlay on the map
List<Double> latList = new ArrayList<Double>();
latList.add(145.7309593);
latList.add(146.34);
latList.add(147.34);
List<Double> lonList = new ArrayList<Double>();
lonList.add(-122.6365384);
lonList.add(-123.6365384);
lonList.add(-124.6365384);
for (int i = 0; i < 3; i++) {
// LatLng latLng = new LatLng(45.7309593, -122.6365384);
LatLng latLng = new LatLng(latList.get(i).doubleValue(),
lonList.get(i).doubleValue());
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap
.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager
.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager
.requestLocationUpdates(provider, 20000, 0, this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onSensorChanged(SensorEvent event) {
if (started) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
long timestamp = System.currentTimeMillis();
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locManager.getBestProvider(criteria, true);
Location location = locManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
AccelLocData accelLocData = new AccelLocData(timestamp, x, y, z,
latitude, longitude);
// Log.d("X data","data x:" + data.getX());
try {
// writer.write(data.toString());
if (databaseHelper != null)
databaseHelper.insertLocData(accelLocData);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
Context context = getApplicationContext();
alarmIntent = new Intent(context, AccelLocSender.class);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
pendingIntentSender = PendingIntent.getBroadcast(context, 0,
alarmIntent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 60000, pendingIntentSender);
alarmIntent2 = new Intent(context, AccelLocReceiver.class);
pendingIntentReceiver = PendingIntent.getBroadcast(context, 0,
alarmIntent2, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 30000, pendingIntentReceiver);
btnStart.setEnabled(false);
btnStop.setEnabled(true);
Log.d("startbutton", "cam on click of start");
started = true;
// delete all files..
// start thread to send data
sensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_FASTEST);
break;
case R.id.btnStop:
try {
btnStart.setEnabled(true);
btnStop.setEnabled(false);
// btnUpload.setEnabled(true);
started = false;
sensorManager.unregisterListener(this);
Context context1 = getApplicationContext();
AlarmManager alarmManager1 = (AlarmManager) context1
.getSystemService(Context.ALARM_SERVICE);
alarmManager1.cancel(pendingIntentSender);
alarmManager1.cancel(pendingIntentReceiver);
// System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
protected void onPause() {
super.onPause();
/*
* if (writer != null) { try { writer.close(); } catch (IOException e) {
* // TODO Auto-generated catch block e.printStackTrace(); } }
*/
}
protected void onResume() {
super.onResume();
/*
* try { Log.d("onresume","called onresume"); writer = new
* FileWriter(sensorFile, true); } catch (IOException e) { // TODO
* Auto-generated catch block e.printStackTrace(); }
*/
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
}
Make variable
Marker now;
in this part add Marker and remove marker, of course put in the rest of your marker attributes:
#Override
public void onLocationChanged(Location location) {
if(now != null){
now.remove();
}
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
now = googleMap.addMarker(new MarkerOptions().position(latLng)));
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
Make the marker draggable using,
MarkerOptions markerOptions = new MarkerOptions().position(myLaLn).title(
"Current Location").draggable(true);
map.addMarker(markerOptions);
& Get the dragged position & details as follows,
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
Log.d(TAG, "latitude : "+ marker.getPosition().latitude);
marker.setSnippet(marker.getPosition().latitude);
map.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()));
}
#Override
public void onMarkerDrag(Marker marker) {
}
});
Optimized way to move marker :
marker mMarker;
After adding marker to map. while change the location you just need to set position rather than remove marker and add again.
mMarker.setPosition(new LatLon(latLng));
this will reduce the code from remove and add marker to direct set position and also reduce complexity. :)
Enjoy.
You are just moving camera on location change where as you should add marker as well then it will draw marker on current location. and before adding marker clear all the previous markers by calling googlmap.clear();
addMarker returns a reference to the marker which then later can be updated
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if(mMarker == null) {
mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
} else {
mMarker.setPosition(latLng);
}
}
});

Categories

Resources