I have an Android application where I need to get address from lat/long. I have used the following code base:
Geocoder geoCoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> address = null;
if (geoCoder != null){
try {
address= geoCoder.getFromLocation(51.50, -0.12, 1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (address.size()> 0){
String postCode = address.get(0).getPostalCode();
System.out.println(postCode);
}
}
I have also added the following in my manifest file
uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
but every time I execute this block address.size() remains "0", I have tried with different coordinates also; nothing changed at all. I'm doing all this from eclipse.
Try this:
private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
#Override
protected Void doInBackground(Location... params) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
Location loc = params[0];
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
// Format the first line of address (if available), city, and
// country name.
final String addressText = String.format(
"%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address.getLocality(),
address.getCountryName());
// Update address field on UI.
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(),
addressText.toString(), Toast.LENGTH_SHORT)
.show();
}
});
}
return null;
}
}
Related
"I need to switch Base URL based on a user's Location and change other UI components".
I tried throughout the Build Config but I didn't find anything that seems to work.
First you have to add servers to strings.xml file then you can use this one to get location country name after that in switch case you can change the server
#Override
protected void onResume() {
String country_name = null;
LocationManager lm =
(LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
#SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name = addresses.get(0).getCountryName();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
}
I am working on an app which works with latitude and and longitude after a user input an address. I'm utilizing Geocoder to get the latitude and longitude from the Input address. But the issue is both are returned with associated address from the Geocoder but I'm only able to read one of them. following is the code I'm using:
Geocoder geocoder = new Geocoder(this);
List<Address> addresses;
double[] cordinates = new double[2];
try {
addresses = geocoder.getFromLocationName(locName, 1);
if (addresses.size() > 0) {
cordinates[0] = addresses.get(0).getLatitude();
cordinates[1] = addresses.get(0).getLongitude();//unable to get this one
return cordinates;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
in the above cases I'm able to get latitude but unable to get the longitude. I known this after debugging. Now when I swap them like
cordinates[1] = addresses.get(0).getLongitude();
cordinates[0] = addresses.get(0).getLatitude();
Now I get Longitude but not the latitude.
what is the problem here?
This is working fine. Since you are debugging your code with breakpoints when it encounters the
return cordinates; it goes to
return null;
It only happens while debugging. It always returns the correct value. You can check returned values by inserting a log statement.
{
.....
double[] coordinates = getLongLat("Your address");
Log.wtf(TAG,"Lat:"+coordinates[0]+" Long:"+coordinates[1]);// This will log the correct values
.....
}
public double[] getLongLat(String address){
Geocoder geocoder = new Geocoder(this);
List<Address> addresses;
double[] cordinates = new double[2];
try {
addresses = geocoder.getFromLocationName(address, 1);
if (addresses.size() > 0) {
Address address1 = addresses.get(0);
cordinates[0] = address1.getLatitude();
cordinates[1] = address1.getLongitude();
return cordinates;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Try this working code :
AutoCompleteTextView acGooglePlaces = (AutoCompleteTextView) findViewById(R.id.ac_edit_my_event_places);
acGooglePlaces.setAdapter(new GooglePlacesAutocompleteAdapter(GooglePlaces.this, R.layout.auto_complete_text_layout));
acGooglePlaces.requestFocus();
btnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
List<Address> returnedaddresses = geoCoder.getFromLocationName(acGooglePlaces.getText().toString(),1);
if(!returnedaddresses.isEmpty()){
String latForVol = String.valueOf(returnedaddresses.get(0).getLatitude());
String longForVol = String.valueOf(returnedaddresses.get(0).getLongitude());
Log.e("Lat", latForVol);
Log.e("Long", longForVol);
Log.e("Location", acGooglePlaces.getText().toString());
}else {
Log.e("Check", "Please give the correct address");
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
public static LatLng reverseGeocoding(Context context, String locationName){
if(!Geocoder.isPresent()){
Log.w("zebia", "Geocoder implementation not present !");
}
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(locationName, 1);
} catch (IOException e) {
Log.d(Geocoding.class.getName(), "not possible finding LatLng for Address : " + locationName);
}
if(addresses.size() > 0){
Log.d("zebia", "reverse Geocoding : locationName " + locationName + "Latitude " + addresses.get(0).getLatitude() );
return new LatLng(addresses.get(0).getLatitude(), addresses.get(0).getLongitude());
}else{
//use http api
}
return null;
}
i want to build a app which shows me user location on google map...but it shows me no address is found ..even when i tried to give fixed value ...
if(location!=null && !location.equals("")){
googleMap.clear();
new GeocoderTask(MainActivityMap.this).execute(location);
}
My Geocoder Asynctask Activity
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
private Context mainContxt;
Geocoder geocoder;
public GeocoderTask(Context con){
mainContxt=con;
}
#Override
protected List<Address> doInBackground(String... locationName) {
Geocoder geocoder = new Geocoder(mainContxt);
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found.Please check
address", Toast.LENGTH_SHORT).show();
return; // add this
}
else{
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
if(i==0) {
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
googleMap.addMarker(markerOptions);
}
}
}
}
i think error in this line
addresses = geocoder.getFromLocationName(locationName[0], 3);
address dosent receive anything
....thx in advance...help me friends
In my App I use This code to get Address...!!! This is for your reference.
Geocoder geocoder;
List<Address> addresses;
double latitude, longitude;
String zip, city, state, country;
googleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng arg0) {
latitude = arg0.latitude;
longitude = arg0.longitude;
String title = "";
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
zip = addresses.get(0).getPostalCode();
city = addresses.get(0).getLocality();
state = addresses.get(0).getAdminArea();
country = addresses.get(0).getCountryName();
if (zip != null) {
title += zip + ",";
}
if (city != null) {
title += city + ",";
}
if (state != null) {
title += state + ",";
}
if (country != null) {
title += country;
}
} else {
title = "Unknown Location";
showPosition.setText("Address Not Found");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// This will put marker and set Address as a marker title
googleMap.addMarker(new MarkerOptions().position(arg0).title(title));
}
});
how to set marker in google map?
MarkerOptions options = new MarkerOptions().position(latLng).title(shortDescStr);
googleMap.addMarker(options);
Hi I am working with android.I had created a GPS app for getting the current location.Now How can I get the country name from the latitude and longitude value ? is it possible ? please help me and thanks :)
here is my code I used
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
String countryCode,countryName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.i("location", " "+latitude+" "+longitude);
// \n is for new line
try
{Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(latitude,longitude, 1);
if (addresses.size() > 0)
Toast.makeText(getApplicationContext(), "name "+addresses.get(0).getLocality(),Toast.LENGTH_SHORT).show();
//System.out.println(addresses.get(0).getLocality());
}
catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude+countryName +" "+countryCode, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
String country_name = null;
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
#SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name = addresses.get(0).getCountryName();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
Finally I got the solution, without lat and long value, i got country name.
String country = getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();
.
Use this:
Geocoder myLocation = new Geocoder(AppContext);
try
{
myList = myLocation.getFromLocation(latitude, longitude, 1);
}
catch (Exception e)
{
e.printStackTrace();
}
if(myList != null)
{
try
{
String country = myList.get(0).getCountryName();}
You can Get Country name from below mentioned json. Just pass your lat-long in address. And look for "long_name" which have "country,political" in "types" array.
i.e. http://maps.googleapis.com/maps/api/geocode/json?address=23.022505,72.5713621&sensor=false
From a Geocoder object, you can call the getFromLocation(double, double, int) method. It will return a list of Address objects that have a method getLocality().
import android.location.Address;
import android.location.Geocoder;
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(1.2, 2.2256, 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
List<Address> addresses=null;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(loc.latitude, loc.longitude, 1);
System.out.println("add in string "+addresses.toArray().toString());
String countryName = addresses.get(0).getCountryName();
String countryCode = addresses.get(0).getCountryCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I want to do reverse geocoding in my app using map api 2.But i dont know exactly how to do that?Any ideas?
Use Geocoder:
Geocoder geoCoder = new Geocoder(context);
List<Address> matches = geoCoder.getFromLocation(latitude, longitude, 1);
Address bestMatch = (matches.isEmpty() ? null : matches.get(0));
This is how it works for me..
MarkerOptions markerOptions;
Location myLocation;
Button btLocInfo;
String selectedLocAddress;
private GoogleMap myMap;
LatLng latLng;
LatLng tmpLatLng;
#Override
public void onMapLongClick(LatLng point) {
// Getting the Latitude and Longitude of the touched location
latLng = point;
// Clears the previously touched position
myMap.clear();
// Animating to the touched position
myMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
//tmpLatLng = latLng;
btLocInfo.setEnabled(true);
btLocInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double[] coordinates={tmpLatLng.latitude/1E6,tmpLatLng.longitude/1E6};
double latitude = tmpLatLng.latitude;
double longitude = tmpLatLng.longitude;
Log.i("selectedCoordinates", latitude + " " + longitude);
Log.i("selectedLocAddress", selectedLocAddress);
}
});
}
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>{
Context mContext;
public ReverseGeocodingTask(Context context){
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText="";
try {
addresses = geocoder.getFromLocation(latitude, longitude,1);
Thread.sleep(500);
if(addresses != null && addresses.size() > 0 ){
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
}
catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
selectedLocAddress = addressText;
return addressText;
}
#Override
protected void onPostExecute(String addressText) {
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(addressText);
// Placing a marker on the touched position
myMap.addMarker(markerOptions);
}
}
You can do like this to get complete address :
public class MainActivity extends AppCompatActivity {
...
private Geocoder geocoder;
private TextView mAddressTxtVu;
...
// assume that you got latitude and longitude correctly
mLatitude = 20.23232
mLongitude = 32.999
String errorMessage = "";
geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(
mlattitude,
mlongitude,
1);
} catch (IOException e) {
errorMessage = getString(R.string.service_not_available);
Log.e(TAG, errorMessage, e);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = getString(R.string.invalid_lat_long_used);
Log.e(TAG, errorMessage + ". " + "Latitude = " + mlattitude +",
Longitude = " + mlongitude, illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found);
Log.e(TAG, errorMessage);
}
} else {
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
// Fetch the address lines using getAddressLine,
// join them, and send them to the thread.
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
}
// Log.i(TAG, getString(R.string.address_found));
mAddressTxtVu.setText(TextUtils.join(System.getProperty("line.separator"),
addressFragments));
}
Hope it helps!
You don't need to use Google Maps Api for this purpose. Android SKD have a class for it which you can simply use without any registration of API Key and so on. The class is android.location.Geocoder. It have methods for geocoding and reverse geocoding. I was looking in the source code of this class and found that it have a method android.location.Geocoder#getFromLocationName(java.lang.String, int) where first argument is address, and second is max number of results you want. It returns a List<Address>. The Address class have methods like android.location.Address#getLatitude and android.location.Address#getLongitude. They both return double.
Try it and let me know how good it is :-)