How to get address from latitude and longitude? - android

I have implemented this code to display address based on GPS. The latitude and longitude are working fine (appear on the screen) however, for the address its stands "no address found". Please have look at this code and point any errors. Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find__location);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager =(LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
//String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
//buttons assigned
Button mainMenuBtn = (Button) findViewById(id.mainMenuBtn);
mainMenuBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
};
private void updateWithNewLocation(Location location) {
String latLong;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "no address found";
if(location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLong = "Lat: "+lat+"\nLong: "+lng;
//double latitude = location.getLatitude();
//double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this,Locale.getDefault());
try{
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0){
Address address = addresses.get(0);
for(int i=0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}catch (IOException e){}
}else{
latLong = "No location found";
}
myLocationText.setText("Your coordinates are:\n"+latLong + "\n"+addressString);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.find__location, menu);
return true;
}
}

I have had the same issue which was pretty annoying. Some answers suggested that geocoder does not always return a value so you have to loop some. However, this is not a good approach as you may never get a value, which sometimes is the case. Thus, what I have done in my project was to use google's reverse geocoding api. Idea is same but methodology is different.
This is the api page: https://developers.google.com/maps/documentation/geocoding/
Check the first answer here : Android Geocoder getFromLocationName always returns null
Hope this helps

I prefer to get address using google geocoding API, by sending lat lon params, you'll get some informations
https://developers.google.com/maps/documentation/geocoding/

Related

getting current location..on map its fine..but not getting address

Actually i am using geocoder to get the address..but i am getting address value as null.According to me I wrote the correct code to get current location from methods like getAddress() and address().The code i used is as following:
public class CurrentLoc extends Activity {
// latitude and longitude
static double latitude ;
static double longitude ;
// Google Map
private GoogleMap googleMap;
private LocationManager locationManager;
private Location location;
private String val;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new3);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
getAddress();
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* function to load map. If map is not created it will create it for you
* */
public String getAddress(){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
if (location != null) {
latitude= location.getLatitude();
longitude= location.getLongitude();
/*String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
lat, lng);*/
try {
val = address(latitude, longitude);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText( CurrentLoc.this, val,
Toast.LENGTH_LONG).show();
}
return val;
}
public String address(double lt,double lg) throws IOException{
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(lt, lg, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
return address +"\n"+ city +"\n"+ country;
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
// Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(CurrentLoc.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(CurrentLoc.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(CurrentLoc.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(location.getLatitude(), location.getLongitude())).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Hello Maps ");
googleMap.addMarker(marker);
googleMap.isMyLocationEnabled();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mnew1, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.home:
openSearch();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openSearch(){
String val1 = null;
val1 = getAddress();
Intent intnt=new Intent(getApplicationContext(),SendSms.class);
intnt.putExtra("loct", val1);
startActivity(intnt);
}
}
Move your code:
if (location != null) {
latitude= location.getLatitude();
longitude= location.getLongitude();
value=address(latitude, longitude);
Toast.makeText( CurrentLoc.this, value,
Toast.LENGTH_LONG).show();
}
Inside your public void onLocationChanged(Location location) method.
When you request a new location, you don't get the result immediately. Instead, you need to register a listener, like you did when you called locationManager.requestLocationUpdates, so the location provider can notify it when it fetches a location for you.
Also, from what I understood from your code, you may benefit from calling locationManager.requestSingleUpdate if you just need to get the phone's address in the current location instead of constantly getting location updates that requestLocationUpdates will give you.
Finally, consider this blog post for best practices on fetching the user location. You don't always need to get location updates if the current location is already known.
Hope it helps.

Logging location address to LogCat

A part of my app is attempting to update the location (using DDMS with an emulator in Eclipse) and then get the address to print to LogCat.
My code:
LocationManager locationManager;
String providerName = LocationManager.GPS_PROVIDER;
LocationProvider gpsProvider;
public void enable()
{
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //Need to ask for this system service
Criteria criteria = new Criteria(); //Setting the criteria for the location provider
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(true);
String provider = LocationManager.GPS_PROVIDER;
int time = 5000; //Time in ms
int distance = 5; //Distance in meters
LocationListener myLocationListener = new LocationListener()
{
public void onLocationChanged(Location locations)
{
updateLocation(locations);
}
public void onProviderDisabled(String arg0)
{
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0)
{
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2)
{
// TODO Auto-generated method stub
}
};
locationManager.requestLocationUpdates(provider, time, distance, myLocationListener);
}
/////////////////////////////////////////////////////////////////////////////////
public void findLocation()
{
gpsProvider = locationManager.getProvider(providerName);
//String bestProvider = locationManager.getBestProvider(criteria, true);
Location locations = locationManager.getLastKnownLocation(providerName);
updateLocation(locations);
}
public void updateLocation(Location locations)
{
if (locations != null)
{
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
double latitude = locations.getLatitude();
double longitude = locations.getLongitude();
List<Address> addresses = null;
Geocoder GCoder = new Geocoder(this, Locale.getDefault());
try
{
addresses = GCoder.getFromLocation(latitude, longitude, 10);
Address first = addresses.get(0);
Log.d("ADDRESS", first.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
This, to me, should print the value "first" into LogCat but it doesn't seem to actually display anything.
I have the required permission in the manifest so that is not the issue.
Any help that can be provided is great, thank you.
Use this code
See Updated Code
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if(null!=locations && null!=providerList && providerList.size()>0){
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
String _Location = listAddresses.get(0).getAddressLine(1);
}
} catch (IOException e) {
e.printStackTrace();
}
}

reverse geocoding not working

i written following code to get current location. although I m testing it in emulator with different latitude and longitude. But it cant convert the lattitude and longitude in real location.
public class LocationFindingActivity extends Activity {
/** Called when the activity is first created. */
EditText et;
LocationManager locationManager;
String provider;
LocationListener locationListener;
Location currentLocation;
String addressString="";
String longlattString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText)findViewById(R.id.locationTXT);
locationManager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
currentLocation=locationManager.getLastKnownLocation(provider);
et.setText(addressString);
locationListener =new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
updateWithNewLocation(currentLocation);
}
};
updateWithNewLocation(currentLocation);
locationManager.requestLocationUpdates(provider, 2000, 10,locationListener)
}
private void updateWithNewLocation(Location location) {
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
longlattstring="Lattitude :"+lat+"Longitude :"+lng;
Geocoder gc = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
//Toast.makeText(this, "Problem1", 2000).show();
if (addresses.size() > 0)
{
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
Toast.makeText(this, "Problem2", 2000).show();
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}
catch (IOException e)
{
Toast.makeText(this, "Problem Catch", 2000).show();
}
}
else
{
addressString = "No location found";
}
et.setText(addressString);
}
}
I am getting problem in this line
List addresses = gc.getFromLocation(lat, lng, 1);
the statement doesn't return anything.
It's a known bug which they never fixed see service not avavilable.I think you will find that it works in the the API level 7 emulator.

