Can anyone tell me how reverse geocoder works. I have code which uses getFromlocation and getLastKnownLocation to find out the address. The thing is i don't know how to use the OnLocationChanged on it and how to disable the listener when i dont need it. I am utterly confused for the past 2 days. If any one can provide me some good resources with complete examples or link it would be great..
Geocoder geocoder = new Geocoder(
TrackLogic.this.getApplicationContext(),
Locale.getDefault());
Location locationGPS = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNetwork = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Log.d(TAG, "geocoder works");
First you need to get a LocationManager instance and the name of the provider you want to use to do a location look-up. For example:
String provider = LocationManager.NETWORK_PROVIDER;
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Next, you call requestLocationUpdates(...) like so:
locationManager.requestLocationUpdates(provider, 1000, 0, this);
This can be invoked on the main thread since (I think) the system will do the location lookup using the specified provider on a background thread. When a location is found, the Android system will invoke the onLocationChanged(...) callback, which you need to override. Since you're trying to do an address lookup, you would put in:
Geocoder geocoder = new Geocoder(this);
geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10)
which should get you what you're looking for.
When you're done with using the Location services, you can call
locationManager.removeUpdates(this)
Related
I am developing a proximity alert related project. For that whenever I opened my app, I need to get exact readings of where I am. Even though I am following the right coding practices prescribed by android documentation, I am not getting the expected result.
Why there is no alternative command in entire android Geolocation coding for getLastKnownLocation which will give us where we are earlier not now.
I have did one javascript coding in the same lines. There My code is working properly. The Descriptive address and coordinates where my device is working nice there. Those commands getCurrentPosition and watchPosition are givinga beautiful response via their event handler callbacks. Why there is no getCurrentLocation in android geolocation parlance?
Even though I have followed relevant coding practices, MyLocationListener myLocationUpdate which implements LocationListener is not updating my new location when I am moving from one place to another place. I gave MINIMUM_DISTANCE_CHANGE_FOR_UPDATES as 1(in meters) and MINIMUM_TIME_BETWEEN_UPDATES as 1000 (in milliseconds).
I am giving important code snippets below to understand the problem
in onCreate handler of the activity
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
myLocationUpdate = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, myLocationUpdate);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Finding Location",Toast.LENGTH_LONG).show();
showCurrentLocation();
}
});
latituteField = (TextView) findViewById(R.id.display_Location);
showCurrentLocation();
in showCurrentLocation function
I am using locationManager.getLastKnownLocation(provider) to retrieving that location.
By using GeoCoder Object and the command geocoder.getFromLocation(latitude, longitude, 1) to get First Address match for the coordinates.
// internal class to handle location cahnge event
private class MyLocationListener implements LocationListener contains all the Overridden functions including public void onLocationChanged(Location location)
But Practically I am getting nothing out of all the application. I have already recorded Time via location.getTime(). It is showing a fixed earlier time, but not the interval i specified.
the problem with getting GPS location is that it isnt available immediately. From my understanding of GPS location provider is that when you request location update, the gpr provider will try to connect to the gps satellites which runs in a separate thread (not entirely sure about it). In the meantime your program is executed normally and there maybe a chance that you wont get any location.
What you can do is use Fused Location Provide which was introduced in this year's IO Event. You can find the tutorial here
I have the following code in my Service:
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider =
locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();
Location location = locationManager.getLastKnownLocation(provider);
while(true)
{
if(...)//every 5 seconds it gets into
{
....//control if the location is not null
lat = location.getLatitude();
lon = location.getLongitude();
alt = location.getAltitude();
Log.i(TAG, "Latitude: "+lat+"\nLongitude: "+lon+"\nAltitude: "+alt);
}
else {
Log.i(TAG, "Error!");
}
}
This code kind of works in my emulator (GPS are inserted into the Log), but in my Mobile device, this code gets to the else branch. Could somebody tell me where is the problem? In my code or in my Mobile device? Thanks in advance.
P.S.: The GPS is turned on, in another apps it works.
getLastKnownLocation() will not fetch subsequent location from the GPS provider. It will return (as the name may suggest) the last known location requested by some code. I assume that you check location being not null in the condition, which is not shown in your code. The location is null if the device "decided" that the last known location is too old or unreliable by other means. You need to request location updates and provide a location listener to get locations repeatetly.
There are lots of tutorials available. Here ist one. of them.
I am unable to getLastKnownLocations on my Android device (Samsung Galaxy Note N7000) as it is always null, towers is detected as network so it is fine, anybody got any idea how to get my location?
d = getResources().getDrawable(R.drawable.songs_gray);
//Placing pinpoint at location
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Toast.makeText(LocationActivity.this, "Towers: " + towers, Toast.LENGTH_SHORT).show();
Location location = lm.getLastKnownLocation(towers);
Toast.makeText(LocationActivity.this, "Location: " + location, Toast.LENGTH_SHORT).show();
if(location !=null){
lat = (int) (location.getLatitude()*1E6);
longi = (int) (location.getLongitude()*1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up", "2nd String");
CustomPinpoint custom = new CustomPinpoint(d, LocationActivity.this);
custom.insertPinPoint(overlayItem);
overlayList.add(custom);
}else{
Toast.makeText(LocationActivity.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
}
Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
With getLastKnownLocation() you can only get a Location object when the specified location provider is active.
The documentation says:
Returns a Location indicating the data from the last known location
fix obtained from the given provider. This can be done without
starting the provider. Note that this location could be out-of-date,
for example if the device was turned off and moved to another
location.
If the provider is currently disabled, null is returned.
To detect the current position and not the last detected one you need to enable the location provider(s). This tutorial should help you to understand how to work with location providers as GPS and network.
the last known location is only available if the location has been determined by another app prior to your call. start maps or some other app and let it get a location lock. then run your app.
if you really need location in your app, you need to fall back to some other method, because you cannot depend on there being a last known location.
as a side note, ACCESS_MOCK_LOCATION isn't required here. from the docs,
Allows an application to create mock location providers for testing
Nevermind found out my problem! Just needed to on Google's Location Services on my phone
I got the Latitude and longitude values in Emulator using Telnet.(i.e) GPS.
I have a doubt (i.e) without google map can we able to get the current location using the latitude and longitude.
You can fetch the current location using GPS and Google map both. If you want to fetch location through Google map then plz show this tutorial. And you can see this previous asked question.
If you want to fetch location without Google map then you can be use location manager.
To do this, we need to add the fallowing code in the OnCreate method:
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
In the custom class MyLocationListener using implements the interface LocationListener.
We will add our own personal Location listener, so we can override some of the functions to do what we want. In our case we will just print a message to the screen in the fallowing cases:
onLocationChanged ( Location Update )
onProviderDisabled ( GPS Off )
onProviderEnabled (GPS On )
And add another mandatory method, which will do nothing.
onStatusChanged (We are not adding nothing here).
After that give the permission in AndroidManifest.xml file:
android:name="android.permission.ACCESS_FINE_LOCATION"
You can get latitude and longitude by this code
GPS_Location mGPS = new GPS_Location(MyApplication.getAppContext());
if (mGPS.canGetLocation) {
mLat = mGPS.getLatitude();
mLong = mGPS.getLongitude();
} else {
System.out.println("cannot find");
}
you must add the gps permissions and other permissions to your app
Actually my problem is sometimes i can get the location and sometimes i can't get the location on Android real device. I used following code for getting the location,
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
I need to get the location when my application starts up. I don't know why sometimes it fails. How to resolve this issue?
#jsmith commented on my quesion,
Increase your power requirements and make sure you test where you can
get a network or gps signal. If that helps, then it's simply a case of
the sensors not getting enough reception to know the location.
This is the right answer for my question. Now its working fine.
You forgot to request for 'Location Updates', use this function after declaring the LocationManager:
locationManager.requestLocationUpdates(provider, 0, 0, this);
and you have to let the class implements LocationListener then add this function:
public void onLocationChanged(Location location) {
//get the location here
}
If you don't want to get the location repeatedly, after you get the location you have to stop the 'Location Updates' this way:
locationManager.removeUpdates(this);
in case you want the application always listen for the 'Location Updates', you better request for updates in onResume() and remove the updates in onPause() & onDestroy()
Good Luck