I am trying to get the latitude and longitude of the current location using the following:
GoogleMap map;
map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
lat = map.getMyLocation().getLatitude();
lng = map.getMyLocation().getLongitude();
For some reason the last two lines are causing the app to crash due to a NullPointerException. What am I doing wrong?
The biggest thing that bugs me about this is the fact that map.setMyLocationEnabled(true); does indeed set my current location.
Thanks to anyone looking at this
Try this:
public Double Lat = null;
public Double Lng = null;
String LatLng = null;
private LocationClient mLocationClient;
in your onCreateView() add this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.yourLayout, container, false);
mLocationClient = new LocationClient(getActivity(), this, this);
rootView.findViewById(R.id.ATestButton).setOnClickListener(
// Get the current location
Location currentLocation = mLocationClient.getLastLocation();
Lat = currentLocation.getLatitude();
Lng = currentLocation.getLongitude();
LatLng = Double.toString(Lat) + "," + Double.toString(Lng);
Toast.makeText(getActivity(), LatLng, 0).show();
});
Look at my complete github for a working example.
// I would a test button so can click it to see if anything is returned.
public void turnGPSOn() {
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) {
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
void getLocation()
{
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
turnGPSOn();
}
try {
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10,
locationListener);
} catch (Exception ex) {
}
}
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
String latLongString = "";
try {
if (location != null) {
Log.e("test", "gps is on send");
latitude = Double.toString(location.getLatitude());
longitude = Double.toString(location.getLongitude());
Log.e("test", "location send");
latLongString = "Lat:" + latitude + "\nLong:" + longitude;
Log.w("CurrentLocLatLong", latLongString);
} else {
latLongString = "No location found";
}
} catch (Exception e) {
}
}
Your app is crashing because
map.getMyLocation()
returns null if there is no location data available.So you can have !=null check like this
if( map.getMyLocation() !=null){
lat = map.getMyLocation().getLatitude();
lng = map.getMyLocation().getLongitude();
}
Also this method is deprecated, so you should use FusedLocationProviderApi instead. See official documentation here
Here is a very good implementation of FusedLocation Api, you can check out that too.
map.getMyLocation() is null
you should check for that condition
I have found a solution. While I am still not sure why the other methods is giving me a null pointer, the below works just fine and will suit my needs.
LocationManager locman = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locman .getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lng = location.getLongitude();
double lat = location.getLatitude();
Related
I can not get the GPS to work. I am saving it in a SharedPreference called gps and it will print in a Toast as "http://maps.google.com/?q=" + lat + " , " + lon
this is so when it is sent in a SMS they receiver can just push the link and it opens the map. But when the toast comes up it is blank. Below is my code.
private void showLocation() {
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
locationManager
.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
location = locationManager.getLastKnownLocation(bestProvider);
double lat, lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
prefs.setPreferenceString(getApplicationContext(),"gps" ,"http://maps.google.com/?q=" + lat + " , " + lon);
}
to find your location try to use GPSTracker. link
And use this code.
gps = new GPSTracker(LauncherActivity.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
And one more things, check your device, is it support GPS? And is it (GPS) enable? If your device's GPS is not enable, you will get null....
For more help... check my github repo
I am trying to make such app, here are the code for toast that works well:
Handler handler3 = new Handler(Looper.getMainLooper());
handler3.post(new Runnable(){
#Override
public void run(){
Toast.makeText(context,"mensagem",Toast.LENGTH_LONG).show();
}
});
I have written code in that if GPS is disabled it will be enabled by code and try to get Location from gps but I am getting a null value. Below is my code
public void getValue() {
LocationManager mlocManager = (LocationManager) MySettings.this.getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
System.out.println("GPS IS "+gpsEnabled);
if (!gpsEnabled) {
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy");
try {
getBatteryLevel();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MySettings.this);
Location location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mLocation = location;
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
address = getAddress();
alt = location.getAltitude();
if (meterFootFlag) {
diameter = location.getAccuracy();
} else
diameter = location.getAccuracy() / 3.28084;
} else {
lat = 0.0;
lon = 0.0;
alt = 0.0;
}
} catch (Exception e) {
lat = 0.0;
lon = 0.0;
alt = 0.0;
}
Also I have added permission in manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
but I am getting a null value for the location.
Any ideas on how I can get the location?
Your code is correct just wait until GPs get altitude from a satellite it may take mroe than 1 minute.
try:
public Location showLocation(){
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Class model, save latitude and longitude
NavegadorCoordenadas locate = new NavegadorCoordenadas();
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, false);
Location loc = getLastKnownLocation(lm);
locate.setLatitude(loc.getLatitude());
locate.setLongitude(loc.getLongitude());
return loc;
}
private Location getLastKnownLocation(LocationManager location) {
List<String> providers = location.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = location.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
Make sure that you are checking on DEVICE only.. In Emulator it will give Null Values for GPS as it is running in the system so it doesnot have permission for GPS
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10,
locationListener);
Now make MyLocationListener class in same activity.
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " +loc.getLongitude();
String latitude = "Latitude: " +loc.getLatitude();
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
System.out.println("MESSAGE:"+cityName);
}
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude+"\t city name:"+cityName;
Log.v("OUTPUT, s);
}
#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
}
}
Run your application in Actual device.
you can figure out that automatic start GPS and see console logcat.
Make sure to open Permissions through the
Settings--> Applications-->YourApp-->permissions
And another reason could be delay, it takes time to connect to network, somethimes more than a minute
I am using the following code to find current location of user
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
public void onLocationChanged(Location location) {
Log.e("changed","location");
// TODO Auto-generated method stub
showLocation(location);
}
But the location of user is not finding.If i change provider to Network Provider its working.But with GPS provider only it not working.
change the requestLocationUpdates method so that it updates faster and with less change in coordinates. Change it to:-
requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Try it now. If possible move the phone some meters so that it is detected soon by the GPS satellites. I am presuming that GPS is switched on.
GPS does not provide a 'get my location on demand' functionality. You have to be patient and wait until the device gets a fix from several satellites. This may take several minutes, even with a clear view of the sky. This is why the OS implements this as a callback. onLocationChanged runs when the device has a fix and you just have to wait for it.
Will you please elaborate more? Do you need to find the current location in mapview by Long or Lat? If this is your question then do one thing :
Find Lat and Long by sending manually through DDMS or by generating Lat and Lang on click at mapview :
It can be done by:
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + loc.getLatitude() + "Longitud = " + loc.getLongitude();
Toast.MakeTest(getApplicationContext(),Text,Toast.Length_Long).show()
}
So by this you can get your lat and Long.After getting Lat and Long at mapView's click listener you can write below code:
Projection proj = view1.getProjection();
GeoPoint loc = proj.fromPixels((int)ev.getX(), (int)ev.getY());
//Getting Lat and Log
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
GeoPoint point = new GeoPoint( (int) (loc.getLatitudeE6()),(int) (loc.getLongitudeE6()));
//Getting location from lat and Long
String address="";
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
Toast t =Toast.makeText(getApplicationContext(), "Longitude: "+ longitude +" Latitude: "+ latitude+" name: "+address, Toast.LENGTH_LONG);
t.show();
You will get output as you click at mapview.
For click event on MapView please write above code in dispatchTouchEvent() as
public boolean dispatchTouchEvent(MotionEvent ev) {
int actionType = ev.getAction();
switch (actionType) {
case MotionEvent.ACTION_UP:
//write above code here
}
}
Try this one.
Edit: Check your code with this given below code.
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = "
+ loc.getLatitude() + "Longitud = " + loc.getLongitude();
latituteField.setText(String.valueOf(loc.getLatitude()));
longitudeField.setText(String.valueOf(loc.getLongitude()));
}
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) {
}
}
First check Your GPS is enabled or disabled.After enabling GPS ,using Location listener to get current location.I am using follwing code to get gps location
String sourceLat, sourceLong;
LocationManager locManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtCurrLat = (TextView) findViewById(R.id.txtCurrLat);
txtCurrLong = (TextView) findViewById(R.id.txtCurrLong);
mapView = (MapView) findViewById(R.id.mapview);
geoPoint = null;
mapView.setSatellite(false);
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
double fromLat = location.getLatitude();
double fromLong = roundTwoDecimals(location.getLongitude());
Toast.makeText(getApplicationContext(), fromLat +fromLong+"" , Toast.LENGTH_SHORT).show();
sourceLat = Double.toString(fromLat);
sourceLong = Double.toString(fromLong);
txtCurrLat.setText(sourceLat+","+sourceLong);
btnShow.setOnClickListener(this);
}else{
Toast.makeText(getApplicationContext(), "Location is not avilable", Toast.LENGTH_SHORT).show();
}
}
private void updateWithNewLocation(Location location) {
String latLongString = "";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
sourceLat = Double.toString(lat);
sourceLong = Double.toString(lng);
latLongString = sourceLat + "," + sourceLong;
} else {
latLongString = "No location found";
Toast.makeText(getApplicationContext(), latLongString+"", Toast.LENGTH_SHORT).show();
}
txtCurrLat.setText(latLongString);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
Toast.makeText( getApplicationContext(), "Gps is Disabled.Please enabale gps", Toast.LENGTH_SHORT ).show();
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
Toast.makeText( getApplicationContext(), "Gps is Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
I am trying to find my current location for an android project. When the application is loaded my current location is always null. I have set up the permissions in the manifest etc. When I find the current location I intend to use the coordinates to find distances to other locations on the map. My code snippet is below. Why do I always get a null value?
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = locMan.getBestProvider(crit, false);
location = locMan.getLastKnownLocation(towers);
if (location != null) {
System.out.println("Location is not null!");
lat = (int) (location.getLatitude() *1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lati, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String",
"2nd String");
CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
overlayList.clear();
} else {
System.out.println("Location is null! " + towers);
Toast.makeText(MainMap.this, "Couldn't get provider",Toast.LENGTH_SHORT)
.show();
}
getLastKnownLocation() uses the location(s) previously found by other applications. if no application has done this, then getLastKnownLocation() will return null.
One thing you can do to your code to have a better chance at getting as last known location- iterate over all of the enabled providers, not just the best provider. For example,
private Location getLastKnownLocation() {
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
ALog.d("last known location, provider: %s, location: %s", provider,
l);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
ALog.d("found best last known location: %s", l);
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
If your app can't deal without having a location, and if there's no last known location, you will need to listen for location updates. You can take a look at this class for an example,
https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java
See the method onStartCommand(), where it checks if the network provider is enabled. If not, it uses last known location. If it is enabled, it registers to receive location updates.
if u find current location of devices the use following method in main class
public void find_Location(Context con) {
Log.d("Find Location", "in find_location");
this.con = con;
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) con.getSystemService(location_context);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
locationManager.requestLocationUpdates(provider, 1000, 0,
new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
});
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
addr = ConvertPointToLocation(latitude, longitude);
String temp_c = SendToUrl(addr);
}
}
}
And Add User Permission method in your manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Try this this will not give you null current location
class GetLastLocation extends TimerTask {
LocationManager mlocManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListenerTmp = new CustomLocationListener();
private final Handler mLocHandler;
public GetLastLocation(Handler mLocHandler) {
this.mLocHandler = mLocHandler;
}
#Override
public void run() {
timer.cancel();
mlocManager.removeUpdates(mlocListenerTmp);
Location location = mlocManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
{
if (mlocListenerTmp != null) {
mlocManager.removeUpdates(mlocListenerTmp);
}
currentLocation = location;
}
if (location != null) {
String message = String.format(
"Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Log.d("loc", " :" + message);
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Log.d(
"loc",
":No GPS or network signal please fill the location manually!");
location = mlocManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
currentLocation = location;
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", false);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
}
}
}
}
call it like this
timer.schedule(new GetLastLocation(mLocHandler), 3000);
and the customLocationclass is as follows
public class CustomLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
currentLocation = loc;
String Text = "My current location is: " + "Latitud = "
+ loc.getLatitude() + "Longitud = " + loc.getLongitude();
Log.d("loc", "onLocationChanged" + Text);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
If you are trying it out in a marshmallow device, try enabling location permission for your app manually.
turn on your GPS by using below method. it helps you to show your current location without any ERROR. call it in onCreate
public void displayLocationSettingsRequest(Context context, int requestCode) {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000 / 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(result1 -> {
final Status status = result1.getStatus();
if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED)
try {
status.startResolutionForResult((Activity) context, requestCode);
} catch (IntentSender.SendIntentException ignored) {
}
});
If you are getting a null error with your provider list, change...
List<String> providers = mLocationManager.getProviders(true);
to...
List<String> providers = locationManager.getAllProviders();
This worked for me, and make sure that you have the following in your AndroidManifest.xml file...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Have you tried reversing the code? For example, if(location==null) then print that location is null, and else print location is not null. I got that problem once before and that seemed to have fixed it (i don't know why). Try that.
If that doesn't work, perhaps the google maps API is returning the null value, in which case its a problem with the GM-API or with the call method. Any of these could be the problem.
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