Android Real Time Location Tracking - android

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

Related

Can't get location using onLocationChanged

I have been trying to get location from my android application for a long time. I am still unable to fetch the location. the onLocationChanged is not getting called.
MapsActivity2.java
public class MapsActivity2 extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
//Location location1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(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) {
// 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.
Toast.makeText(this,"Permission Missing",Toast.LENGTH_LONG).show();
return;
}
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng=new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("Bus Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,17.0f));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s)
{
Toast.makeText(MapsActivity2.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
});
}
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng=new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("Bus Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,17.0f));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s)
{
Toast.makeText(MapsActivity2.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
});
}
/*location1=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location1!=null)
{
double latitude = location1.getLatitude();
double longitude = location1.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("Bus Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.0f));
}*/
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
Don't use new LocationListener() in this line locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() .
Create a listener object and use that, or simply use this.
new LocationListener()
is different which you're accessing .
Lots of things could change the result. The first one seems permission, so if the app isn't granted to use them then it'll be returned and wont make any location request.
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;
}
Others could be statuses of providers. So if they are not enabled, wont make any location request too
One for network provider
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
And gps provider
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
This code is also error-prone.
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;
}
You saying there, don't work if gps and network permissions aren't granted. But work if any of them granted.
Then you are making location requests without knowing which one is granted.
Finally, causing the not granted one will throw SecurityException

Can't get user location using Google's LocationServices API

I am trying to get the location from the user but when I put the following request code for the location:
private void getLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
}
}
It crashes because it gets the mLastLocation null
I call the function in the onResume() method but with no success. But if I put it in a button click callback, it gets the location.
Is there any way to get the location once the application has loaded?
First you should check that you have the required permissions to make this request.
You should get user location after you are connected to Google's LocationServices API.
Then you should request location asynchronously using Task returned by FusedLocationProviderClient.getLastLocation()
Here is some code to help you out:
GoogleApiClient mGoogleApiClient;
private void getGoogleApiClient() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(#Nullable Bundle bundle) {
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e(getClass().getName(), "Location permission not granted");
return;
}
Task task = mFusedLocationClient.getLastLocation();
task.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
});
}
#Override
public void onConnectionSuspended(int i) {
Log.e(getClass().getName(), "onConnectionSuspended() ");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.e(getClass().getName(), "Get location failure : " + connectionResult.getErrorMessage());
}
})
.build();
}
mGoogleApiClient.connect();
}
Simply call the method getGoogleApiClient() when you need location.
Do make sure GPS location is activated on your device.
For more infos on this topic:
https://developer.android.com/training/location/retrieve-current.html

Why I can't add markers or zoom in my google maps Android app?

I am currently working on an app with Android studio. This app uses the google maps API.
Recently I managed to initialize the map with my location but for some reason, this does not let me add a marker in my location or make it start with a certain zoom. (You only see a blue dot)
Do you know why? What am I doing wrong?
My map activity code is like this:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
String provider;
LatLng myPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), 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;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = 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;
}
mMap.setMyLocationEnabled(true);
Location location = locationManager.getLastKnownLocation(provider);
if(location != null){
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
myPosition = new LatLng(latitude, longitude);
//mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition,14));
//mMap.addMarker((new MarkerOptions().position(myPosition)));
}
}
#Override
public void onLocationChanged(Location location) {
//mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition,14));
// mMap.addMarker((new MarkerOptions().position(myPosition)));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
}
EDIT:
First of all, thanks to everyone who tried to help me.
Second of all, I couldnt make my app work using all the tools you provided me so right now I still want to use location manager. The other reason for me using this is that I hate Android Studio emulator and my LG G3 only accepts API 21 (I think so)
This is the current code. I think it works fine but whenever it starts it starts in the last known location and not in the actual location. I do not know what to put instead of this --> Location locationActual = locationManager.getLastKnownLocation(provider);;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
String provider;
LatLng myPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), 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;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
/* locationRequest = new LocationRequest();
//locationRequest.setInterval(7500);
//locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);*/
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = 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;
}
mMap.setMyLocationEnabled(true);
Location locationActual = locationManager.getLastKnownLocation(provider);;
if(locationActual != null) {
// Getting latitude of the current location
double latitude = locationActual.getLatitude();
// Getting longitude of the current location
double longitude = locationActual.getLongitude();
// Creating a LatLng object for the current location
myPosition = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 16));
}
}
#Override
public void onLocationChanged(Location location) {
Log.i("TESTTAG", "onLocationChanged called");
LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 16));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
}
Add marker in on LocationChanged.
#Override
public void onLocationChanged(Location location) {
if(mMap != null){
Latlng currentPosition = new Latlng(location.latitude, location.longitude);
mMap.addMarker(new MarkerOptions().position(currentPosition));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 16));
}
}
Instead of LodcationManger Use FusedLocationProviderApi. The advantage of FusedLocationProviderApi is here.
Complete tutorial here.
Okay let's try to do this the new and better way with FusedLocationApi.
You will need these implements.
implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
locationRequest = new LocationRequest();
locationRequest.setInterval(7500);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = 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;
}
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
requestLocationUpdates();
}
private void requestLocationUpdates() {
Log.i("TESTTAG", "requestLocationUpdates");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION
}, 10);
}
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
Log.i("TESTTAG", "Is connected? requestlocationupdates " + String.valueOf(googleApiClient.isConnected()));
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
Log.i("TESTTAG", "onLocationChanged called");
Double myLocationLat = location.getLatitude();
Double myLocationLong = location.getLongitude();
LatLng myLocation = new LatLng(myLocationLat, myLocationLong);
mMap.addMarker(new MarkerOptions().position(myLocation));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
}
This will 100% work for you. It will crash on first run because of permissions (You need to find a good place to actually ask for your permissions)
LocationRequest.setInterval(7500) means that it will ask for your device position ever 7,5 seconds.
If you try to use this in your project i am certain it will work for you

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