Android: Reverse geocoding - getFromLocation - android

I am trying to get an address based on the long/lat. it appears that something like this should work?
Geocoder myLocation = Geocoder(Locale.getDefault());
List myList = myLocation.getFromLocation(latPoint,lngPoint,1);
The issue is that I keep getting : The method Geocoder(Locale) is undefined for the type savemaplocation
Any assistance would be helpful. Thank you.
Thanks, I tried the context, locale one first, and that failed and was looking at some of the other constructors (I had seen one that had mentioned just locale). Regardless,
It did not work, as I am still getting : The method Geocoder(Context, Locale) is undefined for the type savemaplocation
I do have : import android.location.Geocoder;

The following code snippet is doing it for me (lat and lng are doubles declared above this bit):
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

Here is a 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:
getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());
And the handler 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);
}
}
Don't forget to put the following permission in your Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />

It looks like there's two things happening here.
1) You've missed the new keyword from before calling the constructor.
2) The parameter you're passing in to the Geocoder constructor is incorrect. You're passing in a Locale where it's expecting a Context.
There are two Geocoder constructors, both of which require a Context, and one also taking a Locale:
Geocoder(Context context, Locale locale)
Geocoder(Context context)
Solution
Modify your code to pass in a valid Context and include new and you should be good to go.
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> myList = myLocation.getFromLocation(latPoint, lngPoint, 1);
Note
If you're still having problems it may be a permissioning issue. Geocoding implicitly uses the Internet to perform the lookups, so your application will require an INTERNET uses-permission tag in your manifest.
Add the following uses-permission node within the manifest node of your manifest.
<uses-permission android:name="android.permission.INTERNET" />

The reason for this is the non-existent Backend Service:
The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform.

First get Latitude and Longitude using Location and LocationManager class. Now try the code below for Get the city,address info
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());
}
City info is now in sb. Now convert the sb to String (using sb.toString() ).

