how to get latlng from LocationSettingsResponse method? - java

I am Trying to make a map activity that i can choose my current location and make a marke on any location in the map,, i tried to use google documentation but i didn't understand how can i get latlng from this method any one have and idea about that !
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
// ...
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// All location settings are satisfied. The client can initialize
// location requests here.
// ...
}
});

For your problem create a function like follows :
public void centreMapOnLocation(Location location, String title){
if (location != null) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}
}
In onMapReady function add the following code :
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLongClickListener(this);
mMap.clear();
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
centreMapOnLocation(location, "Your Location");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0 , 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centreMapOnLocation(lastKnownLocation, "Your Location");
}else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
}
In the onMapLongClick :
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
String address = "";
try {
List<Address> listAddresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if(listAddresses != null && listAddresses.size() > 0){
if (listAddresses.get(0).getThoroughfare() != null){
address += listAddresses.get(0).getThoroughfare() + " ";
}
address += listAddresses.get(0).getSubThoroughfare() + " ";
}
}catch (Exception e){
e.printStackTrace();
}
if (address.equals("")){
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd-MM-yyyy");
address += sdf.format(new Date());
}
mMap.addMarker(new MarkerOptions().position(latLng).title(address));
SharedPreferences sharedPreferences = this.getSharedPreferences("com.luv.memorableplaces", Context.MODE_PRIVATE);
try {
ArrayList<String> lat = new ArrayList<String>();
ArrayList<String> lng = new ArrayList<String>();
for (LatLng coord : MainActivity.locations){
lat.add(Double.toString(coord.latitude));
lng.add(Double.toString(coord.longitude));
sharedPreferences.edit().putString("latitudes", ObjectSerializer.serialize(lat)).apply();
sharedPreferences.edit().putString("longitudes", ObjectSerializer.serialize(lng)).apply();
}
sharedPreferences.edit().putString("places", ObjectSerializer.serialize(MainActivity.places)).apply();
}catch (Exception e){
e.printStackTrace();
}
Toast.makeText(this, "Location Saved", Toast.LENGTH_SHORT).show();
This will also help you save the previous location. Try it out, it should work.

Related

location does't update after calling update function

I am implementing an android application in java to retrieve Location but the location doesn't update every time i call the function , it always returns me the same positions and i don't understand why.First i collect the position by calling the getCurrentLocation function ,then the callbackLocation function to update the location and finally the onstartLocationUpdates() to call the callbackLocation function; .I also allow all the permission when launching the app. Here is the code i've implemented :
public class TimeService extends Service {
private final static String TAG = TimeService.class.getName();
BroadcastReceiver mReceiver;
private LocationCallback locationCallback;
LocationRequest locationRequest;
FusedLocationProviderClient fusedClient;
double Longitude, Latitude, Altitude;
float Accuracy;
#Override
public void onCreate() {
super.onCreate();
fusedClient = LocationServices.getFusedLocationProviderClient(this);
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, new IntentFilter("sendLocationIntent"));
getCurrentLocation();
callbackLocation();
}
//Here when i am trying to update the location when i receive the upcoming message
private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals("sendLocationIntent")) {
return;
}
onstartLocationUpdates();
String socket_id = intent.getStringExtra("socket_id");
String messageTosend = Latitude + ":" + Longitude + ":" + Altitude + ":" + Accuracy + ":" + socket_id + ":" + globals.getDeviceIMEI(TimeService.this);
;
sendLocationMessageWithStatus();
}
};
protected void sendLocationMessageWithStatus(String phoneNumber, String Msg) {
//Send message block
}
public void getCurrentLocation() {
fusedClient.getLastLocation()
.addOnSuccessListener(getMainExecutor(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
Latitude = location.getLatitude();
Longitude = location.getLongitude();
Accuracy = location.getAccuracy();
}
}
});
//Setting
createLocationRequest();
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(getMainExecutor(), new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// All location settings are satisfied. The client can initialize
// location requests here.
// ...
}
});
}
protected void createLocationRequest() {
locationRequest = new LocationRequest();
LocationRequest.Builder locationRequestBuilder = new LocationRequest.Builder(locationRequest);
locationRequestBuilder.setIntervalMillis(10000);
locationRequestBuilder.setMinUpdateIntervalMillis(5000);
locationRequestBuilder.setPriority(Priority.PRIORITY_HIGH_ACCURACY);
}
private void onstartLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
private void callbackLocation(){
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
Latitude = location.getLatitude();
Longitude = location.getLongitude();
Accuracy = location.getAccuracy();
}
}
};
}
}

How do I draw a repeatable polyline on googleMap?

