I have this code:
Location newLocation = new Location(LocationManager.GPS_PROVIDER);
Location oldLocation = new Location(LocationManager.GPS_PROVIDER);
float distanceTravelled=0;
onLocationChanged:
#Override
public void onLocationChanged(Location location)
{
oldLocation.set(newLocation);
startactivity();
distanceTravelled+=newLocation.distanceTo(oldLocation);
String stringDistance= Float.toString(distanceTravelled);
TextView distance = (TextView) findViewById(R.id.textDistance);
distance.setText(stringDistance);
}
startactivity:
public void startactivity()
{
GPSTracker gps = new GPSTracker(Live.this);
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
}
else
{
gps.showSettingsAlert();
}
}
GPSTracker is a separate class which gets the current latitude and longitude (it is working fine!).
GPS updates at min. distance 5 metres and min. time 5 seconds.
Here is my full GPSTracker class: GPSTracker.java
I have added the three permissions in the manifest: fine,coarse and internet.
My problem is the textview inside onLocationChanged never gets changed.
What is the problem? Is onLocationChanged not getting called or there is some logical error (distance always remains zero)?
And how to fix that?
Your function is
public void onLocationChanged(Location location)
but you are not using that parameter anywhere in the function.
It looks like you should add
newLocation.set(location);
after the first line of your function.
At the moment you are calculating the distance between the starting point and itself, and that will always be 0.
Related
I'm trying to make an app that will use an Place autocomplete fragment in one activity and when I select a place in it, on a click of a button, I'm supposed to open another activity (Google Maps activity) and it's supposed to get the location that I chose in the first one. I've tried passing Longitude and Latitude from Main class to Maps class, but it just crashes my app. Anyone have any idea how to fix?
Thank you in advance!
EDIT: Sample of what I've tried so far:
/*This is the main class where my autocomplete fragment is*/
Double Lat;
Double lang;
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
// Lat = place.getLatLng().latitude;
// lang = place.getLatLng().longitude;
setLang(place.getLatLng().longitude);
setLat(place.getLatLng().latitude);
Log.i(TAG, "Place: " + place.getName());
}
public void setLang(Double langg){
this.lang = langg;
}
public void setLat(Double Latt){
this.Lat = Latt;
}
public Double getLang(){
return lang;
}
public Double getLat(){
return Lat;
}
/* This is the maps class */
MainActivity maAct;
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng place = new LatLng(maAct.getLat(), maAct.getLang());
// LatLng paris = new LatLng(48.8566, 2.3522);
mMap.addMarker(new MarkerOptions().position(place).title("Marker inPlace"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place));
}
Ok, you may consider to pass the latitude and longitude by Intent.
// MainActivity
Intent intent = new Intent(MainActivity.this, MapActivity.class);
intent.putExtra("lat", Lat);
intent.putExtra("lng", lang);
startActivity(intent);
And..
// Map Activity onMapReady
double lat = getIntent().getDoubleExtra("lat", DEFAULT_LAT);
double lng = getIntent().getDoubleExtra("lng", DEFAULT_LNG);
LatLng place = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(place).title("Marker inPlace"));
You cannot getValue by maAct, your concept is incorrect.
First if you just
MainActivity maAct;
maAct is not assigned any 'value', so that if you call any methods of maAct, you will get NullPointerException.
Besides, if you really give it a 'value',
// it is totally wrong, just an example only
MainActivity maAct = new MainActivity();
But it is not the same reference so that you cannot get the values you stored before.
What i understand is you want to navigate to the passed latitude and longitude.Here is a sample
String uri = String.format(Locale.ENGLISH, "google.navigation:q=%f,%f", Double.parseDouble(latitude), Double.parseDouble(longitude));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
if(intent.resolveActivity(context.getPackageManager())!=null)
context.startActivity(intent);
You can find more info like creating markers and all here
Edit:
As per your code you want to set the marker.Here is the steps and sample for a working marker example.
Firstly sorry for asking so many questions here the past couple of weeks, I'm new to android studio and finding it tough to figure out a lot of the core concepts by myself.
In regards to the question, I have a project set up so whatever you type into the "1.2, -1.2" ect parameters you will find you the distance between two places and your answer will be displayed as a toast. However, I want the latitudes and longitueds to be variables.
Button button1=(Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Double distance = 1.0;
int val = 1;
Toast.makeText(getApplicationContext(), "You are " + String.valueOf(distance
(1.2, -1.2, 1.3, -2.4, "K")) + "kilometers away from the flag", Toast.LENGTH_LONG).show(); }
});
I have the following two methods and I want the values LatLng and currentLatitude and currentLongitude doubles for the parameters above.
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(53.3835,6.5996)).title("Marker"));
}
and
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
Any insight on how to do it would be much appreciated. From what I've read I know I'll need to split the LatLng variable into strings but thats all I can think of so far
If those 2 methods are in the same class then just make those 2 variables attributes of that class, else you will need to pass them to the corresponding classes. I will demonstrate in a simpler example than your code :
public class MyClass(){
private int lat;
private int longt;
//constructors ,setters and getters
public void method1(){
//affecting those attributes with values
lat = 1;
longt = 2;
}
public void method2(){
//simply access the attributes
System.out.println("lat "+lat+" longt "+longt);
}
}
Reading the comments , I think I need to further explain to you that when a variable is declared inside a method, it is local to that method, and therefor it will be "destroyed" (garbage collected or w.e) when that method is done doing it's job. But when a variable is declared outside a method, like the class's attributes, you can still refer to it whenever you need to, until the instance of that class is "destroyed".
I have a class which extends from AsyncTask and gets data in JSON format from a web service. My android app has to retrieve data asynchronously whenever the location is changed. My android activity implements LocationListener and I am invoking the asynchronous execution in onLocationChanged() method. I have tried setting zero for both minTime and minDistance parameters of requestLocationUpdates() method but the data which is to be retrieved asynchronously is never retrieved.
The code for my onCreate() and onLocationChanged() methods is given below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
}
#Override
public void onLocationChanged(Location location) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLatitude());
new MyAsyncTask().execute();
}
The latitude and longitude variables are used in the MyAsyncTask class for getting data with respect to user's current location.
Please tell me what's wrong with my code. I have been looking for the solution since last week but haven't found any.
oke, a little bit confused but let me understand it. You retrieve the data in onLocationChanged() ? example long=111 lat=222 and with your Asyntask you make a GET request to a WS with a json parameter probably long and lat and some other stuff in it ? and if you try to debugg it there are some values in logcat ? or some error ? or did you put the permision in the manifest file ? or in the phones settings ?
did tried debugging??
or
Log??
are you getting any error???
sometimes the location.getLatitute() and location.getLatitute() returns null which may cause null pointer Exception..
that may stopped reaching the MyAsyncTask()
check this may help you..
#Override
public void onLocationChanged(Location location) {
double latit =null;
double longi =null;
do
{
latit=location.getlatitude();
longi=location.getlongitude();
}while(latit!=null && longi!=null);
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLatitude());
new MyAsyncTask().execute();
}
The getlatitude() and getlongitude() function will return double value check this documentation
http://developer.android.com/reference/android/location/Location.html#getLatitude()
Oops My Bad!
The correct code is
#Override
public void onLocationChanged(Location location) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
new MyAsyncTask().execute();
}
I have a separate class GPSTracker.java which returns the current latitude and longitude.
public class Live extends Activity implements LocationListener
{
GPSTracker gps;
Location newLocation = new Location(LocationManager.GPS_PROVIDER);
Location oldLocation = new Location(LocationManager.GPS_PROVIDER);
float distanceTravelled=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
startactivity();
}
startactivity:
public void startactivity()
{
gps = new GPSTracker(Live.this);
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
}
else
{
gps.showSettingsAlert();
}
}
Whenever I do that commented out part, it gives an exception even if I declare the location outside the startactivity() in the Live class. Otherwise it displays the correct latitude and longitude.
I want to use it to calculate distance travelled, like this:
#Override
public void onLocationChanged(Location location)
{
oldLocation.set(newLocation);
startactivity();
distanceTravelled+=newLocation.distanceTo(oldLocation);
String stringdistance= Float.toString(distanceTravelled);
TextView distance = (TextView) findViewById(R.id.textDistance);
distance.setText(stringdistance);
}
Is that logic correct?
And the onLocationChanged() does not finds the newLocation in the startactivity(). How can I do that?
But first thing is I get an exception when I use location in startactivity().
But first thing is I get an exception when I use location in startactivity().
Location newLocation;
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
You are trying to execute above code, but see newLocation is null (by default value) and you are trying to use null instead of Object and it results in NullPointerException.
In order to create a new object in Java, you have to use:
Location newLocation = new Location("test");
You are trying to set the longitude and latitude to a non-object. This creates a NullPointerException. You have to create the ojbect location before you use it.
I'm building an app that allows a user to set a proximity alarm by selecting a marker and clicking on the info window to confirm. I need to be able to get the latitude and longitude from the marker so I can use the coordinates to set up the radius.
googleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener(){
public void onInfoWindowClick(Marker marker) {
//click function
Toast.makeText(getBaseContext(),
"Info Window clicked#" + marker.getPosition(),
Toast.LENGTH_SHORT).show();
LocationManager lm;
double lat=0;
double long1=0; //Defining Latitude & Longitude
float radius=3000;
lm=(LocationManager) getSystemService(LOCATION_SERVICE);
Intent i= new Intent("com.example.sleepertrain5.proximityalert"); //Custom Action
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), -1, i, 0);
lm.addProximityAlert(lat, long1, radius, -1, pi);
So far, I've only been able to find marker.getLocation() which doesn't allow direct variable setting. Is there a way to do this?
Have you tried this:
map.setInfoWindowAdapter(new InfoWindowAdapter() {
// Use default InfoWindow frame
#Override
public View getInfoWindow(Marker args) {
return null;
}
// Defines the contents of the InfoWindow
#Override
public View getInfoContents(Marker args)
{
LatLng clickedMarkerLatLng = args.getPosition();
double latitude = clickedMarkerLatLng.latitude;
double longitude = clickedMarkerLatLng.longitude;
....
}
I hope this code helps you :
#Override
public void onMapLongClick(LatLng point) {
Latitude lat = point.getLatitude();
Longitude lng = point.getLongitude();
}