GPS coordinates are inaccurate on my Android Program - android

I am trying to get my current position of my phone via GPS in my program.
The Problem is, that either the coordinates are to inaccurate (only degrees) or no location is given. I programmed my third program now and each of them with a different tutorial, but it did not work as it should work there.
uses-permission are set, so that is not the answer ;)
So here is my code:
public class GpsActivity extends Activity{
private TextView latituteField;
private TextView longitudeField;
private TextView dateField;
private TextView timeField;
private LocationManager locationManager;
private String provider;
private LocationListener listener;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
dateField = (TextView) findViewById(R.id.tvdate);
timeField = (TextView) findViewById(R.id.tvtime);
GregorianCalendar g = new GregorianCalendar();
g.setTimeInMillis(System.currentTimeMillis());
DateFormat df = DateFormat.getInstance();
Date d = df.getCalendar().getTime();
dateField.setText(""+d.getDate()+"."+(d.getMonth()+1)+"."+(1980+d.getYear()));
timeField.setText(""+g.getTime().getHours()+"h "+g.getTime().getMinutes()+"m "+g.getTime().getSeconds()+"s");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(""+lat+"//"+location.getAccuracy());
longitudeField.setText(""+lng+"//"+location.getProvider());
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
listener = new MyLocationListener();
locationManager.requestLocationUpdates("gps" ,10000L, 10.0f, listener);
}
class MyLocationListener implements LocationListener{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null){
latituteField.setText(("Lat: " + location.getLatitude()));
longitudeField.setText("LLong: " + location.getLongitude());
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Thanks for answering!
Rene

You are probably getting just a weak signal. You may use the android location API to get an approximate location.
Make sure that you stand outside and have a free view to the sky for getting a "good" signal. Don't stand next to buildings, etc. However even if you do that you won't get an accurate signal. Phone GPSs' are optimized for energy saving and not for accuracy. They won't put a too expensive chip on your phone as well...

Related

Android | Google Maps Getting Current Location and Update

I am trying to get my current location on map and update it when I move. Every time when an update happens, I want to get current longtidude and latitute values to use in other methods.
private LocationRequest request = LocationRequest.create().setInterval(50000);
I think I have to use LocationRequest . I created an object which will update its location every 5 minutes. But now I don't have any idea how to use it. I checked tutorials on internet but they are so complicated for a beginner. Does anybody have simple solution?
EDIT
This is how my code looks now :
public class MainActivity extends Activity implements LocationListener {
private GoogleMap map;
public double latitude;
public double longitude;
private LocationManager locationManager;
private Context mContext;
private android.location.LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
;
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
getLocation();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
public void getLocation()
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
}
}
When I tried to test it, my app stopped working. Since this is my first android app and I am not very good at it, I couldn't find whats wrong.
for location use this
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
longitude = "0.00";
latitude = "0.00";
}
}
}
from http://androidadvance.com/android_snippets.php#h.r43fot3suy6h
use gps to determine location ( longtidude and latitute values ) and pass it to maps
this mainactivity.java for gps
public class GpsBasicsAndroidExample extends Activity implements LocationListener {
private LocationManager locationManager;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_basics_android_example);
text=(TextView)findViewById(R.id.tv1);
/********** get Gps location service LocationManager object ***********/
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
/*
Parameters :
First(provider) : the name of the provider with which to register
Second(minTime) : the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
Third(minDistance) : the minimum distance interval for notifications, in meters
Fourth(listener) : a {#link LocationListener} whose onLocationChanged(Location) method will be called for each location update
*/
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,10, this);
/********* After registration onLocationChanged method called periodically after each 3 sec ***********/
}
/************* Called after each 3 sec **********/
#Override
public void onLocationChanged(Location location) {
String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
//Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
text.setText(str);
}
#Override
public void onProviderDisabled(String provider) {
/******** Called when User off Gps *********/
Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
/******** Called when User on Gps *********/
Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
and this for maps
main.java
enter code here
public class MainActivity extends FragmentActivity {
GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
final LatLng CIU = new LatLng(35.21843892856462, 33.41662287712097);
Marker ciu = mMap.addMarker(new MarkerOptions()
.position(CIU).title("My Office"));
final LatLng CIU1 = new LatLng(30.21843892856462, 33.41662287712097);
Marker ciu1 = mMap.addMarker(new MarkerOptions()
.position(CIU1).title("My Second Office"));
final LatLng CIU2 = new LatLng(30.21843892856462, 30.41662287712097);
Marker ciu2 = mMap.addMarker(new MarkerOptions()
.position(CIU2).title("My thired Office"));
}
}
Here is how you can do. I will try to make it simple for you:
Add LocationListener interface to your extended activity class using implements keyword. This will force you to Override some methods you will need to find your current location.
public class A extends Activity implements LocationListener {}
Create an instance of the Location Manager class which would act as a hook to call various services and methods in Location package.
private LocationManager locationManager;
Create a method like getLocation() and call the predefined service method from the Location Manger instance.
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
In the onLocationChanged() method you can request the latitude using getLatitude() and longitude using getLongitude() using these two methods that are the part of Location Manager class.
Store the two values obtained by these methods in two separate variables make sure they are of Double type, later you can convert them in String type and then display them on a Text view of your app activity.
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
Call the getLocation() method in your onCreate() and display them on app screen by having a TextView or a toast.
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
Last but not the least dont forget to add permissions in you Manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Fore more details please refer to this link.

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;
}
});
}
}

