2

I am trying to get an address from latitude and longitude in Android Google Maps v2, but it errors.

Here is my code:

case PLACES_DETAILS :
                final HashMap<String, String> hm = result.get(0);

                final double latitude = Double.parseDouble(hm.get("lat"));
                final double longitude = Double.parseDouble(hm.get("lng"));

                SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
                googleMap = fm.getMap();

                final LatLng point = new LatLng(latitude, longitude);
                CameraUpdate cameraPosition = CameraUpdateFactory.newLatLngZoom(point, 10);
                CameraUpdate cameraZoom = CameraUpdateFactory.zoomBy(5);

                googleMap.moveCamera(cameraPosition);
                googleMap.animateCamera(cameraZoom);
                googleMap.getCameraPosition();
                //Log.e("Lat", String.valueOf(googleMap.getCameraPosition().target.latitude));
                //Log.e("Long", String.valueOf(googleMap.getCameraPosition().target.latitude));
                //googleMap.setOnMyLocationChangeListener(myLocationChangeListener);

                googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
                    @Override
                    public void onCameraChange(CameraPosition cameraPosition) {
                        Log.e("Lat", String.valueOf(googleMap.getCameraPosition().target.latitude));
                        Log.e("Long", String.valueOf(googleMap.getCameraPosition().target.longitude));
                    }
                });
Glen Thomas
  • 10,190
  • 5
  • 33
  • 65
Jeje
  • 33
  • 1
  • 1
  • 5

3 Answers3

8

Use the following code snippet:

try { 
Geocoder geo = new Geocoder(youractivityclassname.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
    yourtextfieldname.setText("Waiting for Location"); 
} 
else { 
    if (addresses.size() > 0) {
        yourtextfieldname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
        //Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show(); 
    } 
} 
}    
   catch (Exception e) {
e.printStackTrace(); // getFromLocation() may sometimes fail
} 

reference : https://mobiforge.com/design-development/using-google-maps-android

N Kaushik
  • 2,198
  • 18
  • 29
1

This should give you the address for your lat long

Geocoder geocoder;
    List<Address> addresses;
    geocoder = new Geocoder(mContext, Locale.getDefault());
    try {
        String sPlace;
        addresses = geocoder.getFromLocation(mLat, mLong, 1);
        String address = addresses.get(0).getAddressLine(0);
        String city = addresses.get(0).getAddressLine(1);
        String country = addresses.get(0).getAddressLine(2);

        String[] splitAddress = address.split(",");
        sPlace = splitAddress[0] + "\n";
        if(city != null && !city.isEmpty()) {
            String[] splitCity = city.split(",");
            sPlace += splitCity[0];
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
iZBasit
  • 1,314
  • 1
  • 15
  • 30
0

I am giving you my code, i use this code,2 months ago.. I didn't able to test this code right now, but it worked that time. may u need to modify some lines. use this function

 public void getAddressByLatLong(){
latitude = bundle.getDouble("Lat");
        longitude = bundle.getDouble("Long");
        LatLng pos = new LatLng(latitude, longitude);

        try {
            if (googleMap == null) {
                googleMap = ((MapFragment) getFragmentManager()
                        .findFragmentById(R.id.map)).getMap();
            }
            googleMap.setMapType(googleMap.MAP_TYPE_HYBRID);

            LocationManager location_manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            LocationListener listner = new MyLocationListner();
            location_manager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 3000, 5000, listner);

                    } catch (Exception e) {
            e.printStackTrace();
        }
                    }

Create a class

public class MyLocationListner implements LocationListener {

@SuppressLint("NewApi")
@SuppressWarnings("static-access")
@Override
public void onLocationChanged(Location arg0) {


        Toast.makeText(getApplicationContext(),
                "In on Location Changed", Toast.LENGTH_SHORT).show();
        // TODO Auto-generated method stub
        getLatitude = "" + arg0.getLatitude();
        getLongitude = "" + arg0.getLongitude();

        // lati.setText(getLatitude + "," + getLongitude);

        latitude = arg0.getLatitude();
        longitude = arg0.getLongitude();



    try {

        geocoder = new Geocoder(DisplayActivity.this, Locale.ENGLISH);
        addresses = geocoder.getFromLocation(latitude, longitude, 1);

        if (geocoder.isPresent()) {
            Toast.makeText(getApplicationContext(), "geocoder present",
                    Toast.LENGTH_SHORT).show();

            Address returnAddress = addresses.get(0);

            String localityString = returnAddress.getLocality();
            String city = returnAddress.getCountryName();
            String region_code = returnAddress.getCountryCode();
            String zipcode = returnAddress.getPostalCode();
            str = new StringBuilder();
            str.append(localityString + " ");
            str.append(city + " ");
            str.append(region_code + " ");
            str.append(zipcode + " ");

            // Add = str.toString();
            // longi.setText(str);

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(latitude, longitude)).zoom(2)
                    .build();

            googleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));
            MarkerOptions marker = new MarkerOptions().position(
                    new LatLng(latitude, longitude)).title(
                    str.toString());
            marker.icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.mario));

            googleMap.addMarker(marker);
            Toast.makeText(getApplicationContext(), str,
                    Toast.LENGTH_SHORT).show();
        } else
            Toast.makeText(getApplicationContext(),
                    "geocoder not present", Toast.LENGTH_SHORT).show();

    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Exception",
                Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onProviderDisabled(String arg0) {
}

@Override
public void onProviderEnabled(String arg0) {
}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}

}

Himanshu Shekher Jha
  • 1,334
  • 2
  • 14
  • 27