Geocoder returned address - android

I am using Geocoder class to get Latitude and Longitude to from my String address that user types to EditText.
And what is interesting it returns results for such query as "q", "qq", "n", "N". Is there any way to make it better?(validate or something, or use another service?)
if (!s.toString().isEmpty()) {
try {
List<Address> addresses = geocoder.getFromLocationName(s.toString(), 4);
if (addresses.size() > 0) {
Address userAddress = addresses.get(0);
double latitude = userAddress.getLatitude();
double longitude = userAddress.getLongitude();
mRestaurantLatLng = new LatLng(latitude, longitude);
if (userAddress != null) {
mPin.setVisibility(View.VISIBLE);
} else {
mPin.setVisibility(View.GONE);
mRestaurantLatLng = null;
}
} else {
mPin.setVisibility(View.GONE);
mRestaurantLatLng = null;
}
} catch (Exception e) {
e.printStackTrace();
}

You could always use another Service directly, or you could prune your results for the detail level you want.
So like:
List<Address> results = GeoCoder.getFromLocationName(query, 100);
filter(results);
if (results.size() > 0) {
// Do Stuff
}
....
void filter(List<Address> results) {
for (int i = 0; i < results.size(); i++) {
Address address = results.get(i);
if (!address.hasLatitude() || !address.hasLongitude()) {
results.remove(i);
}
// remove any that dont match your desired detail level
...
}

Related

Google map Activity(Not getting lat,lang)

Here I'm trying to get the current location on the google maps activity. but it is no fetching the latitude or longitude when the map page is loaded. Assist me here. while checking with the breakpoints, latitude, and longitude values are null.
private void configureCameraIdle() {
onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
Geocoder geocoder = new Geocoder(TrialActivity.this);
try {
addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addressList != null && addressList.size() > 0) {
String locality = addressList.get(0).getAddressLine(0);
String country = addressList.get(0).getCountryName();
System.out.println("Address "+addressList.get(0).getAddressLine(0));
System.out.println("getAdminArea "+addressList.get(0).getAdminArea());
System.out.println("getCountryCode "+addressList.get(0).getCountryCode());
System.out.println("getCountryName "+addressList.get(0).getCountryName());
System.out.println("getExtras "+addressList.get(0).getExtras());
System.out.println("getLocale "+addressList.get(0).getLocale());
System.out.println("getLocality "+addressList.get(0).getLocality());
System.out.println("getPhone "+addressList.get(0).getPhone());
System.out.println("getPostalCode "+addressList.get(0).getPostalCode());
System.out.println("getPremises "+addressList.get(0).getPremises());
System.out.println("getSubAdminArea "+addressList.get(0).getSubAdminArea());
System.out.println("getSubLocality "+addressList.get(0).getSubLocality());
if (locality!=null && country!=null)
{
if (!locality.isEmpty() && !country.isEmpty())
resutText.setQuery(locality + " " + country,true);
}
else {
System.out.println("Please drag map to valid address..");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}

How to get the place address from specified latitude and longitude with Google Place API

I'm making a cab booking app like Uber,
User drag the map to choose his location with the pin,
And I grab the LatLng of that pin.
This is my code:
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
pinLocation = mMap.getCameraPosition().target;
setPickupLocationPrefs(pinLocation);
}
});
//Initialize Google Play Services
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
updateLocationUI();
}
}
else {
buildGoogleApiClient();
updateLocationUI();
}
}
I want to get the place address of that pin to show to my users if the app operate in that location or not (like uber does).
How can I get that address from pin location coordinate?
Use Reverse Geocoding. First get Latitude and Longitude from pin point. better to handle this in background thread. otherwise it will block UI.
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());
}
String Address=sb.toString());
}catch(Exception E);
SOLUTION TO FIX UI BLOCKING
Full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.
Geocoder call procedure, can be located in a Helper class
public static void getAddressFromLocation(
final Location location, final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality();
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to Geocoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
Here is the call to this Geocoder procedure in your UI Activity/Fragment:
getAddressFromLocation(PinPointLocation, mContext, new GeocoderHandler());
And the handler class within Activity/Fragment to show the results in your UI:
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String result;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
result = bundle.getString("address");
break;
default:
result = null;
}
// replace by what you need to do
myLabel.setText(result);
}
}

unable to get both latitude and longitude from address, I get one of them either latitude or longitude

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;
}

No Location Found In Geocoder Asyncktask Activity

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);

Location manager in android get wrong results

I am writing android code to get current location and convert lat,long to address but I am getting wrong results,
the problem is here:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
Log.d("msgh","msgh");
} else {
System.out.println("location not available");
Log.d("msg","msg");
}
the code enters the else statement always
Try this one it works
private static final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient.newInstance(GeoCoderHelper.class.getName());
private boolean running = false;
public interface CityListener {
public void cityNameListener(String s);
}
public void fetchCityName(final Context contex, final Location location,final CityListener listener)
{
if (running)
return;
new AsyncTask<Void, Void, String>()
{
protected void onPreExecute()
{
running = true;
};
#Override
protected String doInBackground(Void... params)
{
String cityName = null;
if (Geocoder.isPresent())
{
try
{
Geocoder geocoder = new Geocoder(contex, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0)
{
cityName = addresses.get(0).getLocality();
}
}
catch (Exception ignored)
{
// after a while, Geocoder start to trhow "Service not availalbe" exception. really weird since it was working before (same device, same Android version etc..
}
}
if (cityName != null) // i.e., Geocoder succeed
{
return cityName;
}
else // i.e., Geocoder failed
{
return fetchCityNameUsingGoogleMap();
}
}
// Geocoder failed :-(
// Our B Plan : Google Map
private String fetchCityNameUsingGoogleMap()
{
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + location.getLatitude() + ","
+ location.getLongitude() + "&sensor=false&language=fr";
try
{
JSONObject googleMapResponse = new JSONObject(ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl),
new BasicResponseHandler()));
// many nested loops.. not great -> use expression instead
// loop among all results
JSONArray results = (JSONArray) googleMapResponse.get("results");
for (int i = 0; i < results.length(); i++)
{
// loop among all addresses within this result
JSONObject result = results.getJSONObject(i);
if (result.has("address_components"))
{
JSONArray addressComponents = result.getJSONArray("address_components");
// loop among all address component to find a 'locality' or 'sublocality'
for (int j = 0; j < addressComponents.length(); j++)
{
JSONObject addressComponent = addressComponents.getJSONObject(j);
if (result.has("types"))
{
JSONArray types = addressComponent.getJSONArray("types");
// search for locality and sublocality
String cityName = null;
String countyName = null ;
for (int k = 0; k < types.length(); k++)
{
if ("locality".equals(types.getString(k)) && cityName == null)
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
if ("sublocality".equals(types.getString(k)))
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
}
if (cityName != null)
{
return cityName;
}
}
}
}
}
}
catch (Exception ignored)
{
ignored.printStackTrace();
}
return null;
}
protected void onPostExecute(String cityName)
{
running = false;
if (cityName != null)
{
// Do something with cityName
Log.i("GeocoderHelper", cityName);
listener.cityNameListener(cityName);
}
};
}.execute();
}
and you can call like this
new GeoCoderHelper().fetchCityName(this,location,new GeoCoderHelper.CityListener() {
#Override
public void cityNameListener(String s) {
addressCityTextView.setText(s);
}
});

Categories

Resources