Unable to show current location on google map automatically? - java

I am trying to show current location on google map on andorid.I have written some cod to do that.But when i launch the app on Map Activity it does not show current location on google map.But when i tap on current location button on google map then it shows the current location.Please why it does not show current location automatically?
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
Log.i("MAP", "AFTER LOCATION");
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider,0, 0, this);

Use this function, when map is ready:
private void centerMap(GoogleMap map, Double latitude, Double longitude){
LatLng latLng = new LatLng(latitude, longitude);
CameraPosition cp = new CameraPosition.Builder()
.target(latLng)
.zoom(13)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
}
You can get coordinates from location like this: location.getLatitude() and Location.getLongitude()

Related

Camera moves back to original position everytime I scroll/pan/drag

I am creating an Android application and have set up a standard Google Maps activity. The application so far just displays the location of the user. The camera is set to focus on the users location initally. I am running into a problem when I try to scroll or drag to a new position on the emulator. I drag and once i lift up the mouse the camera resets to its original position.
onMapReady Code
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mMap.clear();
LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(currentLocation).title("You Are Here"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(currentLocation)
.zoom(25)
.bearing(200)
.tilt(90)
.build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (listAddresses.get(0).getAdminArea() != null) {
String address += listAddresses.get(0).getAdminArea();
}
Toast.makeText(MapsActivity.this, address, Toast.LENGTH_SHORT).show();
Log.i("Address", address);
} catch (Exception e) {
e.printStackTrace();
}
}
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.clear();
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(userLocation)
.zoom(25)
.bearing(0)
.tilt(90)
.build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
This is the code I have to display a marker at current location. I also have code to get AdminArea of current location.
I believe the problem is that my code is runnning constantly so that when I attempt to drag the screen, it just resets to where the camera was originally set. The same occurs for the Toast displaying the current location. This does not update wth new information when i change new location
You are correct. You are setting the camera location in your onLocationChange method, which fires constantly (the user's location doesn't have to change much for this method to fire). So, by setting the camera location to the currentLocation, it will keep scrolling the map. Try commenting that out and see what happens.
public void onLocationChanged(Location location) {
mMap.clear();
LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(currentLocation).title("You Are Here"));
//CameraPosition cameraPosition = new CameraPosition.Builder()
// .target(currentLocation)
// .zoom(25)
// .bearing(200)
// .tilt(90)
// .build();
//mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

Adding Default Location if User Doesn't Allow Permission for a Fine Location for a Map in Android

I am starting to learn about the runtime permissions. I have a map and I made a permission. If user allows fine location - map zooms to his current location, and if he doesn't allow it, the map stays in the place. What I want to do instead of map staying in the place is this: if the user doesn't allow permission for accessing his location, map should zoom in to my custom location (Greenwich).
My maps fragment:
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_LOCATION_REQUEST_CODE);
}
return;
}
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
// == PackageManager.PERMISSION_GRANTED) {
// mMap.setMyLocationEnabled(true);
// } else {
// // Show rationale and request permission.
// }
//Disable Map Toolbar:
mMap.getUiSettings().setMapToolbarEnabled(false);
// Get the name of the best provider and current location
String provider = null;
if (locationManager != null) {
provider = locationManager.getBestProvider(criteria, true);
}
// Get current location
Location myLocation = null;
if (locationManager != null) {
myLocation = locationManager.getLastKnownLocation(provider);
}
// Set default latitude and longitude to Greenwich
double latitude = 51.4825766;
double longitude = -0.0076589;
// Get latitude and longitude of the current location and a LatLng object
if (myLocation != null) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude();
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(14).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
You can zoom to location manually with this code :
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(latitude,
longitude));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
map.moveCamera(center);
map.animateCamera(zoom);
Couldn't find solution so I put the permission inside the parent activity. I think it is a known bug.

Why is google maps not zooming on the Lat/Long I provide?

