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.
Related
How i am getting location details:
AppLocationService appLocationService = new AppLocationService(getApplicationContext());
Location nwLocation= appLocationService.getLocation(LocationManager.NETWORK_PROVIDER);
nwLocation.getLatitude();
nwLocation.getLongitude();
What is happening since my code has llast known location .... its giving me the last location that was updated say now its evening. its giving me the location updated during morning
What i want:: how can i make a fresh network request to get the current location at my position
AppLocationService.java
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 0;
private static final long MIN_TIME_FOR_UPDATE = 0;
public AppLocationService(Context context) {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#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;
}
}
Your code is registering to receive location updates and also returns the last known location. What happens is expected because you didn't wait to receive an updated one.
Once the method "onLocationChanged" was called by the system you'll have the new one. You can then send a broadcast from the service.
You are trying to get the current location in a synchronous mode which is not possible as it takes some time to lookup the updated one.
The primary reason why you aren't getting updated location information quickly is that you're relying on the NETWORK_PROVIDER.
You should instead use this
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
How to call Explicitly onLocationChanged
public void locationlist()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,
50, 0, this);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {}
if(location == null)
{
}
else{
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
}
}
now call the method locationlist where you want like in a timer.
Use onLocationChanged method and get the longitude and latitude from the parametr location
Code:
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = new Location(location);
latitude=mCurrentLocation .getLatitude();
longitude=mCurrentLocation .getLongitude();
}
I have a simple class GPSListener which gets the GPS coordinates:
public class GPSListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
} ...
Then trying to make use of this class in my activity, I simply invoke the class in my onCreate() function in my activity:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GPSListener();
Criteria criteria = new Criteria();
String bestProvider = mlocManager.getBestProvider(criteria, false);
mlocManager.requestLocationUpdates(bestProvider, 0, 0, mlocListener);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
lat = GPSListener.latitude;
lon = GPSListener.longitude;
Log.d("GPS", "lat: "+lat+" long:"+lon);
} else {
// TODO: GPS not enabled
Log.d("GPSERROR", "GPS not enabled");
}
But whenever I run the application, lat and lon in my activity are always zero. I'm not quite sure how to get around this issue.
When logging:
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
It returns the correct latitude and longitude, it just takes a second or two after the activity starts.
Log.d("GPSSUCCESS", "lat: "+lat+" long:"+lon);
Just returns 0.0 for both. I was under the impression that .requestLocationUpdates would pass the value to lat and lon before the if statement is executed. How can I accomplish this?
You are using public static field for latitude, longitude.
Please change it to non static and using setter, getter with instant object:
lat = mlocListener.getLatitude();
lon = mlocListener.getLongitude();
Google updated its location handling logic. It is now easier to listen location updates with fused location provider. You can implement your location listener in 5 min. Take a look.
Methods for getting the most accurate location
You are listening only gps provider and it is not ready(on waiting for location status) yet and then it does not return any location. Just take a look at fused location provider and write your location listener again.
try this...
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
return false;
}
});
user this Handler to get Location
private Handler customHandler = new Handler();
private Runnable updateTimerThread = new Runnable() {
#Override
public void run()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
secndLocationListener.onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
}
};
to run this
customHandler.postDelayed(updateTimerThread , 1000);
LocationManager uses the last known location from the cache. The cache is updated when you load google maps. Try this out, go out in the open and check your location. Move to a different location about 200m and check your location again. It will be same as the old one. Now, load google maps, you will notice that you application magically now has the new location.
You need to programmatically kick that cache to the latest location. The only way to do that is
YOUR_APPLICATION_CONTEXT.getLocationManager().requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, 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) {
}
});
I have implemented sample application for get the current location latitude longitude.If i lunch my application in emulator and i am sending latitude and longitude from Emulator Controls at eclipse then i am getting current location latitude and longitude which from emulator controls.If i lunch the same application in real device then i am not able to get current location latitude and longitude
I have implemented code for get the current location latitude and longitude as follows:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 11, 11, mlocListener);
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
Log.v("11111","Latitude :"+loc.getLatitude());
Log.v("22222","Longitude :"+ loc.getLongitude());
}
}
From the above code i am not getting current location latitude and longitude in real android device.
How can i get current location latitude and longitude of real device?
please any body help me
GPS_PROVIDER does not work in bound place. So if gps_provider is enabled but you get null location you can replace provider from gps to NETWORK_PROVIDER.
prasad try this code ..by using this i am successfully getting lat long
private Location location = null;
private LocationManager locationManager = null;
locationManager = (LocationManager) context.getSystemService (Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
locationCritera.setAccuracy(Criteria.ACCURACY_FINE);
locationCritera.setAltitudeRequired(false);
locationCritera.setBearingRequired(false);
locationCritera.setCostAllowed(true);
locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT);
String providerName = locationManager.getBestProvider(locationCritera,
true);
location = locationManager.getLastKnownLocation(providerName);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
currentLocation = context.getSharedPreferences(PREFS_NAME, 0);
editor = currentLocation.edit();
}
public String getCurrentLatitude() {
try {
if (!currentLocation.getString("currentLatitude", "")
.equalsIgnoreCase(""))
return currentLocation.getString("currentLatitude", "");
else if (location.getLatitude() != 0.0)
return Double.toString(location.getLatitude());
else
return "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return "0.0";
}
public String getCurrentLongitude() {
try {
if (!currentLocation.getString("currentLongitude", "")
.equalsIgnoreCase(""))
return currentLocation.getString("currentLongitude", "");
else if (location.getLongitude() != 0.0)
return Double.toString(location.getLongitude());
else
return "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return "0.0";
}
are you trying on emulator or device. if you are trying in device then your device should have to be near window or in open place.
override these methods in your MyLocationListener. so that you can track your GPS status. check and see if you can get whats the problem
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
On a real device, you will have to be patient and wait for a fix from the satellites. This can take several minutes, even with a clear view of the sky.
For testing outside, you would be better advised to have a simple text box in your app, initialise it to something like "No GPS fix yet", then send a string comprised of the lat/long coordinates to it when the location changes.
Maybe this is more clear. I will change the conditional to something more efficient later if it is possible
double longitude = 0;
double latitude = 0;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null) {
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else {
Location location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
}
There are two types of location providers,
GPS Location Provider
Network Location Provider
package com.shir60bhushan.gpsLocation;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
This Link can help you for more information
http://androidtutorials60.blogspot.in/2013/09/gps-current-location-of-device.html
I am new to android, can anyone help me for my question....
How to get a current position and tracking in map using GPS without giving any location in a program?????
You want the easy way out ! Use MyLocationOverlay object. you can get the current location by calling the method getLastFix(); . To enable tracking use enableMyLocation(). To add this object to the map you need to add it to your map overlays.
MyLocationOverlay currLoc=new MyLocationOverlay(context,mapKey);
mapView.getAllOverlays.add(currLoc);
currLoc.enableMyLocation();
Location myLastLocation=currLoc.getLastFix();
currLoc.enableCompass();
Do make sure, in onPause() you do this :
currLoc.disableMyLocation(); //to save battery.
you can resume updates in onResume() by calling currLoc.enableMyLocation();
This is the easiest way I could find! and it is quite accurate too
Try ;
String m_BestProvider;
LocationManager m_LocationManager;
LocationListener m_LocationListener = null;
Location m_Location = null;
m_LocationManager = (LocationManager) m_Context.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
m_BestProvider = m_LocationManager.getBestProvider(c, false);
// Define a listener that responds to location updates
m_LocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
m_LocationManager.requestLocationUpdates(m_BestProvider, 0, 0, m_LocationListener);
m_Location = m_LocationManager.getLastKnownLocation(m_BestProvider);
Systme.out.println(m_Location.getLatitude() "," +m_Location.getLongitude());
Add in AndriodManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
public class GPSLocationBased extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationbased);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new Mylocationlistener();
// ---Get the status of GPS---
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS is not enable then it will be on
if(!isGPS)
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
}
//<--registers the current activity to be notified periodically by the named provider. Periodically,
//the supplied LocationListener will be called with the current Location or with status updates.-->
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
/**
*Mylocationlistener class will give the current GPS location
*with the help of Location Listener interface
*/
private class Mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// ---Get current location latitude, longitude, altitude & speed ---
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
float speed = location.getSpeed();
double altitude = location.getAltitude();
Toast.makeText(GPSLocationBased.this,"Latitude = "+
location.getLatitude() + "" +"Longitude = "+ location.getLongitude()+"Altitude = "+altitude+"Speed = "+speed,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Through this code u will get ur lat and long.
and u may use it on ur gmap.
this code also start gps functionality problematically. Hope this will help u.. All the best :)
I want to display latitude and longitude my current location..
For this rather than searching in Google, i searched in SO.
I just want to display my current location latitude and longitude.
See my code below :
public class LocationGetter extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
LocationManager mlocManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new LocationManagerHelper();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100,mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
+ '\n');
tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
+ '\n');
Log.i("MyLocation1",Double.toString(LocationManagerHelper.getLatitude())+" "+Double.toString(LocationManagerHelper.getLongitude()));
} else {
tv.setText("GPS is not turned on...");
}
/** set the content view to the TextView */
setContentView(tv);
}
/* Class My Location Listener */
public static class LocationManagerHelper implements LocationListener {
private static double latitude;
private static double longitude;
#Override
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
}
#Override
public void onProviderDisabled(String provider) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public static double getLatitude() {
return latitude;
}
public static double getLongitude() {
return longitude;
}
}
}
I have also added permission in manifest file :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
See the output i am getting :
Where i am going wrong ? I dont understand, its a simple code and why its not working ?
I just verified your code and it works with these changes, you just need to move the tv.append() calls to the onLocationChanged() method as that is called each time, if you don't use that for the CallBack, then u will get the first set values only and it's only executed once.
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
+ '\n');
tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
+ '\n');
Log.i("MyLocation1",Double.toString(LocationManagerHelper.getLatitude())+" "+Double.toString(LocationManagerHelper.getLongitude()));
}
and I have used these permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
You can look at these and filter out the ones you won't be interested in. I have used a downloaded .gpx file from here
I've tested it on Android 2.2 though,
You got location in Onlocationchanged
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
}
so the lattitude and longitude will be displayed only when the change from the current location.for checking you give some latitude and longitude and send from your emulator control in DDMS and after that you run your program.Sure it will show the location.
If you run this program in device then it show latitude and longitude 0.0 until we change our position.You must move at least 10 meter from your current position to see the output. Because without change current position onLocationChange() method does not fire and output will be 0.0
Use the LocationManager.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
I think with the emulator you can't get the GPS co-ordinates. If you are working with the mobile, try the GPS outside of your building. sometimes you won't get the GPS co-ordinates inside the building. If that time also you failed, then i will post the code that we got succeeded.
The below code just now i have tested and its works for me..
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 GetGPS extends Activity {
String GPSPROVIDER = LocationManager.GPS_PROVIDER;
private static final long MIN_GEOGRAPHIC_POOLING_TIME_PERIOD = 10000;
private static final float MIN_GEOGRAPHIC_POOLING_DISTANCE = (float)5.0;
public LocationManager gpsLocationManager;
static Context context = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
/*Get a listener for GPS*/
LocationListener gpsLocationListener = null;
gpsLocationListener = new GpsLocationListener(this);
/*Start Location Service for GPS*/
gpsLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
/*Register GPS listener with Location Manager*/
gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_GEOGRAPHIC_POOLING_TIME_PERIOD,
MIN_GEOGRAPHIC_POOLING_DISTANCE, gpsLocationListener);
boolean isavailable = gpsLocationManager.isProviderEnabled(GPSPROVIDER);
if(isavailable) {
Location loc = gpsLocationManager.getLastKnownLocation("gps");
if(loc != null) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(GetGPS.this,"Longitude is "+longitude + " Latitude is "+latitude, Toast.LENGTH_LONG).show();
}
}
}
public static class GpsLocationListener implements LocationListener {
public GpsLocationListener(Context context){
}
public void onLocationChanged(Location loc) {
if (loc != null) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(context,"Longitude is "+longitude + " Latitude is "+latitude, Toast.LENGTH_LONG).show();
}
}//End of onLocationChanged Method
#Override
public void onProviderDisabled(String provider) {
}//End of onProviderDisabled Method
#Override
public void onProviderEnabled(String provider) {
}//End of onProviderEnabled Method
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}//End of onStatusChanged Method
}//End of GpsLocationListener class
}
I tested this by moving the device from one place to another...
I hope it will helps..