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

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.

Related

my location point appears out of the street google maps eclipse

I developed an application for Android in Eclipse with Google maps. The problem is that the blue dot indicating my current location appears always parallel to the road where I am driving, on roads outside cities. But if you are within the city the point already on top of the road.
I'm using this to get my location on the start of the app:
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location myLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
then I add the blue dot to the map:
googleMap.setMyLocationEnabled(true);
and then I start listening for location changes:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, time, 1, this);
My location change function:
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Lat1 = location.getLatitude();
Long1 = location.getLongitude();
if (Lat1 != Lat || Long1 != Long) {
Lat = location.getLatitude();
Long = location.getLongitude();
if (startNav == true) {
googleMap.animateCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 17));
b = new LatLng(Lat, Long);
if (a != null) {
String urlTopass = makeURL(b.latitude, b.longitude, a.latitude, a.longitude);
new connectAsyncTask(urlTopass).execute();
}
}
}
}
}
My question is why does the blue dot appear parallel to the street instead of on top of it?
Use the FusedLocationProviderAPI. It is recommended over using the older open source Location APIs, especially since you're already using a Google Map so you are already using Google Play Services.
Simply set up a Location Listener, and update your current location Marker in each onLocationChanged() callback. If you only want one location update, just un-register for callbacks after the first callback returns.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()){
buildGoogleApiClient();
mGoogleApiClient.connect();
}
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap retMap) {
map = retMap;
setUpMap();
}
public void setUpMap(){
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
}
#Override
protected void onPause(){
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this,"onConnected", Toast.LENGTH_SHORT).show();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//remove previous current location Marker
if (marker != null){
marker.remove();
}
double dLatitude = mLastLocation.getLatitude();
double dLongitude = mLastLocation.getLongitude();
marker = map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))
.title("My Location").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
}

Google maps Android API and current location

I am trying to implement the google maps API. I want to see my own position on the map and I want that it changes when I move significantly. The problem is that there are no errors but it does not display a marker of my position on the map. This is my onCreate() methode in the .java file
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public static final String TAG = MapPane.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_pane);
// 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);
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}//onCreate
And this is the method I think I am missing here something
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
Log.i(TAG, "loc exists");
if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}//if
}//if
else {
handleNewLocation(location);
}//else
}//onConnected
because I never get into the second if statement. I guess I need the permission of the user first? Turning the gps on manually on my device does not work either. And the method below I used for displaying the marker on the map
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}//handleNewLocation
I used more methods but I think there is no flaw in there. In the AndroidManifest.xml I included
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
You can use LocationManager instead of google api client
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
final Geocoder gc = new Geocoder(this, Locale.getDefault());
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//here you can get current position 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) {
}
};
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
It seems your code is not providing any location to thehandlelocation() method.
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public static final String TAG = MapPane.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
LocationListener li;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_pane);
// Obtain the SupportMapFragment and get notified when the map is reato be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
li=new LocationListener() {
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
getHandledCurrentLocation();
}//onCr
private void getHandledCurrentLocation() {
String locationProvider = LocationManager.NETWORK_PROVIDER;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
Log.e("LOCATION_DEBUG","LOCATION REQUESTED--- ");
LCM.requestLocationUpdates(locationProvider, 10 * 1000, 0,li);
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}//handleNewLocation
this code should work.
I can see few issues with your code. I don't think you are handling the location updates provided by FusedLocationApi. I believe you are implementing LocationListener even though that part of the code is not provided in your question. In that case you are implementing a method 'onLocationChanged(Location location) ' in your activity. This is the method in which you should try to set the new location on the map. Your handleNewLocation method will not be called by FusedLocationApi automatically
You may want to provide the complete code for your activity , then we can help you better.

How to disable google map current location tracking after first loading android

