get Latitude and Longitude values from locationManager - java

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

Related

Get values from Service into Activity

I wrote below code using fusedapi to get lat and longi.
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
/**
* Created by DELL WORLD on 1/24/2017.
*/
public class LocationWithFusedApi extends Service implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, LocationListener {
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
private LocationRequest mLocationRequest;
double lat, lon;
final static String Mydata = "MyData";
/* public LocationWithFusedApi() {
super("LocationWithFusedApi");
}*/
/*
#Override
public void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}*/
#Override
public void onStart(Intent intent, int startId) {
Log.d("LocationWithFusedAPI", "Called");
super.onStart(intent, startId);
mGoogleApiClient.connect();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
/* #Override
protected void onHandleIntent(Intent intent) {
}*/
#Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
}
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lon = location.getLongitude();
System.out.println("Latest" + lat + ":" + lon);
Intent intent = new Intent();
intent.setAction("Mydata");
intent.putExtra("lat",lat);
intent.putExtra("lon",lon);
sendBroadcast(intent);
sendlat();
sendlon();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();
System.out.println("Last" + lat + ":" + lon);
sendlat();
sendlon();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
buildGoogleApiClient();
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public double sendlat() {
return lat;
}
public double sendlon() {
return lon;
}
public void removeupdate() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
Now trying to get lat and lon values in another activity to show to user via calling sendlat and sendlon but getting null. what mistake m I doing.
Here is code for activity where I m trying to get values.
public class ShareLocation extends AppCompatActivity {
GPSDataPicker gps;
String clickable = "";
Latlonreceiver latlonreceiver;
double lat, lon;
#Override
protected void onStart() {
latlonreceiver = new Latlonreceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(LocationWithFusedApi.Mydata);
registerReceiver(latlonreceiver, intentFilter);
Intent intent = new Intent(ShareLocation.this, LocationWithFusedApi.class);
startService(intent);
super.onStart();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* LocationWithFusedApi locationWithFusedApi = new LocationWithFusedApi();
double latitude = locationWithFusedApi.sendlat();
double longitude = locationWithFusedApi.sendlon();*/
double latitude = lat;
double longitude = lon;
setContentView(R.layout.sharelocation);
clickable = "https://maps.google.com/?q=" + latitude + "," + longitude;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(latlonreceiver);
}
public class Latlonreceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
lat = intent.getDoubleExtra("lat", 0.0);
lon = intent.getDoubleExtra("lon", 0.0);
}
}
Look into using broadcast receiver. The basic mistake here is that the retrieval of the location is running on a different thread asynchronously. So by the time you call your sendXxx() methods the location has not been resolved yet. With asynchronous code you need the service to push you the result after the location has been resolved. The standard way in this case would be the broadcast receiver.

Arcgis Map : Get Current Location Error , Not displaying my current location

Hie,
I tried this sample code that one of the person who gave me this in my other question in stack overflow. I tried using this code but when i run the applicationn, it doesnt locate my current device and it doesnt even display a dot of my location .. The code does not give me any red underline errors but i am unable to locate the current location i am at.
What did i miss out? is there anyone who has a sample working source code file that i can download from to get my current device location??
the codes i used is as followed,
This is my MainActivity.class
public class MainActivity extends Activity {
MapView mMapView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMapView = (MapView) findViewById(R.id.mapview);
mMapView.addLayer(new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"));
mMapView = new MapView(this);
LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(Location loc){
}
};
MyLocation mylocation = new MyLocation();
mylocation.getLocation(this, locationResult);
}
This is MyLocation.java
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
You have to write the code for displaying a red dot in the gotLocation method which is currently empty. That is why you are not getting anything displayed on top of the map.

onLocationChanged doesn't work?

on LocationChanged listener don't work.
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class SimpleLocation extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
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());
Toast.makeText(getApplicationContext(),
"Lat:" + lat + " Lng:" + lng, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "No Value",
Toast.LENGTH_LONG).show();
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1,
(LocationListener) this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates((LocationListener) this);
}
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
Toast.makeText(getApplicationContext(),
"onLocationChanged Lat:" + lat + " Lng:" + lng,
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
locationManager.requestLocationUpdates(provider, 400, 1,
(LocationListener) this);
which is of the format:
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
This line in your code specifies that the location changes will be registered in your application only when there is minimum of "1" distance movement. Set that to 0 and try running your code again. Or set both minTime and minDistance to 0 and try.

User location not found :- latitude and longitude in android

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.

User location cannot be found

I post a question not long ago. Basically what I am trying to do is have my location manager return my longitude and latitude. My getBestProvider() method returns network, however my locationManager.getLastKnownLocation(provider) returns null. As you can see I've implemented the listener. I must have done something wrong.
Here is the code.
public class Activity1 extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
readFile();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println(provider);
System.out.println(locationManager.getProviders(criteria, false));
System.out.println(locationManager.getProvider("network"));
System.out.println(locationManager.getAllProviders());
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());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
} else {
System.out.println("Provider not available");
System.out.println("Provider not available");
}
}#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
}
private void updateWithNewLocation(Location location){
String latLongString;TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else { latLongString = "No location found"; }
}

Categories

Resources