Location in Map Activity not set immediately? - android

What I want is my map activity to zoom to the users current location when the map is opened. If I enable location services before running the app, it works fine. When I disable location services and run my app, I have a prompt for the user to turn on location services. It takes them to settings to turn it on, and when they hit back, the map should zoom to their current location. I've placed my zoomToLocation in setUpMap(), which is called in OnResume(), but for whatever reason it doesn't seem to work.
Code:
Location Services check:
private boolean checkLocationEnabled() {
//credits: http://stackoverflow.com/questions/10311834/how-to-check-if-location-services-are-enabled
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!gpsEnabled) {
AlertDialog.Builder gpsAlertBuilder = new AlertDialog.Builder(this);
gpsAlertBuilder.setTitle("Location Services Must Be Turned On");
gpsAlertBuilder.setMessage("Would you like to turn them on now? (Note: if not, you will be unable to use the map to find breweries. You will still be able to search for them.");
gpsAlertBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent enableGPSIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(enableGPSIntent);
}
});
gpsAlertBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog gpsAlert = gpsAlertBuilder.create();
gpsAlert.show();
}
return gpsEnabled;
}
Zoom and zoomToLocation() methods:
private void zoom(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom// Sets the orientation of the camera to east// Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
private void zoomToLocation() {
//credits: http://stackoverflow.com/questions/18425141/android-google-maps-api-v2-zoom-to-current-location
//http://stackoverflow.com/questions/14502102/zoom-on-current-user-location-displayed/14511032#14511032
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null) {
zoom(location);
} else {
return;
}
}
setUpMap method:
private void setUpMap() {
UiSettings settings = mMap.getUiSettings();
settings.setZoomControlsEnabled(true);
settings.setZoomGesturesEnabled(true);
mMap.setMyLocationEnabled(true);
settings.setMyLocationButtonEnabled(true);
setUpActionBar();
if(checkLocationEnabled()) {
zoomToLocation();
}
}
OnResume method:
protected void onResume() {
super.onResume();
setUpMapIfNeeded(); //setUpMap called in setUpMapIfNeeded
}
And finally mySetUpMapIfNeeded() method:
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) {
setUpMap();
setUpActionBar();
}
}
}

Your setUpMapIfNeeded() onResume is probably called.
But in your setUpMapIfNeeded you only call setUpMap() if first mMap is null. Which isn't null when you resume your application. You have to set zoom level using some other function as well other than inside setUpMap().
Something like this.
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) {
setUpMap();
setUpActionBar();
}
}
else{
//setup zoom level since your mMap isn't null.
}
}

Related

Google map is not visible in android app

I used this code to show my location on map but map is not visible in app. App is running fine. I don't know what i am doing wrong. please help me.Thanks in advance.
public class MapsActivity extends FragmentActivity implements LocationListener,OnMapReadyCallback{
GoogleMap mMap;
LatLng myPosition;
Location location;
LocationManager locationManager;
double latitude = 0, longitude = 0;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// mMap = mapFragment.getMap();
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap mMap) {
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;
}
mMap.setMyLocationEnabled(true);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
alertDialog.setTitle("GPS Is Off");
alertDialog.setMessage("Please Enable GPS for better Location");
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
{
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 100f, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 100f, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
/* String provider = locationManager.getBestProvider(criteria, true).toString();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 100.0f, this);
// locationManager.requestLocationUpdates(provider, 1000, 10f, this);
location = locationManager.getLastKnownLocation(provider);*/
//Toast.makeText(getApplicationContext(),provider,Toast.LENGTH_LONG).show();
if (location != null) {
onLocationChanged(location);
}
// latitude = location.getLatitude();
// longitude = location.getLongitude();
myPosition = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(myPosition));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 16));
Timer t = new Timer(false); //To show text for required time
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
dialogbox();
}
});
}
}, 10000);
}
}
And also mMap.getMyType gives '1' value means normal map. But map is not visible. Further I pass latitude and longitude value to another activity. In that activity it will print address of latitude and longitude provided. This part is working fine,it means app is correctly locating my location but map is not visible.

Android Studio Google Maps how to redirect camera to my current location when i open my application