I have implemented the Google Maps API v2 in my Android app. I add a marker and zoom to level 14 when I open the activity containing the map fragment.
Here is how I add/update the marker:
private void updateMarker() {
if(marker != null){
marker.remove();
}
LatLng latlng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
marker = mMap.addMarker(new MarkerOptions().position(latlng).title(username));
marker.setIcon((BitmapDescriptorFactory.fromResource(R.drawable.marker)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(zoom), 2000, null);
}
It works correctly in debug via Android Studio, using a Nexus 5 with the latest Android installed. The problem is when I run a release build. The marker is added in the correct place, the zoom animation works correctly, zooming to the correct level. But it doesn't move to the marker I added.
Use this
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom));
Or
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom), 2000, null);
Don't call both method right after each other.
you should pass the result value of CameraUpdateFactory.newLatLngZoom(latlng, zoom) to animateCamera which returns a CameraUpdate that moves the center of the screen to a latitude and longitude specified by a LatLng object, and moves to the given zoom level. You can read more about it here
Implement GoogleApiClient.ConnectionCallbacks and override onConnected method as follows:
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
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;
}
mGMLastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGMGoogleApiClient);
try {
// Get LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled)
{
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
//You can still do this if you like, you might get lucky
mGMLastKnownLocation = locationManager.getLastKnownLocation(provider);
if (mGMLastKnownLocation != null) {
//place marker at current position
mMap.clear();
// Get latitude of the current location
double latitude = mGMLastKnownLocation.getLatitude();
// Get longitude of the current location
double longitude = mGMLastKnownLocation.getLongitude();
// Create a LatLng object for the current location
latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(7));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mCurrLocation = mMap.addMarker(markerOptions);
} else {
mGMLocationRequest = new LocationRequest();
mGMLocationRequest.setInterval(5000); //5 seconds
mGMLocationRequest.setFastestInterval(3000); //3 seconds
mGMLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGMGoogleApiClient, mGMLocationRequest, this);
}
} else {
//prompt user to enable location
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
}
} catch (Exception e) {
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
}
Also, implement LocationListener and override the onLocationChanged method as follows:
#Override
public void onLocationChanged(Location location) {
//remove previous current location marker and add new one at current position
if (mCurrLocation != null) {
mCurrLocation.remove();
}
double latitude = location.getLatitude();
double longitude = location.getLongitude();
latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(latitude, longitude)).title("Position").snippet("I am here").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mCurrLocation = mMap.addMarker(markerOptions);
Toast.makeText(this, "Location Changed", Toast.LENGTH_SHORT).show();
//If you only need one location, unregister the listener
LocationServices.FusedLocationApi.removeLocationUpdates(mGMGoogleApiClient, this);
}
I hope it helps!!

get current location on start

I need to display users current locations using gps. At startup it displays some random location in sea and when i'll click to gps icon it displays my current location (white circle with optic icon).
How can I do to display that on startup? I'm new at android/java so feel free to correct me anything.
my code is:
public class MainMapsActivity extends FragmentActivity implements android.location.LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_maps);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
}
Create a data member of Location class.
public static Location mLocation;
use OnMyLocationChangeListener on Map
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mLocation = location;
displayCurrentLocation();
}
});
public void displayCurrentLocation(){
CameraPosition cameraPosition = new CameraPosition.Builder().
target(new LatLng(mLocation.getLatitude(), mLocation.getLongitude())).
tilt(60).
zoom(15).
bearing(0).
build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
hope it will works.
You can achieve this in two ways
Run a service (background operation) and get current latitude and longitude at the app starting itself , before coming to the targeted screen
Expose methods in service which you can access from Activity
Show users current location from the service method input
Or else implement a listener which will every time update the users current location
You can refer the following Example 1 and Example 2

Location value returning null android

I'm trying to get a user's location and I have this method
public Location getCurrentLocation() {
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locManager.getBestProvider(criteria, true);
Location location = locManager.getLastKnownLocation(provider);
return location;
}
I have another method that will center a circle object based on the location variable's latitude and longitude in this method
private void loadMapResources() {
userLocation = getCurrentLocation();
//DRAW CIRCLE HERE
if(userRadius != 0){
Circle radiusCircle = googleMap.addCircle(new CircleOptions()
.center(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
.radius(userRadius)
.strokeWidth(4)
.strokeColor(Color.parseColor("#FF6699"))
.fillColor(Color.parseColor("#66F3F3F3"))
);
//SHOW USER ICON AT CURRENT LOCATION
BitmapDescriptor userIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_user);
googleMap.addMarker(new MarkerOptions()
.title("YOU ARE HERE")
.icon(userIcon)
.position(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
);
}
}
Now this code has worked before on devices with and without GPS. Could anyone tell me why userLocation is throwing a NullPointerException?
Please keep in mind, that getLastKnownLocation can sometimes return null (for example, if provider is currently disabled or there is no last known location), so you should always check the result of this method:
Location location = locManager.getLastKnownLocation(provider);
if (location == null){
//handle this case
//return location with some default coordinates, for example
}
return location;

Categories

Resources