onLocationChanged() isn't working properly - java

I'm trying to track users position and draw a path/his route on a map according to his movement (updatePolyline(), updateCamera(), updateMarker() are responsible for drawing a route). Program compiles, but the crucial error is that onLocationChanged() isn't called when location actually changes, thus, no path is beeing drawn.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private PolylineOptions mPolylineOptions;
LocationManager locationManager;
private LatLng mLatLng;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
// LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
this.locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
// if(location != null) {
//
// onLocationChanged(location);
// }
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, this);
}
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
mLatLng = new LatLng(latitude, longitude);
runOnUiThread(new Runnable() {
#Override
public void run() {
updatePolyline();
updateCamera();
updateMarker();
}
});
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
initializeMap();
}
private void updatePolyline() {
mMap.clear();
mMap.addPolyline(mPolylineOptions.add(mLatLng));
}
private void updateMarker() {
mMap.addMarker(new MarkerOptions().position(mLatLng));
}
private void updateCamera() {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16));
}
private void initializeMap() {
mPolylineOptions = new PolylineOptions();
mPolylineOptions.color(Color.BLUE).width(10);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
LocationManager lm = null;
boolean gps_enabled = false, network_enabled = false;
if (lm == null)
lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MapsActivity.this);
dialog
.setTitle("No gps")
.setPositiveButton("Atšaukti", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
})
.setNegativeButton("Open settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MapsActivity.this.startActivity(myIntent);
}
});
AlertDialog alert_dialog = dialog.create();
alert_dialog.show();
}
return false;
}
});
}
}
}

Related

Why my Location return null for the first attempt?

