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);
}
Related
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?
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);
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!
when my location is null my application force closes. I'm certain it's because the location returns null. I tried using the code with Mock GPS and the code works when it passes through the "if (myLocation != null)". I just can't "return myLocation;" after the "if (myLocation == null)"
Please help. Thank you.
#Override
public void onMapReady(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) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
}, 10);
}
return;
}
gMap = googleMap;
if(!gMap.isMyLocationEnabled())
gMap.setMyLocationEnabled(true);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
if I add "return myLocation;" after the "if( myLocation == null )"
It returns an error.
its because you are using void type return
public void onMapReady(GoogleMap googleMap)
use Location type.
public Location onMapReady(GoogleMap googleMap)
public void onMapReady(GoogleMap googleMap) is a abstract "call back" usage method, but i can see that you want to have a method to return a Location obj to use. There is several way to do.
One is use a global object to store the returned result like:
private Location location = null;
#Override
public void onMapReady(GoogleMap googleMap){
......
this.location = myLocation;
}
public void someMethodIUseLocation(){
//TO CALL this.location if need to use
}
just depends on how you wanted to call the way to implement is different
Hello everyone I am developing two apps one for Admin and second for its employees. Now i want to track the employee device using this app the location is send to server when location of employee device changed.Location is send only when location changed. how i can send location of device to server when location is changed??
second i want to show the location of employee on admin app map as it is changing its location.(May i send Location co ordinates from server to admin app through GCM or any other technique?)
Hey, down voters can you explain what is wrong in this question? If you have a Answer to the question the give otherwise try to understand the questions.
please help
Thanks in advance..
public LatLng getLocation()
{
// Get the location manager
MyLocationListener myLocListener = new MyLocationListener();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
locationManager.requestLocationUpdates(bestProvider,timeAfteryougetUpdate, minDistanceAfterYougetupdate, myLocListener);
Double lat,lon;
try {
lat = location.getLatitude ();
lon = location.getLongitude ();
return new LatLng(lat, lon);
}
catch (NullPointerException e){
e.printStackTrace();
return null;
}
}
**Use this to get location **
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
if (loc != null)
{
// Do something knowing the location changed by the distance you requested
methodThatDoesSomethingWithNewLocation(loc);
}
}
#Override
public void onProviderDisabled(String arg0)
{
// Do something here if you would like to know when the provider is disabled by the user
}
#Override
public void onProviderEnabled(String arg0)
{
// Do something here if you would like to know when the provider is enabled by the user
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2)
{
// Do something here if you would like to know when the provider status changes
}
}
you can implement locationListener with service, you can req api from server and send data in any of form, json, xml and once you got the co-ordinates you can show them to the map.
LocationListener
android-location-based-services-example
Hope these can help you.
I know my response is a little bit late.
I will explain my answer using google maps services and firebase real-time database and Geo-Fire for easy location uploading to the cloud database.
Get the real-time location -
#Override public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
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) {
// add the code to get the permission
return;
}
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
protected synchronized void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
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) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override public void onLocationChanged(Location location) {
if(getApplicationContext() != null) {
mlasLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); // plot the realtime location on the map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
addToDataBase(latLng);
}
}
Adding the real-time location to the cloud database using Geo-Fire
public void addtoDataBase(LatLng location){
//unique name work like a promary key
String uid = "119-userID";
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("SOSRequests");
GeoFire geoFire = new GeoFire(databaseReference);
geoFire.setLocation(uid, new GeoLocation(location.latitude, location.longitude));
}