how to get postal code using reverse geocoding in android - android

I am new to Andriod development..i try to get postal code and city name from reverse geocoding using below code.it finding latitude, longitude value fine but cant able to get cityname and postal code.
package com.example.code;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Geocoder gcoder=new Geocoder(this, Locale.ENGLISH);
List<Address> Data = null;
double latitude;
double longitude;
if (location != null) {
latitude=location.getLatitude();
longitude=location.getLongitude();
try {
Data=gcoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String cityname=Data.get(0).getLocality();
String postalcode=Data.get(0).getPostalCode();
String message=String.format("City Name \n PostalCode \n", Data.get(0).getLocality(),Data.get(0).getPostalCode());
Toast.makeText(LbsGeocodingActivity.this,message ,
Toast.LENGTH_LONG).show();
}
}
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(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show(); }
}
}

It looks like your code for finding the city and zipcode is right, but your code for formatting the string for your toast is wrong. It does not put the values in there.
It should look like this:
String message=String.format("City Name %s \n PostalCode %d \n", Data.get(0).getLocality(),Data.get(0).getPostalCode());
The %s represents a string and the %s represents a decimal number (integer).

Related

How to get a non null value using getLastKnownLocation when the app is launched

package com.example.getlocation;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LbsGeocodingActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LbsGeocodingActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
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(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
I am trying to get my current location on the click of a button. I tried the above code but the line Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) always gives the location null. I looked up to find out the problem may be due to getLastKnownLocation. As LastKnownLocation is not cancehd, I am getting null value. But how I modify this code to give the current location instead of null value.
make two global strings like:
public class LbsGeocodingActivity extends Activity {
private latVar;
private lonVar;
then in your onLocationChanged method in your location listener:
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
latVar = Double.toString(lat);
lonVar = Double.toString(lon);
then in your button click:
protected void showCurrentLocation() {
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LbsGeocodingActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
}
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
lonVar, latVar
);
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}
also consider changing your variable MINIMUM_DISTANCE_CHANGE_FOR_UPDATES to 0

Android get location from cell tower

Hi I want to get location from cell tower(Sim card) without internet. I had used below mentioned code it's give me only last location when network available.
my requirement is to get location without WiFi or internet. can it's possible?
package com.example.gpscelltower;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CellTowerActivity1 extends Activity {
private static final String TAG = "Cell";
private static LocationManager locationManager;
private static LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cell_tower);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
String providerName=LocationManager.NETWORK_PROVIDER;
Location location=locationManager.getLastKnownLocation(providerName);
updateWithLocation(location);
//Cell-ID and WiFi location updates.
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.d("TAG", "locationListner");
updateWithLocation(location);
String Text = "My current location is: " + "Latitude = "+ location.getLatitude() + "Longitude = " + location.getLongitude();
Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_LONG).show();
Log.d("TAG", "Starting..");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("TAG", "onSatatus");
}
public void onProviderEnabled(String provider) {
Log.d("TAG", "onProviderEnable");
}
public void onProviderDisabled(String provider) {
Log.d("TAG", "onProviderDisble");
}
};
}
private void updateWithLocation(Location location) {
Log.d("TAG", "UpdateWithLocation");
String displayString;
if(location!=null){
Double lat=location.getLatitude();
Double lng=location.getLongitude();
Long calTime=location.getTime();
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(calTime);
String time=formatter.format(calendar.getTime()).toString();
displayString="The Lat: "+lat.toString()+" \nAnd Long: "+lng.toString()+"\nThe time of Calculation: "+time;
}else{
displayString="No details Found";
}
Toast.makeText(CellTowerActivity1.this, ""+displayString, Toast.LENGTH_LONG).show();
}
}
Cell geolocation works through sending Cell towers IDs to server which maps it to coordinates. So, unfortunately it's not posssible to get your coordinates w/o data connection with standard APIs.

Network location returned is wrong

