14

I have been trying to geocode a string to get its coordinates but my program always crashes because when ever I try to use getFromLocationName() it returns null. I have been trying to fix this for hours but nothing is working. Here is my code

public class MainActivity extends Activity {

    private GoogleMap mMap;

    List<Address> addresses;
    MarkerOptions miami;
    String myLocation = "Miami,Florida";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (mMap == null) {
            mMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();
        }

        if (mMap != null) {

            Geocoder geocoder = new Geocoder(this);


            double latitude = 0;
            double longitude = 0;

            while(addresses==null){
            try {
                addresses = geocoder.getFromLocationName(myLocation, 1);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
            Address address = addresses.get(0);
            if (addresses.size() > 0) {
                latitude = address.getLatitude();
                longitude = address.getLongitude();
            }
            LatLng City = new LatLng(latitude, longitude);

            miami = new MarkerOptions().position(City).title("Miami");

            mMap.addMarker(miami);

            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(City, 15));

        }
}
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
anishk25
  • 181
  • 1
  • 1
  • 11

1 Answers1

27

Geocoder doesn't always return a value. You can try to send a request 3 times in a for loop. I should be able to return atleast once. If not then, their might be a connection issue or can be other issues like server dis not reply to your request. Try and see these threads:

Geocoder doesn't always return a value and geocoder.getFromLocationName returns only null

Updated:

I had a while loop as well but I used to try it maximum for 10 times. Sometimes, it never returned anything even if it was connected t internet. Then, I used this much more reliable way to get the address everytime:

public JSONObject getLocationInfo() {

        HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
            } catch (IOException e) {
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    

I called it as follows:

JSONObject ret = getLocationInfo(); 
JSONObject location;
String location_string;
try {
    location = ret.getJSONArray("results").getJSONObject(0);
    location_string = location.getString("formatted_address");
    Log.d("test", "formattted address:" + location_string);
} catch (JSONException e1) {
    e1.printStackTrace();

}

Hope this helps. I was also tired of relying on geocoder. This worked for me. If you replace the URL with the lat and longitude coordinates and see the returned JSON object in a web browser. You'll see what just happened.

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
  • but I have a while loop to make sure I get a value for geocoder, and it keeps looping forever. – anishk25 Mar 06 '13 at 04:18
  • See my updated answer. Hope it solves what you are trying to achieve. – Shobhit Puri Mar 06 '13 at 06:04
  • 1
    I face the same [problem](http://stackoverflow.com/questions/15110528/service-not-available-while-calling-geocoder-getfromlocation). And I found out that the `NetworkLocator` on the device has stopped working or killed for some reason(not in our hands). You can actually confirm this by re-booting your device. It must work now(since `NetworkLocator re-boots too`). – Archie.bpgc Mar 09 '13 at 05:28
  • 1
    There are 3 cases. **1. you won't get the location 1st time, then you try to loop and get it 4th/5th time etc..**, **2. No matter how many times you loop, you wont get any location details, so you assume the service might be down temporarily and go with the above solution**, **3. Like I explained in the above comment, It will never work unless you restart your device, which mean I will always go throught step-1 and step-2, which might take some 2-5 secs everytime**. No one wants to wait for so much time just to get a single data like `addressline`. Any better solution for case-3? – Archie.bpgc Mar 09 '13 at 05:33
  • You are extremely right. I was having the same issue. It used to work correctly when I used to restart the phone. So, I decided not to using the Geocoder. After getting the coordinates, getting the addressline in a JSON object by sending an HTTP request worked fine for me. Till now its giving no problems. – Shobhit Puri Mar 09 '13 at 05:46
  • Yeah. Seems like currently that's the only solution. The only problem is it will be slow. Thanks for your input. – Archie.bpgc Mar 09 '13 at 06:05
  • Yeah. I also searched for the solution in lot of threads but no luck. If you get any solution for the problem, please do post it. It would be really helpful. Thanks :) – Shobhit Puri Mar 09 '13 at 06:12
  • the problem is I don't know the coordinates of the location I want to map. I want to map the location directly from a string. The above code needs a lat and lng but I don't have those – anishk25 Mar 12 '13 at 02:19
  • Their is something known as "Reverse Geocoding". I never tried it but you can google to know about it more. Read this thread: http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation – Shobhit Puri Mar 12 '13 at 04:30
  • @shobhipuri, thanks you have provided a good solution but i do have some doubt ,here you using geocoding on server side in which you have to make call to geocode api (http call) will intern return address if there is any address is available for particular location(which limit is 2500 request per day), but why the geocoding from android doesn't works at first place is still not clear, Is there any time out period so google map server will not respond to your request??? hope you will replay as soon as you read this comment!!!! – Dev Jun 12 '14 at 07:12
  • @Dev Apologies for the late reply. Just saw it again. This HTTP call I make from the user's device to Google's servers. I am really not sure why Geocoder is not that reliable. – Shobhit Puri Nov 15 '14 at 18:37
  • @Shobhit: the answer is written here: https://developer.android.com/training/location/display-address.html Note: Address lookup requires a backend service that is not included in the core Android framework. If this backend service is not available, Geocoder.getFromLocation() returns an empty list. The helper method isPresent(), available in API level 9 and later, checks to see if the backend service is available. – marco Jan 04 '15 at 22:30
  • @Shobhit: your function doesn't handle utf-8. Better to use BufferedReader: String line; BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); while ((line = rd.readLine()) != null) result.append(line); Anyway, thanks for the hint. – marco Jan 04 '15 at 23:28
  • @ShobhitPuri : Ur answer works fine for me...now can you tell me how to do the reverse?? i.e input an address and get the latitude and longitude??? – Benedict Apr 22 '16 at 06:46
  • 1
    @Ben See something liek http://stackoverflow.com/questions/15711499/get-latitude-and-longitude-with-geocoder-and-android-google-maps-api-v2 – Shobhit Puri Apr 22 '16 at 13:21
  • Just restart your phone – Alaa M. Nov 15 '16 at 20:45