mLastLocation: null, always is null, how can solve it? - android

mLastLocation: null, always is null, how can solve it?
this is my code
private void displayLocation() {
if(ActivityCompat.checkSelfPermission(TrackingOrder.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(TrackingOrder.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
Log.d("Check-1","ok");
requestRuntimePermission();
}
else
{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
//mLastLocation = LocationServices.getFusedLocationProviderClient(this).getLastLocation().addOnSuccessListener(mGoogleApiClient);
Log.d("Check-2","ok");
Log.d("mLastLocation",String.valueOf(mLastLocation));
if(mLastLocation != null)
{
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Log.d("Check - latitude",String.valueOf(latitude));
Log.d("Check - longitude",String.valueOf(longitude));
// Add Marker in your location and move the camera
LatLng yourLocation = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(yourLocation).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(yourLocation));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
//After add marker for your location, add marker for this order and draw route
drawRoute(yourLocation,Common.currentRequest.getAddress());
}
else
{
Log.d("Error","Cannot get location");
Toast.makeText(this,"Could'nt get your location", Toast.LENGTH_SHORT).show();
}
}
}
this is my mGoogleApiClient code
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
But when I locad this displayLocation funcation, there is problem
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Because the mLastLocation still get null.
So where I need to modify?
there has full code
https://luvtas.com/gmap.txt

There are some edge cases when getLastLocation returns null. Look at this question for more information:
LocationClient getLastLocation() return null
Are you testing on emulator or physical device? Do you have GPS turned on? Do you have permissions defined in Manifest.xml?
Also, in your code, you are listening for location updates in onLocationChanged(Location location). You are storing new received location in mLastLocation and then calling displayLocation(). And then you do mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); in displayLocation() and override value received from onLocationChanged. Maybe not intended?

Related

Zoom Google Maps Android Firebase

I'm doing my car tracking application. The problem is that when I zoomed in or out, the zoom restarts its position. And when I look at another part of the map, it returns me to my location. How can I solve that?
public void onLocationChanged(Location location) {
if(getApplicationContext()!=null){
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
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) {
ActivityCompat.requestPermissions(CustomerMapActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
The issue is, with every new location update, your are moving and zooming the camera so you need remove
public void onLocationChanged(Location location) {
if(getApplicationContext()!=null){
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
// remove to stop frequent camera movement
//mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
or alternatively, you can increase the location retrieval interval to give user some more time as
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);

android - onLocationChanged never called

I am currently implementing a feature of getting user's current location with Google API.
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); // user location center in map (every update)
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
#Override
public void onConnected(#Nullable Bundle bundle) {
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) {
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(DISPLACEMENT)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}else{
}
}
However, onLocationChanged callback function is never triggered when I requestLocationUpdates in onConnected. I have log several status out, showing that mLocationRequest is created and requestLocationUpdates is called.
Any ideas on this? Thank you all!

Android app stopped unfortunately (Location)

I was struggling very long to fix a users location
in a Google maps activity. When i runned it once it worked perfectly,
the marker was spotted at the users location.
But now i ran it again and the app stops with two errors in the stack-trace.
Here are the errors:
at com.doppler.stackingcoder.pechhulp.PechhulpActivity.onLocationChanged(PechhulpActivity.java:87)
at com.doppler.stackingcoder.pechhulp.PechhulpActivity.onMapReady(PechhulpActivity.java:101)
And here are the two methods which have the errors:
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude(); // Line 87
longtitude = location.getLongitude();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.zoomTo(10));
mMap.getUiSettings().setRotateGesturesEnabled(false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
onLocationChanged(location); // Line 101
LatLng myPosition = new LatLng(latitude, longtitude);
mMap.addMarker(new MarkerOptions().position(myPosition)
.title("Uw Locatie:")
.snippet("Dit is uw locatie")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_mini))
);
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
}

GoogleMaps API v2 setMyLocationEnabled is different from LocationManager

I am having probably simple question, but i can't figure out, what is wrong.
When i set my location with button on the map, the location is almost 100 exact.
When i use Location manager to get my location, i am getting about 10-20 meters wrong location.
Here is the code:
#Override
public void onMapReady(final GoogleMap googleMap) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mGoogleMap = googleMap;
mGoogleMap.setMyLocationEnabled(true);
Button setLoc = (Button) findViewById(R.id.setLoc);
assert setLoc != null;
setLoc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mGoogleMap.clear();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
latLng = new LatLng(location.getLatitude(), location.getLongitude());
Toast.makeText(MainActivity.this, String.valueOf(latLng), Toast.LENGTH_LONG).show();
//zoom to current position:
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
mGoogleMap.addMarker(new MarkerOptions().position(latLng).title("Your location").anchor(0.0f, 1.0f));
}
});
}
What am i doing wrong? The blue point is not at the same place where my marker is, and the blue point have better precision as i said above.
Thanks!
small UPDATE
when i run the code on emulator, it is almost the same location...hmm, on real device it is different. What could be the problem?
I think it maybe device dependent. You need to change the priority to PRIORITY_HIGH_ACCURACY. Before requesting location updates, your app must connect to the location services and make a location request. Once a a location request is in place you can start the regular updates by calling requestLocationUpdates() do this in the onConnected() callback provided by Google API Client, which is called when the client is ready.
Update location using LocationListener callback. Call requestLocationUpdates(), passing it your instance of the GoogleApiClient, the LocationRequest object, and a LocationListener. Define a startLocationUpdates() method, called from the onConnected() callback.
#Override
public void onConnected(Bundle connectionHint) {
...
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}