Show Latitude and Longitude as soon as LocationManger gets it

I am developing a Emergency SMS that whenever you access the activity, the GPS will be enabled and the Location of the user will be shown in a textview, then whenever the user presses send it will be sent to the targeted device. now if i am using Network_Provider the Textview will get the Latitude and Longitude as fast as i access my activity and the message will be showin the textview. however, GPS will show an empty textview and empty Location.
Here is my Code:
public class SMSmyLocation extends Activity implements OnClickListener, LocationListener{
LocationManager locationManager;
LocationListener locationListner;
Context ctx = SMSmyLocation.this;
TextView tv1, tv2;
Button b1;
EditText ed;
Geocoder geo;
List<Address> addresses;
String address = "";
boolean visibility = false;
double Long = 0,Lad = 0;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smsmy_location);
tv1 = (TextView) findViewById(R.id.ESMS);
tv2 = (TextView) findViewById(R.id.currentLocation);
b1 = (Button) findViewById(R.id.SendSMS);
turnGPSOn();
geo = new Geocoder(this, Locale.getDefault());
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (addresses != null)
{
address = addresses.get(0).getAddressLine(0) + " " + addresses.get(0).getAddressLine(1) + " " + addresses.get(0).getAddressLine(2);
tv1.setText(address);
}
else
tv1.setText("fail");
b1.setOnClickListener(this);
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("LM", "Not null");
double Lad = location.getLatitude();
double Long = location.getLongitude();
try {
addresses = geo.getFromLocation(Lad, Long, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("Long", String.valueOf(Long));
}
#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
}
}
what can i do to make the system wait till the LocationManger get the Location Coordinates and once it is available, show them in a text. Is threads a good idea and how it can be implemented? please provide tutorial or code with your answer. Thanks for your time and consideration.
Something like this should work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smsmy_location);
tv1 = (TextView) findViewById(R.id.ESMS);
tv2 = (TextView) findViewById(R.id.currentLocation);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
double Lad = location.getLatitude();
double Long = location.getLongitude();
tv2.setText(Lad+", "+Long);
}
It's mostly just that within the onLocationChanged function you set the textView you want updated. So when the GPS location comes in (yes it can take a long time), it'll trigger this function and update your textView

Setting GPS position on android emulator

I am trying to set a GPS position on my emulator with telnet and using DDMS perspective. Nothing seems to be working, because if you think my code the output on the screen will be "Couldn't get a GPS location". The application works when I run it on a phone. Code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvLat = (TextView) findViewById(R.id.tvLat);
tvLongi = (TextView) findViewById(R.id.tvLongi);
tvLat.setText("test");
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
providers = lm.getBestProvider(crit, false);
Location loc = lm.getLastKnownLocation(providers);
if (loc != null) {
x = loc.getLatitude();
y = loc.getLongitude();
t = "Current latitude: " + x;
t1 = "Current longitude: " + y;
tvLat.setText(t);
tvLongi.setText(t1);
} else {
tvLat.setText("Couldn't get a GPS location");
}
}
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
x = loc.getLatitude();
y = loc.getLongitude();
t = "Current latitude: " + x;
t1 = "Current longitude: " + y;
tvLat.setText(t);
tvLongi.setText(t1);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
tvLat.setText("GPS disabled");
}
#Override
public void onProviderEnabled(String arg0) {
tvLat.setText("GPS enabled");
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
Permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"></uses-permission>
From the DDMS Perspective from the Emulator Control tab located in the bottom-left of Eclipse you have Locations Controls. From there you can input the longitude and latitude and click Send to send those coordinates to the selected emulator.
Maybe you will still not be able to get the last know location, but this will fire the onLocationChanged() method.
EDIT: I see that your class implements LocationListener. Did you register your class for the location changes using lm.requestLocationUpdates() ?
EDIT2: I mean :
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,this);
lm.requestLocationUpdates(LocationManager.GPS, 0, 0,this);

Android MapActivity cannot retrieve location data

I have followed the HelloMapView tutorial for android, and added some code to capture my current location information and display in a textview.
I have tested these code in another program and it worked, it is able to display my longitude and latitude data when the launch that app. However when i copied the code into this MapActivity, it seems that i cannot get the location data.
Here's part of the code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.androidmarker);
itemizedOverlay = new HelloItemizedOverlay(drawable, this);
Button button1 = (Button)this.findViewById(R.id.button1);
tv1 = (TextView) this.findViewById(R.id.textView1);
button1.setOnClickListener(mScan);
latitude = 1.3831625;
longitude = 103.7727321;
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
if (System.currentTimeMillis() - location.getTime() < 3000)
{
longitude = location.getLongitude();
latitude = location.getLatitude();
tv1.setText(Double.toString(longitude));
}
}
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 10, locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
tv1.setText(Double.toString(latitude));
}
#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
}
};
Did you added proper permissions in Manifest? Like this
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Also please check your gps is enabled or working on ur deive.

Categories

Resources