I want to get the location of the user using network. This is my code
package com.example.locationtest;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
public class WhereAmI extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
// String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 1000, 0,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
String timeStamp = (String) DateFormat.format("hh:mm:ss",
new java.util.Date());
String locationString = location.getLatitude() + ", "
+ location.getLongitude();
Log.i("Main", "Time = " + timeStamp + " Location = " + locationString);
}
}
This code works with my nexus 4, but if I use it with my Galaxy Gio the location is off by 30 Miles..
network location is based on the nearest Cell tower which the phone is connected to. It could be possible that your Nexus4 is connected to one Cell tower and the Galaxy Gio connected to another cell tower that could be like a bit far from where the Device is. To get an accurate fix, use GPS_PROVIDER. I had this issue before when using a NETWORK_PROVIDER. Got rid of it when I started using the GPS_PROVIDER which gave me accurate fixes

Getting longitude and latitude works in emulator but not on device?

I've been trying to work GPS coordinates but it's been a lot tougher than I thought. After a few hours of trial and error, I've managed to output the latitude and longitude (mocked) for my emulator. Below are the 2 ways I've done it:
First way:
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String text = "";
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
showMyAddress(location);
}
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
showMyAddress(location);
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 10, locationListener);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.i(TAG, "longitude: " + longitude);
Log.i(TAG, "latitude: " + latitude);
text = "longitude: " + longitude + ", " + "latitude: " + latitude;
TextView textView = (TextView) findViewById(R.id.txtvwMain);
textView.setText(text);
}
private void showMyAddress(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> myList;
try {
myList = myLocation.getFromLocation(latitude, longitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Second way:
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity implements LocationListener
{
private LocationManager lm;
private TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.txtvwMain);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this);
Location location = lm.getLastKnownLocation(lm.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
tv.setText("latitude="+latitude+", longitude="+longitude);
}
#Override
public void onLocationChanged(Location arg0) {
String lat = String.valueOf(arg0.getLatitude());
String lon = String.valueOf(arg0.getLongitude());
Log.e("GPS", "location changed: lat="+lat+", lon="+lon);
tv.setText("lat="+lat+", lon="+lon);
}
public void onProviderDisabled(String arg0) {
Log.e("GPS", "provider disabled " + arg0);
}
public void onProviderEnabled(String arg0) {
Log.e("GPS", "provider enabled " + arg0);
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
Log.e("GPS", "status changed to " + arg0 + " [" + arg1 + "]");
}
}
Both ways above work and print out the mock latitude and longitude onto a TextView in the emulator (running Android 4.2.2). However, when I upload the .apk file onto my device (tablet running Android 4.0.4), it just crashes. I don't know what's wrong because I can't see any error messages. What is the source of the problem and how may I go about solving it? Thanks.

LocationManager not working on Android phone

I have a problem,
The locationmanager is working perfectly fine when i test it in the emulator and edit the location in the DDMS screen, but when i test it on the Samsung Galaxy SII, its nog working..
Please help me.
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
public String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format("Current Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s ", location.getLongitude(), location.getLatitude(), getMyPhoneNumber());
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s ",
location.getLongitude(), location.getLatitude(), getMyPhoneNumber()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
In the permissions i have:
ACCES_COURSE_LOCATION
ACCES_FINE_LOCATION
Maybe you are testing indoors, and can't get any GPS information.
Try to change LocationManager.GPS_PROVIDER-->LocationManager.NETWORK_PROVIDER.
It could be a problem with your incorrect usage of String.format(). Sometimes this can cause weird, device-specific issues. Try,
String lon = "" + location.getLongitude();
String lat = "" + location.getLatitude();
String num = getMyPhoneNumber();
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s",
lon,
lat,
num
);
Have you tried using this?
LocationManager lm = (LocationManager)act.getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, true);
Location loc = lm.getLastKnownLocation(provider);
i had similar issues using the locationmanager on my HTC incredible S running 4.0.4.
it would simply stop firing location changes on the real device after some time.
on some other devices it would work.
very intermittent.
my solution was to piss off the LocationManager and use LocationClient pardiagm.
http://developer.android.com/reference/com/google/android/gms/location/LocationClient.html
ever since google play services have been introduced the Locationmanager has been intermittent on my device. I cant give any other explanation as to why it occurs.
But the LocationClient works everytime plus it removes the dumb 'provider' notion from location management.

Categories

Resources