I have an app which calculates distance and speed by gps
the speed is working well
but the distance always equals to zero !!
at first i didn't initialize float[] dist by zero .. but it crashed once gps was found !
that's the code
public class Main_Activity extends Activity {
TextView tvdistance;
TextView tvSpeed;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance = 0;
float[] dist = {
0, 0, 0
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
tvdistance = (TextView) findViewById(R.id.tvdistance);
tvSpeed = (TextView) findViewById(R.id.tvspeed1);
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc == null) {
tvdistance.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(LocationManager.GPS_PROVIDER);
// Request new location
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
if (currentLat != 0 && currentLon != 0) {
Location.distanceBetween(currentLat, currentLon, location.getLatitude(),
location.getLongitude(), dist);
distance += (long) dist[0];
}
currentLat = location.getLatitude();
currentLon = location.getLongitude();
float speed = location.getSpeed();
tvSpeed.setText("Speed = " + speed / 1000 * 60 * 60 + "Km/h");
tvdistance.setText("Distance = " + distance);
}
#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
}
};
}
As you have just gotten a location fix, I fully expect the location returned from getLastKnownLocation to be the same as what you get in location. This means that your distance between the two is correctly 0. If you want your older location, you'll need to store that yourself.
Here is the complete code to get location updates from a GPS provider
public class MainActivity extends Activity {
private GoogleMap googleMap;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1
// meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000; // 1
// second
// Declaring a Location Manager
protected LocationManager locationManager;
// The alert dialog to enable GPS
private Dialog alertDialog;
// flag for GPS status
boolean isGPSEnabled = false;
Location location; // location
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onStart()
*/
#Override
protected void onStart() {
// fetching your current location
super.onStart();
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
if (googleMap != null) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
}
// Getting current location and adding the marker
locateMe();
}
/**
*
*/
private void locateMe() {
// Checking for GPS Enabled
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
// GPS is disabled
askUserToEnableGPS();
}
}
/**
*
*/
private void askUserToEnableGPS() {
// Asking user to enable GPS
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog
// characteristics
builder.setMessage(R.string.generic_gps_not_found)
.setTitle(R.string.generic_gps_not_found_message_title)
.setPositiveButton(R.string.generic_yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected yes
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(R.string.generic_no,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected no
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onResume()
*/
#Override
protected void onResume() {
// Getting location from GPS
super.onResume();
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);
Log.e("GPS Enabled", "GPS Enabled");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// Setting the marker
if (googleMap == null || location == null) {
return;
} else {
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
location.getLatitude(), location.getLongitude())));
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 3000ms
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
}, 1000);
Marker myLocation = googleMap.addMarker(new MarkerOptions()
.position(
new LatLng(location.getLatitude(), location
.getLongitude()))
.title("Me")
.snippet("I am here")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
}
locationManager.removeUpdates(listener);
locationManager = null;
}
};
}
Now you can use various methods to store your location. Following are some ways:
Shared preferences
SQLite Database
Web Server
Saving in a file
You can refer this link.
Related
I am calling toast message in AndroidGPSTrackingActivity.class. how to fetch geo locations after every 1 minutes.. With below code I am getting only once
public class AndroidGPSTrackingActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText( getApplicationContext(),"Your Locion is - \nLat: " + latitude
+ "\nLog: " + longitude, Toast.LENGTH_LONG).show();
System.out.println("respmaillati::;;"+latitude);
} else {
gps.showSettingsAlert();
}
}
in manifest I given
<service android:name=".GPSTracker" />
Code:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 100 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
System.out.println("responsel:::"+latitude);
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
System.out.println("responsel:::"+longitude);
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Try this!
Wrap the toast code in a method and call it recursively using Handler and Runnable:
public class AndroidGPSTrackingActivity extends Activity {
Handler showLocationHandler;
Runnable showLocationRunnable;
private static final int DELAY_TIME = 1000 * 60; //delay time - 1 minute
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
showLocationHandler = new Handler();
showLocationRunnable = new Runnable() {
#Override
public void run() {
showLatLongToast();
}
};
//call the method once
showLatLongToast();
}
public void showLatLongToast() {
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Locion is - \nLat: " + latitude
+ "\nLog: " + longitude, Toast.LENGTH_LONG).show();
System.out.println("respmaillati::;;" + latitude);
} else {
gps.showSettingsAlert();
}
//call the same method after some delay
showLocationHandler.postDelayed(showLocationRunnable, DELAY_TIME);
}
#Override
protected void onDestroy() {
super.onDestroy();
//kill this runnable when ever you want to stop displaying toast like this
showLocationHandler.removeCallbacks(showLocationRunnable);
}
}
I am just beginning to learn android, but could not get proper idea, how to handle this, so I want to store every 2 minute location coordinate if i travel in bus.
What i am using:
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
TextView tv;
ArrayList<String> cordsList= new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=new TextView(this);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnShowLocation.setText("Start Save Location");
Log.i("Finall", "AndroidGPSTrackingActivity-> ");
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String longlat=String.valueOf(latitude)+":"+String.valueOf(longitude);
cordsList.add(longlat);
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
Log.i("Finall", "Location-> "+cordsList.toString());
}
});
}
I am getting on time but could not get every 30 and where to store.
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 2; // 2 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10000, // 3 sec
10, this);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("location", "->longitude>> "+longitude);
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("location", "latitude->longitude>> "+latitude);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
Log.i("latitude", "latitude-> "+latitude);
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
Log.i("longitude", "longitude-> "+latitude);
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
Log.i("onLocationChanged", "onLocationChanged-> "+latitude+"---- "+longitude);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("onStatusChanged", "onLocationChanged-> "+latitude+"---- "+longitude);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Hello , every body, any idea, If i travel bus and my gps on then i travel 20 minute, then i want to save 10 co-ordinate in arrays. Any idea, how to do this. and stop after clicking STOP button.
Thanks in Adavance.
You are can use the Timer class in android which will give you the TIME_INTERVAL to call that class .In your case you can give the TIME_INTERVAL = 20000
Here is my example code :
public class MainActivity extends Activity {
Timer timer = new Timer();
GpsTracker gpsTracker ;
ArrayList<Double> arrLat= new ArrayList<Double>();
ArrayList<Double> arrLng = new ArrayList<Double>();
private final int TIME_INTERVAL = 20000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpsTracker = new GPSTracker(this);
timer.scheduleAtFixedRate(new TimerTask() {
#SuppressLint("DefaultLocale")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void run() {
latitude = GPSTracker.getLatitude();
longitude = GPSTracker.getLongitude();
System.out.println("lat------ "+latitude);
System.out.println("lng-------- "+longitude);
arrLat.add(latitude);
arrLng.add(longitude);
}
}, 0, TIME_INTERVAL);
}
}
I am doing application, we are in inside the room or not. I have to stored 4 corner values means doing polygon. But i cant get exactly value in the same position, it gets different values in the same position. How it get solution this problem??
Code:
MainActivity.java
public class MainActivity extends Activity {
Button btnShowLocation;
TextView tvLat;
TextView tvLang;
TextView tvInsideRoom;
dbHandler myDbHelper;
// GPSTracker class
GPSTracker gps;
Handler mHandler1;
tvInsideRoom = (TextView)findViewById(R.id.insideRoom);
btnShow = (Button) findViewById(R.id.btnShow);
// show location button click event
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mHandler1 = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(100);
mHandler1.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// creating GPS Class object
GPSTracker gps = new GPSTracker (MainActivity.this);
// check if GPS location have some values
if (gps.canGetLocation()) {
double currentlat = gps.getLatitude();
double currentlong = gps.getLongitude();
tvLat = (TextView)findViewById(R.id.lat);
tvLang = (TextView)findViewById(R.id.lang);
tvLat.setText(""+currentlat);
tvLang.setText(""+currentlong);
boolean boolFlag = myDbHelper.isInsideRoom(currentlat,currentlong);
tvInsideRoom.setText("");
if(boolFlag)
tvInsideRoom.setText("You are in inside Room");
else
tvInsideRoom.setText(""+boolFlag);
} else {
// no current location
gps.showSettingsAlert();
}
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
}); }
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.d("Accuracy1 := ", ""+location.getAccuracy());
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.d("Accuracy2 := ", ""+location.getAccuracy());
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
this.location = location;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}}
The accuracy of location tracking can vary vastly. What you are trying to achieve will never work because of an insufficient accuracy. Especially inside a room, but even with GPS.
Depending on where you are, network cell-towers, wifi or GPS will be used to determine the current location, and all with a different accuracy. Even outside, it usually takes a few seconds until you get a GPS fix.
Use getAccuracy() to check if your location is somewhat useful with the current fix.
I'm trying to make a simple program to perform distance calculations that will be shown in listview. I use GPSTracker from androidhive, and calling latitude and longitude fo my List Activity
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled =false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context){
this.mContext = context;
getLocation();
}
public Location getLocation() {
try{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled&& !isNetworkEnabled){
//no network enable
}else {
this.canGetLocation = true;
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network","Network");
if(locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location == null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} catch (Exception e){
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And My List Activity
public class Mobil extends ListFragment implements LocationListener{
GPSTracker gps;
private static final String url = "http://10.0.2.2/tambalban/car.php";
JSONArray tambalban = null;
ArrayList<HashMap<String, String>> listMobil = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new getJSONData().execute();
}
public class getJSONData extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromURL(url);
gps = new GPSTracker(getActivity()); // is it right calling from GPSTracker?
double lat_user = gps.getLatitude(); // get latitude, right?
double lng_user = gps.getLongitude();
System.out.println("lat_user : "+lat_user+""); // print in logcat return 0.00
System.out.println("lng_user : "+lng_user+"");// print in logcat return 0.00
try {
tambalban = json.getJSONArray(TAG_TAMBALBAN);
for (int i = 0; i < tambalban.length(); i++) {
JSONObject mtr = tambalban.getJSONObject(i);
String id_tb = mtr.getString(TAG_ID);
String name_tb = mtr.getString(TAG_NAMA);
String address_tb = mtr.getString(TAG_ALAMAT);
String telp_tb = mtr.getString(TAG_TELP);
String lat = mtr.getString(TAG_LAT);
String lng = mtr.getString(TAG_LNG);
double lat_tujuan = Double.parseDouble(lat);
double lng_tujuan = Double.parseDouble(lng);
double distance = hitungJarak(lat_user, lng_user, lat_tujuan, lng_tujuan);
distance = RoundDecimal(distance, 2);
String dist = Double.toString(distance)+" km";
HashMap<String, String> a = new HashMap<String, String>();
a.put(TAG_ID, id_tb);
a.put(TAG_NAMA, name_tb);
a.put(TAG_ALAMAT, address_tb);
a.put(TAG_TELP, telp_tb);
a.put(TAG_LAT, lat);
a.put(TAG_LNG, lng);
a.put(TAG_JARAK, dist);
listMobil.add(a);
}
} catch (JSONException e) {
e.printStackTrace();
}
return listMobil;
}
private double RoundDecimal(double distance, int i) {
BigDecimal bd = new BigDecimal(distance);
bd = bd.setScale(i, 6);
return bd.doubleValue();
}
private double hitungJarak(double lat_user, double lng_user,
double lat_tujuan, double lng_tujuan) {
double dist;
double radius = 6371;
double dLat = Math.toRadians(lat_tujuan - lat_user);
double dLon = Math.toRadians(lng_tujuan- lng_user);
double a = Math.sin(dLat/2) * Math.sin(dLat /2)
+ Math.cos(Math.toRadians(lat_user)) * Math.cos(Math.toRadians(lat_tujuan))
* Math.sin(dLon/ 2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = radius * c;
double km = valueResult/1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
dist = radius * c;
return dist;
}
#Override
protected void onPostExecute(
ArrayList<HashMap<String, String>> listMobil) {
// TODO Auto-generated method stub
super.onPostExecute(listMobil);
ListAdapter adapter = new SimpleAdapter(getActivity(), listMobil,
R.layout.list_item, new String[] { TAG_NAMA, TAG_ALAMAT, TAG_JARAK },
new int[] { R.id.namatb, R.id.alamattb,R.id.jarak });
setListAdapter(adapter);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.list_fragment, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String pilih = getListAdapter().getItem(position).toString();
Toast.makeText(getActivity(),
pilih,
Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(), DetailDaftar.class);
Bundle bundle = new Bundle();
bundle.putString("Selected", pilih);
i.putExtras(bundle);
startActivity(i);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
I check using Sytem.out.println, both latitude and longitude return 0.00.
Am I wrong with calling current Location? Thanks you for any help.
You should create your GPSTracker gps object outside your AsyncTask try like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gps = new GPSTracker(getActivity()); // is it right calling from GPSTracker?
new getJSONData().execute();
}
And also add required permission into your manifest.xml file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
your GPSTracker class will return current location latitude and longitude. I have already checked and it is returning lat/long values.
In second part I am not getting, what you are trying to do with json but if you want to get latitude longitude in another activity then simply instantiate GPSTracker class like
Inside activity
GPSTracker tracker;
and inside onCreate method
tracker=new GPSTracker(this);
and another one thing ypu can not print or log any statement in doInBackground() method because it will run in background only.
Try to toast your output in onPostExecute() method
If you are using emulator for testing, then you should do the following:
1.In your editor (I assume you are using Eclipse) go to
Window -> Open Perspective -> Show View -> Emulator Control.
2 There you would see two editable textbox with tags 'latitude' and 'longitude'.
3 Set the values appropriately and click send.
Now your emulator has the values set by you.
This is my code for getting Longitude and Latitude , it works great for me
public void setLocation() {
LocationManager LM;
LM = (LocationManager) CurrentContext
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// adjust ur criteria with ur desired features
provider = LM.getBestProvider(criteria, true);
try {
LM.requestLocationUpdates(provider, 1000, 1, this);
if (LM != null) {
Loc = LM.getLastKnownLocation(provider);
if (Loc != null) {
userLocation = new Location("");
userLocation.setLatitude(Loc.getLatitude());
userLocation.setLongitude(Loc.getLongitude());
}
}
} catch (Exception e) {
DisplayUnexpected();
e.printStackTrace();
return;
}
LM.removeUpdates(this);
}
Use this code
public class LocationUpdateService extends Service {
private LocationManager _locationManager;
private boolean _gpsEnabled,_networkEnabled;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
_gpsEnabled = _locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
_networkEnabled = _locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void onStart(Intent intent, int startId) {
Log.e("onStart","onStart");
if( _gpsEnabled ) {
_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000, 0, locationListener);
} else if ( _networkEnabled ){
_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000, 0, locationListener);
}
};
LocationListener locationListener = 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(final Location location) {
final Location currentLocation = location;
Log.e("onLocationChanged", " " + currentLocation);
_locationManager.removeUpdates(locationListener);
Toast.makeText(LocationUpdateService_2.this, "Location lat "+currentLocation.getLatitude()+ " long "+currentLocation.getLongitude() , Toast.LENGTH_LONG).show();
}
};
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;
}
});
}
}