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;
}
}
Related
Im trying to get realtime location with pointing on the Google Map. Currently i successfully get the latitude and longitude in realtime and it will update everytime to a getter, setter class called sosrecord.getLatitude() and sosrecord.getLongitude(). I want to point the google map based on the updated latitude and longitude. But everytime when i put the getter on the LatLng latLng = new LatLng(sosrecord.getLatitude(), sosrecord.getLongitude()); it will return me Null and eventually crash the app due to java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference It should point the current location when user click on a button. Sorry if the code sample below is messy, hope someone could help me with this issue. Thanks.
Main.java
public class MainActivity extends FragmentActivity{
private Handler mHandler = new Handler();
DatabaseReference reff;
SosRecords sosrecords;
boolean startclicked =true;
String selectedOfficer = "Police";
private static final String TAG = "MainActivity";
int LOCATION_REQUEST_CODE = 1001;
SupportMapFragment smf;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult <------This function will get the lat and long and set the value to sosrecordlocationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
double lat = location.getLatitude();
double lon = location.getLongitude();
sosrecords.setLatitude(lat);
sosrecords.setLongitude(lon);
}
}
};
private void showOptionDialog() {
String[] officers = {"Police", "Hospital", "Bomba"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Choose SOS types");
builder.setSingleChoiceItems(officers, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedOfficer = officers[which];
}
});
builder.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
sosrecords.setCallFor(selectedOfficer);{
onStart();
startclicked= false;
//GET ALL INFORMATION FROM FIRESTORE AND SEND TO REALTIME DATABASE
if(FirebaseAuth.getInstance().getCurrentUser()!= null){
DocumentReference df = FirebaseFirestore.getInstance().collection("Users").document(FirebaseAuth.getInstance().getCurrentUser().getUid());
df.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.getString("FullName")!= null){
String id = reff.push().getKey();
Log.d(TAG, "asdasd"+id);
SosRecords sosRecords = new SosRecords(documentSnapshot.getString("FullName"), (documentSnapshot.getString("PhoneNumber")), (documentSnapshot.getString("UserEmail") ),sosrecords.getLatitude(),sosrecords.getLongitude(),sosrecords.getCallFor() );
reff.child(id).setValue(sosRecords);
sosrecords.setRecordID(id);
btnStartSOS.setEnabled(false);
btnStopSOS.setEnabled(true);
Toast.makeText(MainActivity.this, "You're are now activating SOS request !", Toast.LENGTH_SHORT).show();
LatLonLoop.run();
smf.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(sosrecords.getLatitude(),sosrecords.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Here");
googleMap.addMarker(markerOptions);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),Login.class));
finish();
}
});
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
checkSettingsAndStartLocationUpdates();
}else{
askLocationPermission();
}
}
dialog.dismiss();
}
});
My get/set class
package com.example.sossystem;
public class SosRecords {
String RecordID;
String FullName;
String PhoneNumber;
String EmailAddress;
Double Latitude;
Double Longitude;
String CallFor;
public SosRecords(){
}
public SosRecords(String fullName, String phoneNumber, String userEmail, Double latitude, Double longitude, String callFor) {
FullName = fullName;
PhoneNumber = phoneNumber;
EmailAddress = userEmail;
Latitude = latitude;
Longitude = longitude;
CallFor = callFor;
}
public String getRecordID() {
return RecordID;
}
public void setRecordID(String recordID) {
RecordID = recordID;
}
public String getFullName() {
return FullName;
}
public void setFullName(String fullName) {
FullName = fullName;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
PhoneNumber = phoneNumber;
}
public String getEmailAddress() {
return EmailAddress;
}
public void setEmailAddress(String emailAddress) {
EmailAddress = emailAddress;
}
public Double getLatitude() {
return Latitude;
}
public void setLatitude(Double latitude) {
Latitude = latitude;
}
public Double getLongitude() {
return Longitude;
}
public void setLongitude(Double longitude) {
Longitude = longitude;
}
public String getCallFor() {
return CallFor;
}
public boolean setCallFor(String callFor) {
CallFor = callFor;
return false;
}
}
The thing is that when you open MainActiity that time onMapReady() called first automatically before LocationCallback. Eventually, it will return null latitude and Longitude.
However, your problem is that you haven't assigned your map fragment.
first of all, you need to assign in onLocationResult() below the for loop.
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(MapsActivity.this);
Secondly, remove smf.getMapAsync() from onMapReady().
Instead of,
smf.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(sosrecords.getLatitude()
,sosrecords.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().
position(latLng).title("Here");
googleMap.addMarker(markerOptions);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
});
Replace,
// declare googlemap as a globally
private GoogleMap mMap;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng latLng = new LatLng(sosrecords.getLatitude()
,sosrecords.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().
position(latLng).title("Here");
googleMap.addMarker(markerOptions);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
});
I am trying to save two Strings (latitude and longitude) to pass them into a String 'URL'.
However, I keep getting null values once I exit the onLocationChanged method and I'm not sure why.
When inside the onLocationChanged method, the values appear to be stored and display correctly in the console, but further in the code they return null when in the console and I have no idea why. Can someone please help?
public void getTransport(View v) {
String[] requiredPermissions = {
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
boolean ok = true;
for (int i = 0; i < requiredPermissions.length; i++) {
int result = ActivityCompat.checkSelfPermission(this, requiredPermissions[i]);
if (result != PackageManager.PERMISSION_GRANTED) {
ok = false;
}
}
if (!ok) {
ActivityCompat.requestPermissions(this, requiredPermissions, 1);
// that last parameter MUST be >0, or it fails silently
System.exit(0);
} else {
// doStuffThatNeedsPermissions();
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
String latitude = Double.toString(lat);
//latitude = latitude.substring(0,6);
String longitude = Double.toString(lng);
//longitude = longitude.substring(0,6);
String URL = "http://10.0.0.2:8080/stations?latitude=" + latitude +"&longitude=" + longitude + "&type=all";
System.out.println(URL);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});
}
System.out.println(URL);
ConnectivityManager ConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = ConnMgr.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected())
{
// fetch data
Log.d("test", "TEST");
AsyncTask task = new AsyncTask(this);
//task.execute;
task.execute(URL);
}
else
{
//output.setText(" test ");
}
}
Thank you in advance for any advice,
This is a threading issue. Your code to return the location is evaluated before the code to set the fields, thats why its null.
Separate the two ideas:
public void logLocation(View v){
System.out.println("LAT IS: "+ lati);
System.out.println("Long IS: "+ longi);
}
public void getTransport(View v){
getLocation();
}
// Get current location method
private void getLocation() {
String[] requiredPermissions = {
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
boolean ok = true;
for (int i = 0; i < requiredPermissions.length; i++) {
int result = ActivityCompat.checkSelfPermission(this, requiredPermissions[i]);
if (result != PackageManager.PERMISSION_GRANTED) {
ok = false;
}
}
if (!ok) {
ActivityCompat.requestPermissions(this, requiredPermissions, 1);
// that last parameter MUST be >0, or it fails silently
System.exit(0);
} else {
// doStuffThatNeedsPermissions();
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
TextView laititude = (TextView) findViewById(R.id.Lat);
TextView longitude = (TextView) findViewById(R.id.Long);
laititude.setText("" + lat);
longitude.setText("" + lng);
lati = (laititude.getText().toString());
longi = (longitude.getText().toString());
Log.d("Running", "looping");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});
}
}
I've shown you how its done simply, by adding another button. 1 button starts to monitor for new locations, and the other will print out the location (null if you press the button to early, but wait a bit and press it again).
Your alternative choice, is a callback mechanism across the threads:
interface MyCallback {
void onLocationRetrieved(double lati, double longi);
}
public void getTransport(View v){
getLocation(new MyCallback() {
#Override
public void onLocationRetrieved(double lati, double longi) {
System.out.println("LAT IS: "+ lati);
System.out.println("Long IS: "+ longi);
}
});
}
private void getLocation(MyCallback callback) {
String[] requiredPermissions = {
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
boolean ok = true;
for (int i = 0; i < requiredPermissions.length; i++) {
int result = ActivityCompat.checkSelfPermission(this, requiredPermissions[i]);
if (result != PackageManager.PERMISSION_GRANTED) {
ok = false;
}
}
if (!ok) {
ActivityCompat.requestPermissions(this, requiredPermissions, 1);
// that last parameter MUST be >0, or it fails silently
System.exit(0);
} else {
// doStuffThatNeedsPermissions();
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
callback.onLocationRetrieved(lat, lng);
Log.d("Running", "looping");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});
}
}
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));
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;
}
});
}
}
}
I have two classes.. First.java and Second.java,
In the First class.. latitude, longitude, and address show correctly in TextView.
But in Second class, latitude and longitude become 0.0 , address becomes null.
Can anyone help me why?
Here's the code for First.java
public class First extends Activity {
private Context context=null;
AppLocationService appLocationService;
String address;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_location);
context=this;
appLocationService = new AppLocationService(First.this);
btngetLocation=(Button)findViewById(R.id.button_getLocation);
btngetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// getting GPS status
boolean isGPSEnabled = appLocationService
.getStatus(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = appLocationService
.getStatus(LocationManager.NETWORK_PROVIDER);
if( isGPSEnabled==false && isNetworkEnabled==false){
showSettingsAlert("Location Service");
}
else {
Toast.makeText(
getApplicationContext(),
"Attempt to get location...Please Wait.. ",
Toast.LENGTH_LONG).show();
if( isNetworkEnabled ==true ){
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation == null){
Toast.makeText(
getApplicationContext(),
"Network bermasalah.. Pastikan Anda terkoneksi Internet, dan coba get Location lagi",
Toast.LENGTH_LONG).show();
}
else {
latitude = nwLocation.getLatitude();
longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
}
}
else {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation == null){
Toast.makeText(
getApplicationContext(),
"GPS bermasalah.. Silahkan di ruangan terbuka atau aktifkan network provider Anda, dan coba get Location lagi",
Toast.LENGTH_LONG).show();
}
else {
latitude = gpsLocation.getLatitude();
longitude = gpsLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (GPS): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
}
}
}
}
});
}
public class AppLocationService extends Service implements LocationListener{
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10; //10 meter
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 3; //3 menit
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public boolean getStatus(String provider){
return locationManager.isProviderEnabled(provider); /
}
public Location getLocation(String provider) {
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
locationManager.removeUpdates(this);
return location;
}
return null;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
public String getAddress(Context ctx, double latitude, double longitude) {
// StringBuilder result = new StringBuilder();
String alamat=null;
try {
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
String jalan = (address.getAddressLine(0));
String locality=address.getLocality();
String country=address.getCountryName();
String country_code=address.getCountryCode();
String zipcode=address.getPostalCode();
alamat = jalan +", "+ locality +", "+ country+", " + country_code+", " + zipcode;
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return alamat;
}
public double getLatitude(){
return latitude;
}
public double getLongitude(){
return longitude;
}
public String getAlamat(){
return address;
}
Here's Second. java
public class Second extends Activity{
AddLocation data_dr_location;
Double latitude;
Double longitude;
String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_description);
data_dr_location = new AddLocation();
address= data_dr_location.getAlamat();
latitude = data_dr_location.getLatitude();
longitude = data_dr_location.getLongitude(); }
In your first java, there is only getter method and no setter method!
private double latitude;
private double longitude;
private String address;
public double getLatitude(){
return latitude;
}
public double getLongitude(){
return longitude;
}
public String getAlamat(){
return address;
}
/* THE BELOW SETTER METHODS ARE MISSING IN YOUR CODE.*/
public void setLatitude(double latitude){
this.latitude = latitude;
}
public void setLongitude(double longitude){
this.longitude=longitude;
}
public setAlamat(String address){
this.address=address;
}
At appropriate location (say whereever you get lat/long/address), add these lines.
latitude = nwLocation.getLatitude();
setLatitude (latitude);
longitude = nwLocation.getLongitude();
setLongitude (longitude);
your are only getting value.means you have written getter mehtod. you have not set value using setter method. please try that and check.
public void setLatitude(double latitude){
this.latitude = latitude;
}
public void setLongitude(double longitude){
this.longitude=longitude;
}
public setAlamat(String address){
this.address=address;
}