Well, I am still stumped. So here is more code.
Before I leave my map, I call SaveLocation(myMapView,myMapController); This is what ends up calling my geocoding information.
But since getFromLocation can throw an IOException, I had to do the following to call SaveLocation
try
{
SaveLocation(myMapView,myMapController);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Then I have to change SaveLocation by saying it throws IOExceptions :
public void SaveLocation(MapView mv, MapController mc) throws IOException{
//I do this :
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
List myList = myLocation.getFromLocation(latPoint, lngPoint, 1);
//...
}
And it crashes every time.

Use this
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

Related

Geocoder city fetch issue

I am using google's geocoder class to fetch city with given lat-long.
I am facing this problem in India where earlier city name was Banglore and now it is changed to bengaluru.
So when I fetch using geocoder.getFromLocation method I get Banglore instead of bengaluru
While using the same lat-long I call Geocoder api directly, then I get the right city value i.e bengaluru.
Following is code geocoder class code
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String city = null;
if (geocoder != null) {
if (geocoder.isPresent()) {
try {
List<Address> addressList = geocoder.getFromLocation(params[0], params[1], 1);
city = addressList.get(0).getLocality();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My target and compile sdk version is 23.
Thank you in advance.

Get nearly locations by query in Android using Geocoder?

I want to implement search suggestions similar to Google Maps ones.
I use this code to archive this:
List<Address> searchResults = new ArrayList<>();
Geocoder geocoder = new Geocoder(context, context.getResources().getConfiguration().locale);
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(query, count);
for (Address address : addresses) {
if (address.getMaxAddressLineIndex() > 0) {
searchResults.add(address);
}
}
} catch (IOException e) {
return Collections.emptyList();
}
return searchResults;
But It seems, that It outputs locations from all over the world, sorted in a random order. What can I do to get results related with current location?

How to get Latitude Longitude from more than 500 addresses?

I have more than 700 addresses in database.
I want to plot them region wise.
I have implement this code :
public LatLng getSingleLocationFromAddress(String strAddress)
{
Geocoder coder = new Geocoder(this, Locale.getDefault());
List<Address> address = null;
Address location = null;
GeoPoint p1 = null;
LatLng temp = null;//new LatLng(26.0000, 121.0000);
String strAddresNew = strAddress.replace(",", " ");
try
{
address = coder.getFromLocationName(strAddresNew, 1);
if (!address.isEmpty())
{
location = address.get(0);
location.getLatitude();
location.getLongitude();
temp = new LatLng(location.getLatitude(), location.getLongitude());
Log.d("Latlng : ", temp + "");
} else
{
arrTemp.add(strAddress);
System.out.println(arrTemp);
}
} catch (IOException e)
{
Toast.makeText(mContext, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
return temp;
}
But the problem is when I call this method in loop like this:
Marker TP1 = googleMap.addMarker(new MarkerOptions().position(getSingleLocationFromAddress(fullAddress)));
The line coder.getFromLocationName(strAddresNew, 1); returns null for some addresses, for example if I have an ArrayList of 7 addresses then I get only 4-5 LatLong values.
Use below lines of code...It can be helpful for you
Declare these variables above yours Oncreate or OncreatView
List<Address> From_geocode = null;
private double sLat, sLong;
private Geocoder geocoder;
Than inside yours oncreate or oncreateVIew use these lines of code
geocoder = new Geocoder(getActivity());
try {
From_geocode = geocoder.getFromLocationName("PUT THE ADDRESS HERE", 1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (From_geocode.size() > 0) {
System.out.println("2");
From_geocode.get(0).getLatitude(); // getting
// latitude
From_geocode.get(0).getLongitude();
sLat = From_geocode.get(0).getLatitude();
sLong = From_geocode.get(0).getLongitude();
System.out.println("LATITUTE====="+sLat+" LONGITUTE====="+sLong);
}
And provide the entry inside the manifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Although the google database is extensive it is possible that some of the addresses that you have supplied could not be geocoded. Hence you will not get a lat/lon for those addresses. You could probably check the status of the response.
As mentioned in the link below
https://developers.google.com/maps/documentation/geocoding/#StatusCodes
The "status" field within the Geocoding response object contains the status of the request, and may contain debugging information to help you track down why geocoding is not working. The "status" field may contain the following values:
"OK" indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned.
"ZERO_RESULTS" indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a non-existent address.

Can't get the Address from Geocoder

I have created simple code just for getting address from string location. Code brakes at starred line. Why ?? if I print the exception : Service not Available
List<Address> address;
String myAddress = "Vilnius";
Geocoder coder = new Geocoder(getApplicationContext(), Locale.getDefault());
System.out.println("coder : :" + coder);
**address = coder.getFromLocationName(myAddress, 1);**
ObjLoc1adr = coder.getFromLocationName(ObjLoc1String, 1);
ObjLoc2adr = coder.getFromLocationName(ObjLoc2String, 1);
Because of this you should always wrap that code in a try block to catch an IOException. There is no guarantee that the Geocoder always find a location or the service is reachable. This hasn't to be a fault of your code or device. A simple connection problem or timeout is enough to brake your App.
To be save have something like this:
if(GeoCoder.isPresent()) {
Geocoder geocoder = new Geocoder(this);
String myAddress = "Vilnius";
List<Address> addresses = null;
try {
address = geocoder.getFromLocationName(myAddress, 1);
if (!addresses.isEmpty()) {
Address address = list.get(0);
// do something with your address
} else {
// No results for your location
}
} catch (IOException e) {
e.printStackTrace();
}
}

in android i'm getting IOException in Geocoder

it throw IOException if the network is unavailable or any other I/O problem occurs. It need internet connection to use Geocoder.
public class MainActivity extends Activity {
double LATITUDE = 37.42233;
double LONGITUDE = -122.083;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
TextView myAddress = (TextView)findViewById(R.id.myaddress);
myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
e.printStackTrace();
myAddress.setText("Cannot get Address!");//and tell me what is
}
}
}
anyone has any idea?
I have managed to do it with Emulator 2.1 api 8, but then the reverse geocoding always give an empty result. anyone could confirm my code?
log cat
06-03 10:59:24.689: W/System.err(4129):java.io.IOException: Service not Available
:at android.location.Geocoder.getFromLocation(Geocoder.java:136)
:at com.example.gprsonandoff.MainActivity.city(MainActivity.java:74)
:at com.example.gprsonandoff.MainActivity.onCreate(MainActivity.java:44)
:android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
:at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
It seems to be a prob faced by many. Check this.
You can try using GeoCoding APIs if using Geocoder doesn't work out even if internet connection is there.
I Reboot My Android Device and Error is gone.

Categories

Resources