Android,StreetView not showing correctly on my device Htc Desire

I have an HTC desire and am trying to write an app to show my current location.
I have managed to write the app and to show where I am. But I am only able to see my location in satelite view. When I try and only get the streetView the map appears blank and there are no streets shown at all.
Here is the code that I am trying to use for getting the streetView to show.
public class FindMeInMap extends MapActivity {
#Override
protected boolean isRouteDisplayed() {
return false;
}
MapController mapController;
MyPositionOverlay positionOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView myMapView = (MapView)findViewById(R.id.theMapView);
myMapView.displayZoomControls(true);
myMapView.setBuiltInZoomControls(true);
mapController = myMapView.getController();
myMapView.setSatellite(false);
myMapView.setStreetView(true);
myMapView.displayZoomControls(true);
myMapView.setTraffic(true);
// Add the MyPositionOverlay
positionOverlay = new MyPositionOverlay();
List<Overlay> overlays = myMapView.getOverlays();
overlays.add(positionOverlay);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "No address found";
if (location != null) {
// Update my location marker
positionOverlay.setLocation(location);
// Update the map location.
Double geoLat = location.getLatitude()*1E6;
Double geoLng = location.getLongitude()*1E6;
GeoPoint point = new GeoPoint(geoLat.intValue(),
geoLng.intValue());
mapController.animateTo(point);
mapController.setZoom(17);
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
} catch (IOException e) {}
} else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +
latLongString + "\n" + addressString);
}
}
Can anyone spot my problem and tell me why I cannot see this working on my Desire? I tried the same code on the emulator and it works fine, just not on the phone ?!?
Thanks in Advance!
Make the following changes:
myMapView.setSatellite(false);
myMapView.setStreetView(true);
myMapView.setBuiltInZoomControls(true);
myMapView.postInvalidate();

How to track location through GPS in android application

I am working on development of android game application. I want to judge location of players of game. I want that details like pincode, city name,country name, geo cordinates, accuracy etc.
public class GPSLocationListener implements LocationListener {
Context context;
#Override
public void onLocationChanged(Location location2) {
location2.getLatitude();
location2.getLongitude();
#Override
public void onProviderDisabled(String provider) {
AlertPopup.displayPopup(context, "GPS Disabled");
}
#Override
public void onProviderEnabled(String provider) {
AlertPopup.displayPopup(context, "GPS Enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
but not able to get all data which i want
Assuming that you are aware how to use GPS in android. Here is how to get the information you want.
Pincode, city name, country name
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0)
{
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
} catch (IOException e) {
}
}
else
{
addressString = "No where";
}
Geo cordinates, accuracy
location.getLatitude()
and
location.getAccuracy()

Categories

Resources