I'm beginning in Android programming and I want to get the longitude and latitude of my Android phone, but I read that the Google Longitude API was discontinued. How I can do that now?
Google Longitude was something else. The location API uses LocationManager and has never been deprecated.
This should get you started. Below code gets the location details from NETWORK_PROVIDER. You can use GPS_PROVIDER if you want to get more frequent updates.
LocationManager locmgr = (LocationManager) getSystemService(LOCATION_SERVICE);
LocationListener loclistener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Double lat = (double) (location.getLatitude());
Double lon = (double) (location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
locmgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,10000,100,loclistener);
Source: Code pulled up from my app which is under development.
Related
I'm trying to use Lat & Lon values for a function I created, but I can't find a way how to get this values from the class "Locationer" to the MainActivity.
I have created a new method called getLat(), but I need a location variable in order to get the latitude value with this method.
I have no idea how to get this "location" and where it comes from in the class.
I've am testing it on my own device.
The Locationer class:
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
public class Locationer extends Activity implements LocationListener {
#Override
public void onLocationChanged(Location location) {
location.getLatitude();
location.getLongitude();
String myLocation = "Latitude = " + location.getLatitude() + " Longitude = " + location.getLongitude();
//I make a log to see the results
Log.e("MY CURRENT LOCATION", myLocation);
}
public double getLat(Location location)
{
return location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
the code in my MainAcitivity.java:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Locationer locationListener = new Locationer();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
lat = **NEED YOUR HELP TO GET THIS VALUE**
lon = **NEED YOUR HELP TO GET THIS VALUE**
queryBooks(lat, lon);
You will have no latitude or longitude directly after setting the LocationManager. The onLocationChanged() will be called when it find a location. See here.
You can do the queryBooks(lat, lon); in the onLocationChanged().
Or you can use getLastKnownLocation(LocationManager.GPS_PROVIDER); but it will be less accurate and can provide you an old location.
Here what you can do in you MainActivity :
private LocationManager mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
private LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
queryBooks(location.getLatitude(), location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
protected void onResume() {
super.onResume();
//every second
int minTime = 1000;
//minDistance between two update
int minDistance = 10;
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, mLocationListener);
};
#Override
protected void onPause() {
mLocationManager.removeUpdates(mLocationListener);
super.onPause();
}
I am creating an app that only checks for location when user clicks a button.
here is my code, and it returns null when i call getLastKnownLocation, even after I call requestLocationUpdates:
public void main(String[] args, int iteration, Context context){
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
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) {}
};
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
Location location = locationManager.getLastKnownLocation(bestProvider);
location = locationManager.getLastKnownLocation(bestProvider);
double lat;
double lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
Log.i("results:", String.valueOf(lat) + " " + String.valueOf(lon) + " 10NN");}}
the location service on the device is enabled.
Thanks very much!
getLastKnownLocation will return null until the callback onLocationChanged() is triggered. This may take several minutes for GPS, even if the sky is clearly visible. If you are indoors it may never run. You have to wait for it to run.
try this pls
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
return false;
}
});
Is there a way to access the GPS once instead of having a looper that constantly checks for location updates?
In my scenario all I'm interested in is finding the current co-ordinates and not a continuous connection with the GPS satellite. Does anyone have any ideas how this can be done? Thanks in advance.
Dont use the getLastKnownLocation because that could be returning null or old data.
This code Only fetches the location once a button is pressed and not every time. People use to leave the location listener listen in every instance and that kills the battery life so Use the code snippet I have posted by doing lots of research:
// get the text view and buttons from the xml layout
Button button = (Button) findViewById(R.id.btnGetLocation);
final TextView latitude = (TextView) findViewById(R.id.textview4);
final TextView longitude = (TextView) findViewById(R.id.textview5);
final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mlocation = location;
Log.d("Location Changes", location.toString());
latitude.setText(String.valueOf(location.getLatitude()));
longitude.setText(String.valueOf(location.getLongitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Status Changed", String.valueOf(status));
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Provider Enabled", provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Provider Disabled", provider);
}
};
// Now first make a criteria with your requirements
// this is done to save the battery life of the device
// there are various other other criteria you can search for..
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
// Now create a location manager
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// This is the Best And IMPORTANT part
final Looper looper = null;
// Now whenever the button is clicked fetch the location one time
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationManager.requestSingleUpdate(criteria, locationListener, looper);
}
});
First check if the last know location is recent. If not, I believe you must to set up onLocationChanged listener, but once you get your first valid location you can always stop the stream of updates.
Addition
public class Example extends Activity implements LocationListener {
LocationManager mLocationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
// Do something with the recent location fix
// otherwise wait for the update below
}
else {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
mLocationManager.removeUpdates(this);
}
}
// Required functions
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}
My code is supposed to find out the users location and place a marker on the map upon entering the application. My location value always equals null, and never receives a value.
if (location != null) {
lat = (int) (location.getLatitude() * 1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "AYO",
"Whats good yo");
CustomPinpoint custom = new CustomPinpoint(d, CampusMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
} else {
Toast.makeText(CampusMap.this, "Couldn't get provider",
Toast.LENGTH_SHORT).show();
}
}
I've had a relatively similar issue with a GPS RPG I was working on and here are some things I noticed:
Firstly, it can take a while for your location to initially be found, which would cause that issue since you're only checking if the location is null.
You may also want to make sure the device's location services are actually enabled before doing anything:
private boolean doLocationsCheck(){
if(!checkLocationEnabled()){
final CharSequence[] items = {"Yes", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("Location must be enabled to play this game! Would you like to enable it now?");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
final int i = item;
runOnUiThread(new Runnable() {
public void run() {
if(i == 0){
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
quit();
}
else{
quit();
}
}
});
}
}).show();
AlertDialog alert = builder.create();
return false;
}
else {
return true;
}
}
private boolean checkLocationEnabled(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER) || service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return enabled;
}
After I've made sure the providers are available I setup a connection like so:
private void setupLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(final Location location) {
runOnUiThread(new Runnable() {
public void run() {
mLocation = location;
//Log.d(TAG, "Latitude: " + location.getLatitude() + " - Longitude: " + location.getLongitude());
saveLocation();
}
});
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Can set to GPS or network, whichever is available
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
The location is then set in a global variable whenever it's updated, and then saved to the preferences. This way, in the event that the providers are enabled, but are taking a while to retrieve the location, the user can still continue to use the application with their last known location that the app stored (does not apply to the first time the program is run).
I know I left out a lot there, but I figured it wasn't really necessary since it was either self-explanatory or already explained in a previous answer.
Cheers~
/*
* getting the best location using the location manager
* Constants.MINIMUM_TIME_BETWEEN_UPDATES = 1000 Constants.MINIMUM_TIME_BETWEEN_UPDATES = 1
*/
LocationManager mLocation;
private String mBestProvider;
// in your onCreate() do the following
mLocation = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mBestProvider = mLocation.getBestProvider(criteria, false);
Location location = mLocation.getLastKnownLocation(mBestProvider);
mLocation.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
Constants.MINIMUM_TIME_BETWEEN_UPDATES,
Constants.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new LocationListenerManager()
);
// and use the following locationListener inner class
private class LocationListenerManager 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()
);
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MapViewActivity.this, message, Toast.LENGTH_LONG).show();
Log.v("poiint=====", ""+message);
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MapViewActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MapViewActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MapViewActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
You have to initialize the locationlistener in the onstartActivity before on create so that it location obtain the location value before onCreate.
My code putput always goes in else part. IT means {location} is null.
Any suggestions?
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, locationListener);
location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
double latitude = location.getLatitude();
double longitude = location.getLongitude();
} else {
//
}
.....
.....
....
If locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) returns null then it means you have never been located.
If you want to get the new location, you should make you activity extend the LocationListener interface and implement the following.
public void onLocationChanged(Location location) {
// Code to execute after being located
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
Don't forget to remove the location updates afterwards.