'''
public class GpsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final int PRIORITY_HIGH_ACCURACY = 100;
private GoogleMap mMap;
private static final int PERMISSIONS_FINE_LOCATION = 99;
Location loc;
LatLng curPo;
boolean state = false;
private LocationRequest locationRequest;
private FusedLocationProviderClient fusedLocationProviderClient;
Button rstart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationRequest = LocationRequest.create()
.setInterval(5000)
.setPriority(PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(5);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(GpsActivity.this);
setContentView(R.layout.activity_gps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
rstart = findViewById(R.id.rstart);
rstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
changeState();
}
});
askforPermission();
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(checkPermission()){
mMap.setMyLocationEnabled(true);
}
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart");
if (checkPermission()) {
Log.d(TAG, "onStart : call mFusedLocationClient.requestLocationUpdates");
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
if (mMap!=null)
mMap.setMyLocationEnabled(true);
}
}
#Override
protected void onStop() {
super.onStop();
if(fusedLocationProviderClient != null){
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
}
// Methods
private void askforPermission(){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){
LocationCallback mCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
for(Location location : locationResult.getLocations()){
setCurrentLocation(location);
}
}
};
fusedLocationProviderClient.requestLocationUpdates(locationRequest,mCallback,null);
fusedLocationProviderClient.removeLocationUpdates(mCallback);
}else{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
}
}
}
private boolean checkPermission() {
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
int hasCoarseLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED &&
hasCoarseLocationPermission == PackageManager.PERMISSION_GRANTED ) {
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSIONS_FINE_LOCATION:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
askforPermission();
}else{
Toast.makeText(this,"this App requires permission for gps", Toast.LENGTH_SHORT).show();
finish();
}
}
}
public void setCurrentLocation(Location location) {
LatLng startLatLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(startLatLng, 15);
mMap.moveCamera(cameraUpdate);
//mMap.addMarker(new MarkerOptions().position(currentLatLng)); //확인용
}
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> savedLocation = locationResult.getLocations();
if(savedLocation.size() > 0){
loc = savedLocation.get(savedLocation.size() - 1);
curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
String curPoLog = "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude();
Log.d(TAG,"OnLocationResult: " + curPoLog);
setCurrentLocation(loc);
}
}
};
public void changeState() {
if(!state){
mMap.clear();
state = true;
Toast.makeText(this, "Recording Start", Toast.LENGTH_SHORT).show();
if(state && checkPermission()){
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
addMarkerSingle();
}
rstart.setText("Stop");
}else{
state = false;
Toast.makeText(this, "Recording Stop", Toast.LENGTH_SHORT).show();
if(!state) {
addMarkerSingle();
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
rstart.setText("Start");
}
}
public void addMarkerSingle(){
if(checkPermission()){
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
double markerLat = location.getLatitude();
double markerLong = location.getLongitude();
LatLng startEnd = new LatLng(markerLat, markerLong);
mMap.addMarker(new MarkerOptions().position(startEnd));
}
});
}
}
}
'''
Hi I'm a noob to programming this is my first project after learning 3month and I have no
idea how to make it happen
I want to draw a real time foot print tracking polyline but no matter what I do, it never works I tried to get a LatLng and draw a polyline from inside LocationCallback and I also tried making a new Thread to handle it I tried in onCreate, onMapReady and everything but it never works. so I came here to ask how you guys handle these kindda stuff.
I know it's shitty code and I know I suck plz understand, among 3 month of lessons java class went for only 2weeks we never even got to using Thread part, plz help me out.
the code above is code with out any errors. I can check my location on real time and there is start marker and end marker. What I want to do is track the paths I walked and show it with polyline. not after i finish I want it to keep updating real time
Thank you for your time and help
You need to store/cache the list of LatLng you get from LocationCallback.
Create a property
private ArrayList<String> myPath = new ArrayList<>();
Now every time a new location is received in the LocationCallback you add it to the myPath and update your map
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> savedLocation = locationResult.getLocations();
if(savedLocation.size() > 0){
loc = savedLocation.get(savedLocation.size() - 1);
curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
String curPoLog = "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude();
Log.d(TAG,"OnLocationResult: " + curPoLog);
setCurrentLocation(loc);
//add this
myPath.add(loc)
updateMap()
}
}
};
Your updateMap() method might look like this
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.addAll(myPath);
polylineOptions.width(10f)
.color(Color.RED)
.geodesic(true);
if(mMap != null {
mMap.addPolyline(polylineOptions);
}
polyLineCollection.addPolyline(polylineOptions)
tempLine.tag = MarkerID(line.id, line.layerId , null)
try this code
//...
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> savedLocation = locationResult.getLocations();
Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
.clickable(false);
for(int i = 0; i<savedLocation.size; i++){
polyline1.add(new LatLng(savedLocation[i].latitude, savedLocation[i].longitude)));
}
// Store a data object with the polyline, used here to indicate an arbitrary type.
polyline1.setTag("A");
// Style the polyline.
stylePolyline(polyline1);
if(savedLocation.size() > 0){
loc = savedLocation.get(savedLocation.size() - 1);
curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
String curPoLog = "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude();
Log.d(TAG,"OnLocationResult: " + curPoLog);
setCurrentLocation(loc);
}
}
};
...//

