0

The Problem which was causing: Geocoding need a connection to Google Api's. On Genymotion I didn't had till I installed 'Gapps'.

The Solution: e.g Install Gapps on Genymotion

I wan't to get the Location informations from longtitude and latitude. In my other app this function works great but in my other projects it didn't working at all.

Do it requires a google json file for it? A key? A whatever ?

I didn't find a solution yet. I really don't know why it returns everytime null. I tried with several locations.

private String getLocationFromLongLati(String longi, String lati) throws IOException {
        if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1001);
        } else {
            Geocoder geocoder = new Geocoder(MainActivity.this, Locale.GERMAN);
            List<Address> nm = geocoder.getFromLocation(Double.valueOf(lati), Double.valueOf(longi), 1);
            if(nm != null && nm.size()>0) {
                return nm.get(0).getPostalCode() + ", " + nm.get(0).getLocality();
            }
        }
        return null;

    }
J.Doe
  • 177
  • 1
  • 2
  • 13
  • What does "it didn't working at all" mean? Is there an error message involved? – Nico Haase Jan 24 '18 at 08:52
  • Hey, no theres no error. No Logcat. Only if I remov the if statement it gives me an inbound exception, Geocoder returns always null – J.Doe Jan 24 '18 at 08:54
  • instead of return null value store your address in one variable than return it at the end...it will solve your issue – Lokesh Desai Jan 24 '18 at 09:00
  • @Lokesh Thanks but it didn't worked too – J.Doe Jan 24 '18 at 09:04
  • 1
    did you read `android.location.Geocoder` documentation? `" 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. Use the isPresent() method to determine whether a Geocoder implementation exists."` – pskink Jan 24 '18 at 09:04
  • Please check this link and try to implement in proper way https://javapapers.com/android/android-get-address-with-street-name-city-for-location-with-geocoding/ – Lokesh Desai Jan 24 '18 at 09:06
  • Welcome to Stack Overflow! To give you a great answer, it might help us if you have a glance at [ask] if you haven't already. It might be also useful if you could provide a [mcve]. – Mat Jan 24 '18 at 09:08
  • so what does `Geocoder#isPresent()` return? – pskink Jan 24 '18 at 09:14
  • It returns false. So I need a backend service, and I read that it needs a connections to Google API's. So maybe this is causing because I use the emulator. So I installed Gapps on Genymotion and I will try if this is the cause of it. – J.Doe Jan 24 '18 at 09:16
  • so you have your answer why you got null or empty list... – pskink Jan 24 '18 at 09:19
  • Not yet, genymotion not responsing after install of gaps....Funny... only problems with updating windows 10 – J.Doe Jan 24 '18 at 09:20
  • Okay, on my phone it is working. Not on the emulator... – J.Doe Jan 24 '18 at 09:21
  • Yeah, after connections to google Apis it worked! – J.Doe Jan 24 '18 at 09:26

4 Answers4

0

You can try this method to get the location details(name) by its LatLng. It works fine for me. Just change your class name from MainActivity to yours in Geocoder constructor.

private String getAddressFromLatLng(LatLng latLng) {
    Geocoder geocoder = new Geocoder(MainActivity.this);

    String address = "";
    try {
        address = geocoder
                .getFromLocation(latLng.latitude, latLng.longitude, 1)
                .get(0).getAddressLine(0);
    } catch (IOException e) {
    }
    return address;
}

You can use this method anywhere in the activity where you require the address of LatLng.

Hope this helps you.

0

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

I used this much more reliable way to get the address every time:

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


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;
}
Deep Lathia
  • 750
  • 7
  • 18
0

You can try !

public static Address getAddress(LatLng latLng) {
            if(latLng != null){
                Geocoder geocoder;
                List<Address> addresses;
                geocoder = new Geocoder(context, Locale.getDefault());

                try {
                    addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
                    return addresses.get(0);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }



    public static String getInfoAddress(Address address) {
                if (address != null) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                        sb.append(address.getAddressLine(i)).append(", ");
                    }
                    return sb.toString();
                }
                return StringUtils.EMPTY;
            }
Iris Louis
  • 297
  • 6
  • 19
0

Add this library in gradle file

implementation 'com.google.android.gms:play-services-location:11.8.0'

Add Permission in Manifest file

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Here is the code

private FusedLocationProviderClient mFusedLocationClient;
private void getCurrentLatLong() {
    //get Current Location
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext);
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }


    mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if (location != null) {

                Log.e("location", location.getLatitude() + "----" + location.getLongitude() + "----" + location.getSpeed());
            } else
                Toast.makeText(mContext, "Get Current Location not found", Toast.LENGTH_SHORT).show();
        }
    });
}
Saurabh Vadhva
  • 511
  • 5
  • 12