While I install my app first time its always return null Location but IF any other app use location then I re- run the app then my app can get my location address. How can I update location successfully from the first run?
//here is my code
public class UserinfoActivity extends AppCompatActivity implements LocationListener {
private Button button;
private EditText editText_pin, editText_mobile, editText_address;
DatabaseReference databaseReference;
MyPreferences myPreferences;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
Location currentLocation;
Intent intentThatCalled;
public double latitude;
public double longitude;
public LocationManager locationManager;
public Criteria criteria;
public String bestProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userinfo);
databaseReference = FirebaseDatabase.getInstance().getReference("user_responses");
myPreferences = MyPreferences.getPreferences(this);
fusedLocationProviderClient= LocationServices.getFusedLocationProviderClient(this);
intentThatCalled = getIntent();
getLocation();
//optional_check
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
REQUEST_CODE);
}
Task<Location> task=fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location!=null){
currentLocation=location;
}
}
});
public static boolean isLocationEnabled(Context context) {
//...............
return true;
}
protected void getLocation() {
if (isLocationEnabled(UserinfoActivity.this)) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
//You can still do this if you like, you might get lucky:
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;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Log.e("TAG", "GPS is on");
Double latitude = location.getLatitude();
float float_latitude = latitude.floatValue();
myPreferences.setlatitude(float_latitude);
Double longitude = location.getLongitude();
float float_longitude = longitude.floatValue();
myPreferences.setlongitude(float_longitude);
/*Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);*/
}
else{
//This is what you need:
locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
}
}
else
{
//prompt user to enable location....
//.................
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
locationManager.removeUpdates(this);
//open the map:
latitude = location.getLatitude();
longitude = location.getLongitude();
/*Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
This link might help you
http://shaoniiuc.com/android/android-receiving-location-updates-kotlin/
I'm assuming you've already COARSE and FINE locations in your manifest
Or something like this:
Log.d("Find Location", "in find_location");
this.con = con;
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) con.getSystemService(location_context);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
locationManager.requestLocationUpdates(provider, 1000, 0,
new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
});
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
addr = ConvertPointToLocation(latitude, longitude);
String temp_c = SendToUrl(addr);
}
}
}
Call this from any method.
Source: https://stackoverflow.com/a/9873478/13319579

How do I place a custom marker in a google-maps activity from an object information

I want to place a marker on a specific location. At first, I thought this would be simple to do but somehow I'm getting confused and I haven't found something that actually gives me what I need. I've tried to base my activity on whats it's done in this video https://www.youtube.com/watch?v=HD48FBwY9U0
My activity starts by receiving an object information on a getIntent() which I then extract the information. In that object (in this case, a car), there is a lot of properties and 2 of them, are the latitude and longitude. The previous are in Double values.
The problem that I am facing is that I don't know how to input the information that I got from the object into the program. I'm placing the code below. Any suggestions?
public class Geolocalizcao extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentLocationMarker;
public static final int REQUEST_LOCATION_CODE = 99;
public static int REQUEST_ERROR_CODE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geolocalizcao);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
Intent i = getIntent();
CarDataset cardata = (CarDataset) i.getExtras().getParcelable("select");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
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)
{
buildGoogleApiClient();
return;
}
}
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Here!");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
currentLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(3));
if(client != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
public boolean checkLocationPermission()
{
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION_CODE);
}
return false;
}
else
return false;
}
#Override
// When connection is lost...
public void onConnectionSuspended(int i)
{
Toast.makeText(this, "Lost connection. Trying to reconnect...", Toast.LENGTH_SHORT);
client.connect();
}
#Override
// Called when the API client doesnt sucessufly connect
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
if (!connectionResult.hasResolution())
{
GoogleApiAvailability.getInstance().getErrorDialog(this, connectionResult.getErrorCode(), 0).show();
return;
}
try
{
connectionResult.startResolutionForResult(this, REQUEST_ERROR_CODE );
} catch (IntentSender.SendIntentException e)
{
Log.e("LOG", "Exception:", e);
}
}
Here's the class CarDataset that I use:
public class CarDataset implements Parcelable
{
int vehicleID;
String model;
String licencePlate;
String brand;
Double latitude;
Double longitude;
public CarDataset(Integer nVehicleID, String nModel, String nLicencePlate, String nBrand, Double nLatitude, Double nLongitude)
{
this.vehicleID = nVehicleID;
this.model = nModel;
this.licencePlate = nLicencePlate;
this.brand = nBrand;
this.latitude = nLatitude;
this.longitude = nLongitude;
}
public int getVehicleID() {
return vehicleID;
}
public void setVehicleID(int vehicleID) {
this.vehicleID = vehicleID;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getLicencePlate() {
return licencePlate;
}
public void setLicencePlate(String licencePlate) {
this.licencePlate = licencePlate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
#Override
public int describeContents()
{
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeInt(vehicleID);
dest.writeString(model);
dest.writeString(licencePlate);
dest.writeString(brand);
dest.writeDouble(latitude);
dest.writeDouble(longitude);
}
public static final Parcelable.Creator<CarDataset> CREATOR
= new Parcelable.Creator<CarDataset>()
{
public CarDataset createFromParcel(Parcel input)
{
return new CarDataset(input);
}
public CarDataset[] newArray(int size)
{
return new CarDataset[size];
}
};
private CarDataset(Parcel input)
{
vehicleID = input.readInt();
model = input.readString();
licencePlate = input.readString();
brand = input.readString();
latitude = input.readDouble();
longitude = input.readDouble();
}
}
All you need to do is create a LatLng object with the latitude and longitude from the CarDataset object that you get from the Intent.
Marker carMarker;
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (cardata != null) {
LatLng latLngCar = new LatLng(cardata.latitude, cardata.longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLngCar);
markerOptions.title("Car");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
carMarker = mMap.addMarker(markerOptions);
}
//.............
}
You will also need to modify onCreate() so that cardata is an instance variable:
CarDataset cardata;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geolocalizcao);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
Intent i = getIntent();
//use instance variable:
cardata = (CarDataset) i.getExtras().getParcelable("select");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(3));
mMap.addMarker(new MarkerOptions()
.title("Here!")
.icon(BitmapDescriptorFactory.defaultMarker())
.position(latlng_object));

Two classes simple pass variable

i have two simple classes. Main and some kind of gps helper. I'm trying to reach distance when gps posiotion has change (on Location change). It works and Toast good but when i try to save variable dis using setter, and reach it in my MainActivity(last method called ObliczanieOdl) a allways have 0.0. Why? Any suggestions?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
#BindView(R.id.butStop)
Button butStop;
#BindView(R.id.butWynik)
Button butKoniec;
private GoogleMap mMap;
private String dlugosc;
private String szerokosc;
private LatLng StartP, StopP;
private Date czasS;
private DatabaseHelper mDatabaseHelper;
private String adres;
private int Dystans;
private boolean oneStop = false;
private GPStracker gpStracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
ButterKnife.bind(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
Intent intent = getIntent();
gpStracker = new GPStracker(getApplicationContext());
dlugosc = intent.getStringExtra("dlugosc");
szerokosc = intent.getStringExtra("szerokosc");
StartP = new LatLng(Double.parseDouble(szerokosc), Double.parseDouble(dlugosc));
czasS = new Date();
mDatabaseHelper = new DatabaseHelper(this);
mDatabaseHelper.setStartP(getAdres(StartP));//wyciągnięcie adresu rozpoczęcia podróży
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
addMarker(StartP);
}
private void addMarker(LatLng pozycja) {
mMap.addMarker(new MarkerOptions().position(pozycja));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(pozycja)
.zoom(10).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#OnClick(R.id.butStop)
public void butStop() {
if (oneStop == false) {
oneStop = true;
Location location = gpStracker.getlocation();
if (location != null) {
StopP = new LatLng(location.getLatitude(), location.getLongitude());
}
addMarker(StopP);
mDatabaseHelper.setKoniecP(getAdres(StopP)); //wyciągnięcie adresu zakonczenia podróży
//wyciągnięcie odległości i czasu podróży
mDatabaseHelper.setCzasP(String.valueOf(ObliczanieOdl(StartP, StopP)) + " KM " + "w czasie: " + WyliczCzas());
boolean insertData = mDatabaseHelper.addData();
} else {
toastMessage("Twoja podróż została zakończona");
}
}
#OnClick(R.id.butWynik)
public void butKoniec() {
if (oneStop == false) {
toastMessage("Musisz zakończyć podróż wciskając STOP");
} else {
Intent intent = new Intent(MapsActivity.this, ListDataActivity.class);
startActivity(intent);
}
}
public double ObliczanieOdl() {
Double metry = gpStracker.getDis();
return metry;
}
}
and second as a GPS Helper:
public class GPStracker implements LocationListener {
Context context;
double plat;
double plon;
double clat;
double clon;
public double dis;
public GPStracker(Context c) {
context = c;
}
public Location getlocation() {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Uprawnienia nie przyznane", Toast.LENGTH_SHORT).show();
}
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGPSenabled;
isGPSenabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSenabled) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, this);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return location;
} else {
Toast.makeText(context, "Proszę włączyć GPS", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
public void onLocationChanged(Location location) {
clat = location.getLatitude();
clon = location.getLongitude();
if (clat != plat || clon != plon) {
dis += getDistance(plat, plon, clat, clon);
plat = clat;
plon = clon;
setDis(dis);
}
Toast.makeText(context, String.valueOf(dis), Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public double getDistance(double lat1, double lon1, double lat2, double lon2) {
double latA = Math.toRadians(lat1);
double lonA = Math.toRadians(lon1);
double latB = Math.toRadians(lat2);
double lonB = Math.toRadians(lon2);
double cosAng = (Math.cos(latA) * Math.cos(latB) * Math.cos(lonB - lonA)) +
(Math.sin(latA) * Math.sin(latB));
double ang = Math.acos(cosAng);
double dist = ang * 6371;
return dist;
}
public double getDis() {
return dis;
}
public void setDis(double dis) {
this.dis = dis;
}
}

How can I send current location from one activity to another?

I am using map to get current location and now I want to send my current location to another activity which has form to input all the data.
I am confused about which variables and methods I should use to send the location data.
ChooseFromMapActivity
This is the activity where I am getting my current location. And now on Click of useLocation layout I want to send this location to the edit text of another activity i.e GoSendActivity.
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GoSendActivity
This is my GoSendActivity which has edit text view. I want to get the current location on edttxt_from text view.
public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void setUI() {
ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("GO-SEND");
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
edtxt_from=(EditText)findViewById(R.id.editText_from);
edtxt_to=(EditText)findViewById(R.id.editText_to);
edtxt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
edtxt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
}
}
Location class
public class Location {
private int id;
private String mFrom_loc;
private String mTo_loc;
private String mFromloc_details;
private String mToloc_details;
private String mItems_details;
public Location(int id,String mFrom_loc,String mFromloc_details,String mTo_loc,String mToloc_details,String mItems_details)
{
this.id=id;
this.mFrom_loc=mFrom_loc;
this.mFromloc_details=mFromloc_details;
this.mTo_loc=mTo_loc;
this.mToloc_details=mToloc_details;
this.mItems_details=mItems_details;
}
public Location(String mFrom_loc){
this.mFrom_loc=mFrom_loc;
}
public Location(){}
public int getId(int id){return id;}
public String getmFrom_loc(String mFrom_loc){return mFrom_loc;}
public String getmTo_loc(String mTo_loc){return mTo_loc;}
public String getmFromloc_details(String mFromloc_details){return mFromloc_details;}
public String getmToloc_details(String mToloc_details){return mToloc_details;}
public String getmItems_details(String mItems_details){return mItems_details;}
public void setId(){this.id=id;}
public void setmFrom_loc(){this.mFrom_loc=mFrom_loc;}
public void setmTo_loc(){this.mTo_loc=mTo_loc;}
public void setmFromloc_details(){this.mFromloc_details=mFromloc_details;}
public void setmToloc_details(){this.mToloc_details=mToloc_details;}
public void setmItems_details(){this.mItems_details=mItems_details;}
}
How can I achieve this?? Please help..
try this :
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChooseFromMapActivity.this , GoSendActivity.class);
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
}
});
And inside onCreate of GoSendActivity,get latitude and longitude like this :
Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("Latitude");
double longitude = extras.getDouble("Longitude");
}
Now you can set latitude and longitude to your edittext edittext.setText(String.valueOf(latitude));
Apart from passing the data to the next activity using intents, you can also use shared preferences, TinyDB lib achieves great results for caching data. Yoou will need to sync this in your gradle file :
compile 'com.mukesh:tinydb:1.0.1'
then in your onCreate in each activity you will be using the same, initialize the tinyDB by passing application context
TinyDB tinyDB = new TinyDB(getApplicationContext());
With that you can store and retrieve any data within the app using a key-value pair,example to store your coordinates, just call :
tinyDB.putDouble("latitude",latitude);
tinyDB.putDouble("longitude",longitude);
And you can retrieve the data this way:
double latitude = tinyDB.getDouble("latitude");
double longitude = tinyDB.getDouble("longitude");
This class supports all data formats, from Strings,Double,Float and even objects such as ararayLists. Would highly recommend you to try it out.
Make this class as serialisable and put it into intent using bundle.putSerializable("myclaa",location).
Class Location implements Seraializable{
}

Progress Dialog location listener

Within my programme i have a location listner used with the GPS to gain the user current lat/long points.
I want to implement a progress Dialog whilst the GPS gains the co-ordinates.
Currently I call the progressDialog within the onCreate() method then when my location object is nolonger null, then i dismess the progressdialog.
Sadly at the moment the dialog does not show at all.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
***** Call a new progress dialog object when the locationManager is gaining lat/long*****
d = ProgressDialog.show(this, "GPS Posistion", "Gaining GPS posistion...", false, true);
}
private class GPSLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
***** Once lat/long is found, dismiss the progress dialog*****
d.dismiss();
Double latToPass = location.getLatitude();
Double longToPass = location.getLongitude();
locationManager.removeUpdates(locationListener);
locationManager = null;
Intent changesStart = new Intent("com.example.flybaseapp.PassLatLong");
changesStart.putExtra("passedLat", latToPass);
changesStart.putExtra("passedLong", longToPass);
startActivity(changesStart);
}
}
Use AsyncTask
Double latToPass;
Double longToPass;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsyncAction().execute(null, null, null);
}
private class AsyncAction extends AsyncTask<String, Void, String> {
public boolean status = false;
private ProgressDialog pd;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
status = true;
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result) {
pd.dismiss();
Intent changesStart = new Intent("com.example.flybaseapp.PassLatLong");
changesStart.putExtra("passedLat", latToPass);
changesStart.putExtra("passedLong", longToPass);
startActivity(changesStart);
}
}
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
private class GPSLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
latToPass = location.getLatitude();
longToPass = location.getLongitude();
locationManager.removeUpdates(locationListener);
//locationManager = null;
}
}

Categories