Shared Preferences not working, Java android

I am unable to save or retrieve data in shared preferences. I have multiple activities.
I am not sure where I went wrong.
When I run the app it works fine except the data is not stored permanently as I wanted it to.
package com.obhan.weather;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
public void centerMapOnLocation(Location location, String title) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
// mMap.clear();
if(title != "Your Location"){
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
}
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 10));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centerMapOnLocation(lastKnownLocation,"Your Location");
}
}
}
#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);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.clear();
mMap.setOnMapLongClickListener((GoogleMap.OnMapLongClickListener) this);
Intent intent = getIntent();
if (intent.getIntExtra("PlaceNumber", 0) == 0) {
//zoom in to users location
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
centerMapOnLocation(location, "Your Location");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT < 23) {
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;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}else
{
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);
centerMapOnLocation(lastKnownLocation,"Your Location");
}
}
}
else{
Location placelocation = new Location(LocationManager.GPS_PROVIDER);
placelocation.setLatitude(MemorablePlaces.locations.get(intent.getIntExtra("PlaceNumber",0)).latitude);
placelocation.setLongitude(MemorablePlaces.locations.get(intent.getIntExtra("PlaceNumber",0)).longitude);
centerMapOnLocation(placelocation,MemorablePlaces.places.get(intent.getIntExtra("PlaceNumber",0)));
//mMap.addMarker(new MarkerOptions().position(MainActivity.locations.get(intent.getIntExtra("placeNumber",0))).title(MainActivity.places.get(intent.getIntExtra("placeNumber",0))));
}
// Toast.makeText(this, intent.getStringExtra("PlaceNumber"), Toast.LENGTH_SHORT).show();
// 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));*/
}
#Override
public void onMapLongClick(LatLng latLng) {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
String address="";
try {
List<Address> listAddress =geocoder.getFromLocation(latLng.latitude,latLng.longitude,1);
if(listAddress!=null && listAddress.size()>0){
if(listAddress.get(0).getThoroughfare()!=null){
Log.i("Address",listAddress.get(0).toString());
address += listAddress.get(0).getThoroughfare();
// address = "";
Log.i("SubThrough", listAddress.get(0).getThoroughfare());
}
if(listAddress.get(0).getSubThoroughfare()!=null){
address +=listAddress.get(0).getSubThoroughfare();
}
// address +=listAddress.get(0).getThoroughfare();
// Log.i("Through",address);
}
} catch (IOException e) {
e.printStackTrace();
}
if(address==""){
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy-MM-dd");
address = sdf.format(new Date());
}
/* if(address=="Unnamed Road"){
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy-MM-dd");
address = sdf.format(new Date());
}*/
mMap.addMarker(new MarkerOptions().position(latLng).title(address));
MemorablePlaces.places.add(address);
MemorablePlaces.locations.add(latLng);
MemorablePlaces.arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.obhan.memorableplaces", Context.MODE_PRIVATE);
try {
ArrayList<String> latitudes = new ArrayList<>();
ArrayList<String > longitudes = new ArrayList<>();
for(LatLng coordinates: MemorablePlaces.locations){
latitudes.add(Double.toString(coordinates.latitude));
longitudes.add(Double.toString(coordinates.longitude));
}
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("places",ObjectSerializer.serialize(MemorablePlaces.places)).apply();
editor.putString("latitudes",ObjectSerializer.serialize(latitudes)).apply();
editor.putString("longitudes",ObjectSerializer.serialize (longitudes)).apply();
editor.commit();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "Location saved", Toast.LENGTH_SHORT).show();
///address="";
}
}
I don't see where you read your preferences and you are sure to not write your preferences .
But I think you don't have to write each time apply().
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("places",ObjectSerializer.serialize(MemorablePlaces.places));
editor.putString("latitudes",ObjectSerializer.serialize(latitudes));
editor.putString("longitudes",ObjectSerializer.serialize(longitudes));
editor.commit(); // or editor.apply()
And if it's not good, see with getApplicationContext(). I don't remember if in java, there's requireContext() (in kotlin yes). And try to replace the context.