I am google map apis for my current location. I am working on map application in which it first load current position then user can be able to point to any where on the map. My problem is that if i am moving, then my location is again and again moving towards my current position and user is not able to point the desired location on map as it again routes towards its current location. My code is given below, in which i am using code to initialize the map. Your help will be appreciated.
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(8000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.clear();
mMap.setOnMapClickListener(MyLocationActivity.this);
if (mMap != null) {
mMap.setOnMapClickListener(MyLocationActivity.this);
mMap.setMyLocationEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setCompassEnabled(false);
mMap.setIndoorEnabled(true);
mMap.setMapType(mMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(true);
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(getApplicationContext(),
connectionCallbacks, onConnectionFailedListener);
}
}
ConnectionCallbacks connectionCallbacks = new ConnectionCallbacks() {
#Override
public void onDisconnected() {
}
#Override
public void onConnected(Bundle connectionHint) {
showLoadingDialog();
mLocationClient.requestLocationUpdates(REQUEST, locationListener);
}
};
OnConnectionFailedListener onConnectionFailedListener = new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
}
};
OnMyLocationChangeListener onMyLocationChangeListener = new OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
}
};
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
dismissLoadingDialog();
float diff = 0;
if (lastLocation != null) {
diff = location.distanceTo(lastLocation);
}
if ((lastLocation == null) || (diff > 5)) {
LatLng latLng = new LatLng(location.getLatitude(),
location.getLongitude());
CameraPosition cameraPosition = new CameraPosition(latLng, 14,
45, 0);
CameraUpdate cameraUpdate = CameraUpdateFactory
.newCameraPosition(cameraPosition);
mMap.animateCamera(cameraUpdate, 25, null);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.flag));
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
lastLocation = location;
}
}
};
#using_coding there may be many ways to do it, i didn't check this code, but may be it will help you in your scenario.
1: Make a boolean checking in the creation of your activity like:
boolean isFirstTime = true;
In your location listener for the first time make:
mMap.setMyLocationEnabled(true);
And in this column make your isFirstTime to be false and in that block make MyLocationEnabled to be false. In this way if users location is changed then it will check boolean and if it is false then it will not update your current location.
2: Second way is not the solution but you can also do it, like you can set the location request time to be relatively more.

Start the map app with my current location

This is my Activity:
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationManager locationManager;
private String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
addMaracanazinho();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void addMaracanazinho()
{
LatLng pos = new LatLng(-34.642491, -58.642841);
mMap.addMarker(new MarkerOptions()
.title("Maracanazinho")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(pos));
}
private void setUpMapIfNeeded()
{
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null)
{
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
{
mMap.setMyLocationEnabled(true);
}
}
}
}
I want that my app start with a zoom in my current location. I looked for some codes but noone have the answer that I want. Can someone tell me what I should add?
I find this: How would I make my google maps app start with zoom on my current location
But I don't understand how put this in my code.
Thanks and sorry for my bad english.
change your setUpMapIfNeeded method to following and add the rest of code as well. Basically you need to register a LocationListener with the location manager of the system. You get a callback as onLocationChanged(Location l). This Location l is the users position, then you set this new location to your map. Simple.
private void setUpMapIfNeeded()
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, this.locationListener);
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null)
{
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
{
mMap.setMyLocationEnabled(true);
}
}
}
private LocationListener locationListener = new MyLocationListener(){
#Override
public void onLocationChanged(Location location) {
// called when the listener is notified with a location update from the GPS
LatLng userPosition = new LatLng(location.getLatitude(),
location.getLongitude());
if (mMap != null){
mMap .moveCamera(CameraUpdateFactory.newLatLngZoom(userPosition,
15));
}
}
#Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
}
#Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the status of the GPS provider changes
}
};
Used animateCamera for that like
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longitude), 18.0f));
In your MapsActivity file -> Change setUpMapIfNeeded() function:
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationManager locationManager;
private String provider;
...
private void setUpMapIfNeeded()
{
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null)
{
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
{
mMap.setMyLocationEnabled(true);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()))
.zoom(14).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}
}
You can also set the Zoom by setting the number (Here Zoom is 14).

Android Real Time Location Tracking

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

Categories

Resources