The Camera Animation is not working its not directing to my location when I open my Application and it does not add a Marker either
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
Here it wont direct my camera in my current location. When I open my application it starts at the center of the map not my location
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();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMapIfNeeded();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
LatLng target = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition position = this.mMap.getCameraPosition();
CameraPosition.Builder builder = new CameraPosition.Builder();
builder.zoom(15);
builder.target(target);
this.mMap.animateCamera(CameraUpdateFactory.newCameraPosition(builder.build()));
mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("You are here!").snippet("Consider yourself located"));
}
}
}
You have few huge super basic errors:
First onResume is only called when activity in the baground comes to the foreground. Put setUpMapIfNeeded() Inside onCreate as well.
Second in your function setUpMapIfNeeded() in the last if statement instead of putting setUpMap() you put setUpMapIfNeeded() change that and it should work.
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
Here is your code modified:
Part 1
#Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
Part 2
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();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new.MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
LatLng target = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition position = this.mMap.getCameraPosition();
CameraPosition.Builder builder = new CameraPosition.Builder();
builder.zoom(15);
builder.target(target);
this.mMap.animateCamera(CameraUpdateFactory.newCameraPosition(builder.build()));
mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("You are here!").snippet("Consider yourself located"));
}
}
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng l = new LatLng(location.getLatitude(), location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(l, mMap.getCameraPosition().zoom));
}
});
}
Just change this 2 methods

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 Google Maps API V2 Zoom to Current Location

I'm trying to mess around with the Maps API V2 to get more familiar with it, and I'm trying to start the map centered at the user's current location. Using the map.setMyLocationEnabled(true); statement, I am able to show my current location on the map. This also adds the button to the UI that centers the map on my current location.
I want to simulate that button press in my code. I am familiar with the LocationManager and LocationListener classes and realize that using those is a viable alternative, but the functionality to center and zoom in on the user's location seems to already be built in through the button.
If the API has a method to show the user's current location, there surely must be an easier way to center on the location than to use the LocationManager/LocationListener classes, right?
Try this coding:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
After you instansiated the map object (from the fragment) add this -
private void centerMapOnMyLocation() {
map.setMyLocationEnabled(true);
location = map.getMyLocation();
if (location != null) {
myLocation = new LatLng(location.getLatitude(),
location.getLongitude());
}
map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
Constants.MAP_ZOOM));
}
if you need any guidance just ask but it should be self explantory - just instansiate the myLocation object for a default one...
youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));
16 is the zoom level
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});
try this code :
private GoogleMap mMap;
LocationManager locationManager;
private static final String TAG = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
arrayPoints = new ArrayList<LatLng>();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
LatLng myPosition;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
LatLng coordinate = new LatLng(latitude, longitude);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 19);
mMap.animateCamera(yourLocation);
}
}
}
Dont forget to add permissions on AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Here's how to do it inside ViewModel and FusedLocationProviderClient, code in Kotlin
locationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let {
val position = CameraPosition.Builder()
.target(LatLng(it.latitude, it.longitude))
.zoom(15.0f)
.build()
map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
}
}
private void setUpMapIfNeeded(){
if (mMap == null){
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();//invoke of map fragment by id from main xml file
if (mMap != null) {
mMap.setMyLocationEnabled(true);//Makes the users current location visible by displaying a blue dot.
LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);//use of location services by firstly defining location manager.
String provider=lm.getBestProvider(new Criteria(), true);
if(provider==null){
onProviderDisabled(provider);
}
Location loc=lm.getLastKnownLocation(provider);
if (loc!=null){
onLocationChanged(loc);
}
}
}
}
// Initialize map options. For example:
// mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
#Override
public void onLocationChanged(Location location) {
LatLng latlng=new LatLng(location.getLatitude(),location.getLongitude());// This methods gets the users current longitude and latitude.
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));//Moves the camera to users current longitude and latitude
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng,(float) 14.6));//Animates camera and zooms to preferred state on the user's current location.
}
// TODO Auto-generated method stub
check this out:
fun requestMyGpsLocation(context: Context, callback: (location: Location) -> Unit) {
val request = LocationRequest()
// request.interval = 10000
// request.fastestInterval = 5000
request.numUpdates = 1
request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
val client = LocationServices.getFusedLocationProviderClient(context)
val permission = ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION )
if (permission == PackageManager.PERMISSION_GRANTED) {
client.requestLocationUpdates(request, object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
val location = locationResult?.lastLocation
if (location != null)
callback.invoke(location)
}
}, null)
}
}
and
fun zoomOnMe() {
requestMyGpsLocation(this) { location ->
mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(
LatLng(location.latitude,location.longitude ), 13F ))
}
}
This is working Current Location with zoom for Google Map V2
double lat= location.getLatitude();
double lng = location.getLongitude();
LatLng ll = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
In kotlin, you will get the current location then move the camera like this
map.isMyLocationEnabled = true
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude, location.longitude), 14f))
}
}
Also you can animate the move by using this function instead
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.latitude, location.longitude), 14f))

Categories

Resources