How to stop a google map from continuously re-Centering at my location

My problem is related to Google Maps in android. when moving the camera at any point, it returns to my original location instantly, How can I stop that? , You can find my code below
The map starts normally and then for some reason it relocates it self to my original location when i try to navigate the map.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
LocationManager locationmanager ;
LocationListener locationlistener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length> 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationmanager.requestLocationUpdates(locationmanager.GPS_PROVIDER, 0, 0, locationlistener);
Location lastKnownLocation = locationmanager.getLastKnownLocation(locationmanager.GPS_PROVIDER);
centerMpOnLocation(lastKnownLocation, "your Location ");
}
}
}
public void centerMpOnLocation (Location location, String title){
if (location != null){
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
if (title != "your Location") {
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
}
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}else {
Toast.makeText(this, "Wait till we get your Location", Toast.LENGTH_SHORT).show();
}
}
#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);
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;
mMap.setOnMapLongClickListener(this);
Intent intent= getIntent();
if (intent.getIntExtra("placeNumber", 0) == 0){
locationmanager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationlistener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
centerMpOnLocation(location, "your Location");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (Build.VERSION.SDK_INT < 23){
locationmanager.requestLocationUpdates(locationmanager.GPS_PROVIDER, 0, 0, locationlistener);
}else {
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);
centerMpOnLocation(lastKnownLocation, "your Location");
}
}
}else {
Location placeLocation = new Location(locationmanager.GPS_PROVIDER);
placeLocation.setLatitude(MainActivity.locations.get(intent.getIntExtra("placeNumber", 0)).latitude);
placeLocation.setLongitude(MainActivity.locations.get(intent.getIntExtra("placeNumber", 0)).longitude);
centerMpOnLocation(placeLocation, MainActivity.memorablePlaces.get(intent.getIntExtra("placeNumber", 0)));
}
}
#Override
public void onMapLongClick(LatLng latLng) {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
String address = "" ;
try {
List <Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addresses != null && addresses.size() > 0){
if (addresses.get(0).getThoroughfare() != null){
if (addresses.get(0).getSubThoroughfare() != null){
address += addresses.get(0).getSubThoroughfare() + " ";
}
address += addresses.get(0).getThoroughfare();
}
}else if( address == "") { // عشان لو ماعرفتش اطلع عنوان هاحتاج اطلع تاريخ ووقت حاجه بديله يعنى
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy-MM-dd");
address = sdf.format(new Date());
}
} catch (IOException e) {
e.printStackTrace();
}
mMap.addMarker(new MarkerOptions().position(latLng).title(address));
MainActivity.memorablePlaces.add(address);
MainActivity.locations.add(latLng);
MainActivity.arrayAdapter.notifyDataSetChanged();
Toast.makeText(this, "Location Saved", Toast.LENGTH_SHORT).show();
}
}`
Anyone can fix this.
Thanks
You are centering to your location, each time there is a location update.
locationlistener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
centerMpOnLocation(location, "your Location");
}
...
}
Remove centerMpOnLocation(location, "your Location"); or change your logic.

Android: How to get offline current location using GPS provider?

I want to build code which provide current location while user is offline . i created a code in which i use GPS provider but i give current location only while user is online. i want to get current and fresh location of user
Here is code
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener=new LocationListener() {
#Override
public void onLocationChanged(Location location) {
lat=location.getLatitude();
String mm = "";
longitude=location.getLongitude();
locationManager.removeUpdates(this);
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, longitude, 1);
Address obj = addresses.get(0);
mm = obj.getCountryName();
mm=mm+" , "+obj.getSubAdminArea();
mm=mm+" , "+obj.getSubLocality();
mm=mm+" , "+obj.getFeatureName();
Log.v("IGA", "Address" + mm);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] permissions,
int[] grantResults)
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Please define online/offline
I suggest you use: locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListenerGPS, null);
your updated code should be:
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener=new LocationListener() {
#Override
public void onLocationChanged(Location location) {
lat=location.getLatitude();
String mm = "";
longitude=location.getLongitude();
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, longitude, 1);
Address obj = addresses.get(0);
mm = obj.getCountryName();
mm=mm+" , "+obj.getSubAdminArea();
mm=mm+" , "+obj.getSubLocality();
mm=mm+" , "+obj.getFeatureName();
Log.v("IGA", "Address" + mm);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
String[] permissions, int[] grantResults)
return;
}
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListenerGPS, null);

Categories