How to get the current location in Google Maps Android API v2?

Using
mMap.setMyLocationEnabled(true)
can set the myLocation layer enable.
But the problem is how to get the myLocation when the user clicks on the button?
I want to get the longitude and latitude.
The Google Maps API location now works, even has listeners, you can do it using that, for example:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
and then set the listener for the map:
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will get called when the map first finds the location.
No need for LocationService or LocationManager at all.
OnMyLocationChangeListener interface is deprecated.
use com.google.android.gms.location.FusedLocationProviderApi instead. FusedLocationProviderApi provides improved location finding and power usage and is used by the "My Location" blue dot. See the MyLocationDemoActivity in the sample applications folder for example example code, or the Location Developer Guide.
At the moment GoogleMap.getMyLocation() always returns null under every circumstance.
There are currently two bug reports towards Google, that I know of, Issue 40932 and Issue 4644.
Implementing a LocationListener as brought up earlier would be incorrect because the LocationListener would be out of sync with the LocationOverlay within the new API that you are trying to use.
Following the tutorial on Vogella's Site, linked earlier by Pramod J George, would give you directions for the Older Google Maps API.
So I apologize for not giving you a method to retrieve your location by that means. For now the locationListener may be the only means to do it, but I'm sure Google is working on fixing the issue within the new API.
Also sorry for not posting more links, StackOverlow thinks I'm spam because I have no rep.
---- Update on February 4th, 2013 ----
Google has stated that the issue will be fixed in the next update to the Google Maps API via Issue 4644. I am not sure when the update will occur, but once it does I will edit this post again.
---- Update on April 10th, 2013 ----
Google has stated the issue has been fixed via Issue 4644. It should work now.
try this
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
Ensure that you have turned ON the location services on the device.
Else you won't get any location related info.
This works for me,
map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange (Location location) {
LatLng loc = new LatLng (location.getLatitude(), location.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
};
map.setOnMyLocationChangeListener(myLocationChangeListener);
}
To get the location when the user clicks on a button call this method in the onClick-
void getCurrentLocation() {
Location myLocation = mMap.getMyLocation();
if(myLocation!=null)
{
double dLatitude = myLocation.getLatitude();
double dLongitude = myLocation.getLongitude();
Log.i("APPLICATION"," : "+dLatitude);
Log.i("APPLICATION"," : "+dLongitude);
mMap.addMarker(new MarkerOptions().position(
new LatLng(dLatitude, dLongitude)).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(Utils.getBitmap("pointer_icon.png"))));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
else
{
Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
}
}
Also make sure that the
setMyLocationEnabled
is set to true.
Try and see if this works...
Have you tried GoogleMap.getMyLocation()?
I just found this code snippet simple and functional,
try :
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}}
here's the link of the tutorial : Getting the Last Known Location
try this
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}
Try This
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: ” +
“Latitud = ” + loc.getLatitude() +
“Longitud = ” + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text, Toast.LENGTH_SHORT).show();
tvlat.setText(“”+loc.getLatitude());
tvlong.setText(“”+loc.getLongitude());
this.gpsCurrentLocation();
}
It will give the current location.
mMap.setMyLocationEnabled(true);
Location userLocation = mMap.getMyLocation();
LatLng myLocation = null;
if (userLocation != null) {
myLocation = new LatLng(userLocation.getLatitude(),
userLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
mMap.getMaxZoomLevel()-5));
Only one condition, I tested that it wasn't null was, if you allow enough time to user to touch the "get my location" layer button, then it will not get null value.
the accepted answer works but some of the used methods are now deprecated so I think it is best if I answer this question with updated methods.
this is answer is completely from this guide on google developers
so here is step by step guide:
implement all this in your map activity
MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks
in your onCreate:
private GoogleMap mMap;
private Context context;
private TextView txtStartPoint,txtEndPoint;
private GoogleApiClient mGoogleApiClient;
private Location mLastKnownLocation;
private LatLng mDefaultLocation;
private CameraPosition mCameraPosition;
private boolean mLocationPermissionGranted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
context = this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
mGoogleApiClient.connect();
}
in your onConnected :
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
in your onMapReady :
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Do other setup activities here too, as described elsewhere in this tutorial.
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
and these two are methods in onMapReady :
private void updateLocationUI() {
if (mMap == null) {
return;
}
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
}
}
private void getDeviceLocation() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
if (mLocationPermissionGranted) {
mLastKnownLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
}
// Set the map's camera position to the current location of the device.
float DEFAULT_ZOOM = 15;
if (mCameraPosition != null) {
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
} else if (mLastKnownLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d("pouya", "Current location is null. Using defaults.");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
this is very fast , smooth and effective. hope this helps
I would rather use FusedLocationApi since OnMyLocationChangeListener is deprecated.
First declare these 3 variables:
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private LocationListener mLocationListener;
Define methods:
private void initGoogleApiClient(Context context)
{
mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
{
#Override
public void onConnected(Bundle bundle)
{
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
setLocationListener();
}
#Override
public void onConnectionSuspended(int i)
{
Log.i("LOG_TAG", "onConnectionSuspended");
}
}).build();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
private void setLocationListener()
{
mLocationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location)
{
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
}
};
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}
private void removeLocationListener()
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
initGoogleApiClient() is used to initialize GoogleApiClient object
setLocationListener() is used to setup location change listener
removeLocationListener() is used to remove the listener
Call initGoogleApiClient method to start the code working :) Don't forget to remove the listener (mLocationListener) at the end to avoid memory leak issues.

Categories

Resources