the app i am creating need to use gps to keep track of how many steps the user steps has taken during excercise. if i cannot count the steps at least i wanted to calculated very accurate distance.
my code can display a map and user location as a blue dot. it did follow me but is quite inaccurate sometimes.i can get the gps to get the current location but it is not very accurate. i heard there is a new location API but i could not find an example code. i can't spot the difference between them..
the following has a lot of code that is unnecessary the reason is i decided to not include the map.
my map api v2 cannot display on emulator. blue-stack displayed a blank map and cannot enter location data. i need to use the same emulator as my team. and i know that map is not a requirement but gps calculate steps/accurate distance is a requirement.
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.view.Menu;
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.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements LocationListener, Runnable, TextWatcher{
protected LocationManager locationManager;
private GoogleMap googleMap;
Button btnStartMove,btnPause,btnResume,btnStop;
//TextView Distance;
static double n=0;
Long s1,r1;
double lat1,lon1,lat2,lon2;
double dis=0.0;
MyCount counter;
Thread t1;
EditText userNumberInput;
boolean bool=false;
int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(isGooglePlay())
{
//setContentView(R.layout.activity_main);
setUpMapIfNeeded();
}
btnStartMove=(Button)findViewById(R.id.Start);//start moving
btnPause=(Button)findViewById(R.id.Pause);//pause
btnResume=(Button)findViewById(R.id.Resume);//resume
btnStop=(Button)findViewById(R.id.Stop);
userNumberInput=(EditText)findViewById(R.id.UserInput);
userNumberInput.addTextChangedListener(this);
//Distance=(TextView)findViewById(R.id.Distance);
btnStartMove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//start(v);
//start(v);
}
});
btnPause.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//start(v);
}
});
btnResume.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//start(v);
}
});
btnStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//start(v);
}
});
}
#Override
public void afterTextChanged(Editable editable) {
try
{
int no = Integer.parseInt(editable.toString());
if(no >= 100)
{
editable.replace(0, editable.length(), "99");
}
}
catch(NumberFormatException e){}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
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();
//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) {
//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!"));
}
#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();
}
public void start (View v){
switch(v.getId()){
case R.id.Start:
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
lat2=location.getLatitude();
lon2=location.getLongitude();
bool=true;
t1=new Thread(this);
t1.start();
counter= new MyCount(30000,1000);
counter.start();
}
else
{
Toast.makeText(MainActivity.this, "null location",
Toast.LENGTH_LONG).show();
}
break;
case R.id.Pause:
counter.cancel();
bool=false;
break;
case R.id.Resume:
counter= new MyCount(s1,1000);
counter.start();
bool=true;
break;
// case R.id.Distance:
// double time=n*30+r1;
// //Distance.setText("Distance:" + dis);
// Toast.makeText(MainActivity.this,"distance in metres:"+String.valueOf(dis)+"Velocity in m/sec :"+String.valueOf(dis/time)+"Time :"+String.valueOf(time),Toast.LENGTH_LONG).show();
// Toast.makeText(MainActivity.this, "Value of Count:" + String.valueOf(count),
// Toast.LENGTH_LONG).show();
// break;
case R.id.Stop:
counter.cancel();
counter= new MyCount(30000,1000);
bool = false;
}
}
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;
//e1.setText(String.valueOf(r1));
}
}
public double getDistance(double lat1, double lon1, double lat2, double lon2) {
double latA = Math.toRadians(lat1);
double lonA = Math.toRadians(lon1);
double latB = Math.toRadians(lat2);
double lonB = Math.toRadians(lon2);
double cosAng = (Math.cos(latA) * Math.cos(latB) * Math.cos(lonB-lonA)) +
(Math.sin(latA) * Math.sin(latB));
double ang = Math.acos(cosAng);
double dist = ang *6371;
return dist;
}
public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)
{
}
#Override
public void run()
{
count=6;
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lat1=location.getLatitude();
lon1=location.getLongitude();
while(bool==true)
{
if(lat1!=lat2 || lon1!=lon2)
{
dis+=getDistance(lat2,lon2,lat1,lon1);
lat2=lat1;
lon2=lon1;
count =7;
//Distance.setText("Distance: " + dis + " Count: " + count);
count++;
}
}
}}
Once you have the distance, you can divide by the persons average step length, which you can let the user enter as paramter.
This will not work when making an exercise whithout moving (on a step trainer).
But for walking or running outdoors this will work.
Related
I'm working on an Android app which gets your current location upon clicking a button, and then prints it if you click another button.
Now, I've got all of the code done, yet I'm stuck into how to retrieve the info of the longitude and latitude to print it, because I earn it on another function.
I'll post my code below to explain what I mean in a clearer manner:
package com.example.geolocation;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener, LocationListener {
private LocationManager locationManager;
public String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button)findViewById(R.id.start);
start.setOnClickListener(this);
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(this);
Button show = (Button)findViewById(R.id.show);
show.setOnClickListener(this);
TextView location = (TextView)findViewById(R.id.location);
TextView providers = (TextView)findViewById(R.id.providers);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
}
#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;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
//funcions boto start
case R.id.start:
locationManager.requestLocationUpdates(
provider,
10000, //temps em ms (10s)
500, //distancia (meters)
this);
//mostrar provider
TextView location = (TextView)findViewById(R.id.location);
location.setText("Provider: " + provider);
break;
//funcio boto stop
case R.id.stop:
locationManager.removeUpdates(this);
break;
//funcio boto show
case R.id.show:
Location locations = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(
provider,
10000, //temps em ms (10s)
1000, //distancia (meters)
this);
//show long & lat
TextView providers = (TextView)findViewById(R.id.providers);
providers.setText("Latitude & longitude: " + ""); //com traslladar valor loc aqui?
break;
}
}
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
int lat = (int) (loc.getLatitude());
int lng = (int) (loc.getLongitude());
loc.toString();
}
#Override
public void onProviderDisabled(String np) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String p) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
The segment where I get the desired info is this one:
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
int lat = (int) (loc.getLatitude());
int lng = (int) (loc.getLongitude());
loc.toString();
}
As you can see, I turn the information into a String.
Now, my problem is: how do I call this info in the main function to print it? In this segment:
//funcio boto show
case R.id.show:
Location locations = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(
provider,
10000, //temps em ms (10s)
1000, //distancia (meters)
this);
//show long & lat
TextView providers = (TextView)findViewById(R.id.providers);
providers.setText("Latitude & longitude: " + ""); //com traslladar valor loc aqui?
break;
what you have to do is the following :
1st - declare a String to store your lattitude and longitude :
private String lattitude , longitude;
2nd - in your get onLocationChanged do the following :
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
int lat = (int) (loc.getLatitude());
int lng = (int) (loc.getLongitude());
lattitude = "lattitude = "+ lat ;
longitude = "longitude = "+ lng;
}
3rd - use the lattitude and longitude to print them in any place you want .
Hope that helps .
I am started learning android a few days ago and I wanted to design an app where I can calculate the distance, time and speed I have run by using gps.
So I have tried couple of examples and gone through some of the tutorials. I have written the following code.
But the is just giving me the gps locations but it is not calculating the distance and speed can any one tell me where is my problem and how to solve it.
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class test extends Activity implements Runnable {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 3;
protected LocationManager locationManager;
Location location;
static double n=0;
Long s1,r1;
double plat,plon,clat,clon,dis;
MyCount counter;
Thread t1;
EditText e1;
boolean bool=true;
Button b1,b2,b3,b4,b5;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
b1=(Button)findViewById(R.id.button1);//<--- current position
b2=(Button)findViewById(R.id.button2);//<---- start moving.. calculates distance on clicking this
b3=(Button)findViewById(R.id.button3);//<--- pause
b4=(Button)findViewById(R.id.button4);//<-- resume
b5=(Button)findViewById(R.id.button5);// <-- get distance
e1=(EditText)findViewById(R.id.editText1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
clat=location.getLatitude();
clon=location.getLongitude();
Toast.makeText(test.this, message,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(test.this, "null location",
Toast.LENGTH_LONG).show();
}
}
public void start (View v){
switch(v.getId()){
case R.id.button2:
t1=new Thread();
t1.start();
counter= new MyCount(30000,1000);
counter.start();
break;
case R.id.button3:
counter.cancel();
bool=false;
break;
case R.id.button4:
counter= new MyCount(s1,1000);
counter.start();
bool=true;
break;
case R.id.button5:
double time=n*30+r1;
Toast.makeText(test.this,"distance in metres:"+String.valueOf(dis)+"Velocity in m/sec :"+String.valueOf(dis/time)+"Time :"+String.valueOf(time),Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(test.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(test.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(test.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(test.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
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;
e1.setText(String.valueOf(r1));
}
}
public double getDistance(double lat1, double lon1, double lat2, double lon2) {
double latA = Math.toRadians(lat1);
double lonA = Math.toRadians(lon1);
double latB = Math.toRadians(lat2);
double lonB = Math.toRadians(lon2);
double cosAng = (Math.cos(latA) * Math.cos(latB) * Math.cos(lonB-lonA)) +
(Math.sin(latA) * Math.sin(latB));
double ang = Math.acos(cosAng);
double dist = ang *6371;
return dist;
}
#Override
public void run() {
while (bool){
clat=location.getLatitude();
clon=location.getLongitude();
if(clat!=plat || clon!=plon){
dis+=getDistance(plat,plon,clat,clon);
plat=clat;
plon=clon;
}
}
}
}
Notice that you are not using the distanceBetween or distanceTo methods and opted to calculate the distance your own way. Does your formula calculate great circle distances? It looks simpler than it ought to be. Suggest you check this out.
I am Trying to develop small application in which i am trying to Detect Location.
I am using the following code but i don't know why my application crashes. It show the application stops Unfortunately.
Here is the code. Please tell me if there is any bug and if not then please at least reply.
Thanks.
Here is the Code.
package com.project.kamani.nearby;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
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.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Map extends Activity implements LocationListener{
public GoogleMap google_map;
public List<Address> addresses;
public Geocoder geocoder;
private Location location;
private double lat;
private double lang;
private Criteria criteria;
private LocationManager location_manager;
private String provider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=20;//DISTANCE IN METERS
private static final long MIN_TIME_BW_UPDATES=1000*60*1;// TAKES UPDATE AFTER 1 MINUTES
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isGooglePlayAvailable())
{
criteria=new Criteria();
setContentView(R.layout.mapdemo);
getGoogleMap();
getUserLocation();
//Toast.makeText(this, "Latitude:"+lat+" Longitude:"+lang, Toast.LENGTH_LONG).show();
getAddress(lat,lang);
drawMarker(lat,lang);
}
}
private boolean isGooglePlayAvailable(){
int status=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(status==ConnectionResult.SUCCESS)
return true;
else
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
return false;
}
private void getGoogleMap(){
if(google_map==null){
google_map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
}
}
private void drawMarker(double lattitude,double longitude){
google_map.clear();
google_map.setMyLocationEnabled(true);
LatLng latlng=new LatLng(lattitude, longitude);
google_map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
google_map.animateCamera(CameraUpdateFactory.zoomTo(15));
LatLng currentPosition = new LatLng(lattitude,longitude);
google_map.addMarker(new MarkerOptions().position(currentPosition).snippet("Address:" + addresses.get(0).getAddressLine(0) + "City:"+ addresses.get(0).getAddressLine(1)+"Country:"+addresses.get(0).getAddressLine(2)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).title("ME"));
}
private void getAddress(double lattitude,double longitude){
geocoder=new Geocoder(Map.this, Locale.getDefault());
try {
addresses=geocoder.getFromLocation(lattitude, longitude, 1);
Toast.makeText(Map.this, "Address:" + addresses.get(0).getAddressLine(0) + "City:"+ addresses.get(0).getAddressLine(1)+"Country:"+addresses.get(0).getAddressLine(2), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
private void getUserLocation(){
location_manager=(LocationManager) getSystemService(LOCATION_SERVICE);
if(location_manager!=null){
provider=location_manager.getBestProvider(criteria, true);
location=location_manager.getLastKnownLocation(provider);
location_manager.requestLocationUpdates(provider, Map.MIN_TIME_BW_UPDATES, Map.MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
lat=location.getLatitude();
lang=location.getLongitude();
}
}
#Override
public void onLocationChanged(Location location) {
google_map.clear();
drawMarker(lat, lang);
}
#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
}
}
Here is the snapshot that error i am getting in logcat.
I hope it will be helpful to solve error.
EDIT:-
If you don't want to monitor once again full code just try to view at getUserLocation method still the application stops working when i enable the GPS thanks for your support.
location is never initialized. Your are setting location as the variable that will hold the return value of getUserLocation() and it is also its parameter; both are null.
public class MainActivity extends MapActivity implements LocationListener {
private MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting reference to MapView
mapView = (MapView) findViewById(R.id.map_view);
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));
// Getting MapController
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point);
// Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the image of mark in the map
Drawable drawable = this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark the current location in the map
CurrentLocationOverlay currentLocationOverlay = new CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the overlay
OverlayItem currentLocation = new OverlayItem(point, "Current Location", "Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
#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
}
}
Download Here
I have an app with google maps with one single activity where a map is displayed. I have a menu that allows me to change the map type from but I would like to have an option to get my current location.
Here's the code of my activity:
package com.example.chiapa_mapas;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
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.MarkerOptions;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends android.support.v4.app.FragmentActivity implements OnMapClickListener, LocationListener{
private GoogleMap mMap;
private Context ctx;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setOnMapClickListener(this);
// Enable LocationLayer of Google Map
mMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.opcoes, menu);
return true; }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
mMap.setMapType(1);
break;
case R.id.satellite:
mMap.setMapType(2);
break;
case R.id.terrain:
mMap.setMapType(3);
break;
case R.id.hybrid:
mMap.setMapType(4);
break;
case R.id.none:
mMap.setMapType(0);
break;
case R.id.posicao_actual:
//mMap.setMapType(0);
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria,true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0,(android.location.LocationListener) ctx);
break;
default: return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onMapClick(LatLng position) {
// TODO Auto-generated method stub
mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//double ltt = position.latitude;
//double lgt = position.longitude;
//String msg = "Latitude: " + Double.toString(ltt) + " , Longitude: " + Double.toString(lgt) + "";
//Toast toast = Toast.makeText(ctx, msg, Toast.LENGTH_SHORT);
//toast.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// 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
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView
locationManager.removeUpdates((android.location.LocationListener) this);
}
}
Can someone help? When I press the option "posicao actual" (current location) it crashes.
Thanks in advance
Chiapa
This works for me:
public void methodName(){
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
android.location.LocationListener locationListener = new android.location.LocationListener() {
public void onLocationChanged(Location location) {
//Any method here
}
public void onStatusChanged (String provider, int status, Bundle extras){}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled (String provider){}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0, locationListener);
}
Thanks chiapa.
change
locationManager.requestLocationUpdates(provider, 20000, 0,(android.location.LocationListener) ctx);
to
locationManager.requestLocationUpdates(provider, 20000, 0,this);
and remove updates too
I would like to know how to get the speed of a vehicle using your phone while seated in the vehicle using gps. I have read that the accelerometer is not very accurate. Another thing is; will GPS be accessible while seated in a vehicle. Won't it have the same effect as while you are in a building?
Here is some code I have tried but I have used the NETWORK PROVIDER instead.I will appreciate the help. Thanks...
package com.example.speedtest;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
LocationManager locManager;
LocationListener li;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
li=new speed();
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, li);
}
class speed implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
Float thespeed=loc.getSpeed();
Toast.makeText(MainActivity.this,String.valueOf(thespeed), Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}
}
for more information onCalculate Speed from GPS Location Change in Android Mobile Device view this link
Mainly there are two ways to calculate the speed from mobile phone.
Calculate speed from Accelerometer
Calculate speed from GPS Technology
Unlike Accelerometer from GPS Technology if you're going to calculate speed you must enable data connection and GPS connection.
In here we are going to calculate speed using GPS connection.
In this method we using how frequency the GPS Location points are changing during single time period. Then if we have the real distance between the geo locations points we can get the speed. Because we have the distance and the time.
Speed = distance/time
But getting the distance between two location points is not very easy. Because the world is a goal in shape the distance between two geo points is different from place to place and angle to angle. So we have to use “Haversine Algorithm”
First we have to give permission for Get Location data in Manifest file
Make the GUI
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtCurrentSpeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="000.0 miles/hour"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox android:id="#+id/chkMetricUnits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Use metric units?"/>
Then make an interface to get the speed
package com.isuru.speedometer;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
public interface IBaseGpsListener extends LocationListener, GpsStatus.Listener {
public void onLocationChanged(Location location);
public void onProviderDisabled(String provider);
public void onProviderEnabled(String provider);
public void onStatusChanged(String provider, int status, Bundle extras);
public void onGpsStatusChanged(int event);
}
Implement the logic to get the speed using the GPS Location
import android.location.Location;
public class CLocation extends Location {
private boolean bUseMetricUnits = false;
public CLocation(Location location)
{
this(location, true);
}
public CLocation(Location location, boolean bUseMetricUnits) {
// TODO Auto-generated constructor stub
super(location);
this.bUseMetricUnits = bUseMetricUnits;
}
public boolean getUseMetricUnits()
{
return this.bUseMetricUnits;
}
public void setUseMetricunits(boolean bUseMetricUntis)
{
this.bUseMetricUnits = bUseMetricUntis;
}
#Override
public float distanceTo(Location dest) {
// TODO Auto-generated method stub
float nDistance = super.distanceTo(dest);
if(!this.getUseMetricUnits())
{
//Convert meters to feet
nDistance = nDistance * 3.28083989501312f;
}
return nDistance;
}
#Override
public float getAccuracy() {
// TODO Auto-generated method stub
float nAccuracy = super.getAccuracy();
if(!this.getUseMetricUnits())
{
//Convert meters to feet
nAccuracy = nAccuracy * 3.28083989501312f;
}
return nAccuracy;
}
#Override
public double getAltitude() {
// TODO Auto-generated method stub
double nAltitude = super.getAltitude();
if(!this.getUseMetricUnits())
{
//Convert meters to feet
nAltitude = nAltitude * 3.28083989501312d;
}
return nAltitude;
}
#Override
public float getSpeed() {
// TODO Auto-generated method stub
float nSpeed = super.getSpeed() * 3.6f;
if(!this.getUseMetricUnits())
{
//Convert meters/second to miles/hour
nSpeed = nSpeed * 2.2369362920544f/3.6f;
}
return nSpeed;
}
}
Combine logic to GUI
import java.util.Formatter;
import java.util.Locale;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity implements IBaseGpsListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.updateSpeed(null);
CheckBox chkUseMetricUntis = (CheckBox) this.findViewById(R.id.chkMetricUnits);
chkUseMetricUntis.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
MainActivity.this.updateSpeed(null);
}
});
}
public void finish()
{
super.finish();
System.exit(0);
}
private void updateSpeed(CLocation location) {
// TODO Auto-generated method stub
float nCurrentSpeed = 0;
if(location != null)
{
location.setUseMetricunits(this.useMetricUnits());
nCurrentSpeed = location.getSpeed();
}
Formatter fmt = new Formatter(new StringBuilder());
fmt.format(Locale.US, "%5.1f", nCurrentSpeed);
String strCurrentSpeed = fmt.toString();
strCurrentSpeed = strCurrentSpeed.replace(' ', '0');
String strUnits = "miles/hour";
if(this.useMetricUnits())
{
strUnits = "meters/second";
}
TextView txtCurrentSpeed = (TextView) this.findViewById(R.id.txtCurrentSpeed);
txtCurrentSpeed.setText(strCurrentSpeed + " " + strUnits);
}
private boolean useMetricUnits() {
// TODO Auto-generated method stub
CheckBox chkUseMetricUnits = (CheckBox) this.findViewById(R.id.chkMetricUnits);
return chkUseMetricUnits.isChecked();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null)
{
CLocation myLocation = new CLocation(location, this.useMetricUnits());
this.updateSpeed(myLocation);
}
}
#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 void onGpsStatusChanged(int event) {
// TODO Auto-generated method stub
}
}
If you want to convert Meters/Second to kmph-1 then you need to multipl the Meters/Second answer from 3.6
Speed from kmph-1 = 3.6 * (Speed from ms-1)
GPS works fine in a vehicle. The NETWORK_PROVIDER setting might not be accurate enough to get a reliable speed, and the locations from the NETWORK_PROVIDER may not even contain a speed. You can check that with location.hasSpeed() (location.getSpeed() will always return 0).
If you find that location.getSpeed() isn't accurate enough, or it is unstable (i.e. fluctuates drastically) then you can calculate speed yourself by taking the average distance between a few GPS locations and divide by the time elapsed.
public class MainActivity extends Activity implements LocationListener {
add implements LocationListener next to Activity
LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
LocationManager.GPS_PROVIDER, 0, 0, The first zero stands for minTime and the second one for minDistance in which you update your values. Zero means basically instant updates which can be bad for battery life, so you may want to adjust it.
#Override
public void onLocationChanged(Location location) {
if (location==null){
// if you can't get speed because reasons :)
yourTextView.setText("00 km/h");
}
else{
//int speed=(int) ((location.getSpeed()) is the standard which returns meters per second. In this example i converted it to kilometers per hour
int speed=(int) ((location.getSpeed()*3600)/1000);
yourTextView.setText(speed+" km/h");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
}
Don't forget the Permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
We can use location.getSpeed();
try {
// Get the location manager
double lat;
double lon;
double speed = 0;
LocationManager locationManager = (LocationManager)
getActivity().getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
try {
lat = location.getLatitude();
lon = location.getLongitude();
speed =location.getSpeed();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
mTxt_lat.setText("" + lat);
mTxt_speed.setText("" + speed);
}catch (Exception ex){
ex.printStackTrace();
}