Test123
Test123

Reputation: 368

How to get an address from map in android?

I am building an android application where user can select the address as his favorite places from map.

I need is that when any user double tap any place it should be displayed in my text View and it should work in 100% zoom.

Here is my code -

    package com.amal.googlemap;


public class MainActivitytut extends FragmentActivity{

GoogleMap map;
private static final LatLng GOLDEN_GATE_BRIDGE = 
        new LatLng(37.828891,-122.485884);
private static final LatLng APPLE = 
        new LatLng(37.3325004578, -122.03099823);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maintut);

    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    if (map == null) {
        Toast.makeText(this, "Google Maps not available", 
            Toast.LENGTH_LONG).show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is
    // present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;

}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

    case R.id.menu_sethybrid:
        map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        break;

    case R.id.menu_showtraffic:
        map.setTrafficEnabled(true);
        break;

    case R.id.menu_zoomin:
        map.animateCamera(CameraUpdateFactory.zoomIn());
        break;

    case R.id.menu_zoomout:
        map.animateCamera(CameraUpdateFactory.zoomOut());
        break;

    case R.id.menu_gotolocation:
        CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(GOLDEN_GATE_BRIDGE) // Sets the center of the map to
                                        // Golden Gate Bridge
            .zoom(17)                   // Sets the zoom
            .bearing(90) // Sets the orientation of the camera to east
            .tilt(30)    // Sets the tilt of the camera to 30 degrees
            .build();    // Creates a CameraPosition from the builder
        map.animateCamera(CameraUpdateFactory.newCameraPosition(
            cameraPosition));
        break;

    case R.id.menu_addmarker:
        // ---using the default marker---
        /*
        map.addMarker(new MarkerOptions() 
            .position(GOLDEN_GATE_BRIDGE)
            .title("Golden Gate Bridge") .snippet("San Francisco")
            .icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        */

        map.addMarker(new MarkerOptions()
            .position(GOLDEN_GATE_BRIDGE)
            .title("Golden Gate Bridge")
            .snippet("San Francisco")
            .icon(BitmapDescriptorFactory
            .fromResource(R.drawable.ic_launcher)));
        break;

    case R.id.menu_getcurrentlocation:
        // ---get your current location and display a blue dot---
        map.setMyLocationEnabled(true);

        break;

    case R.id.menu_showcurrentlocation:
        Location myLocation = map.getMyLocation();
        LatLng myLatLng = new LatLng(myLocation.getLatitude(),
                myLocation.getLongitude());

        CameraPosition myPosition = new CameraPosition.Builder()
                .target(myLatLng).zoom(17).bearing(90).tilt(30).build();
        map.animateCamera(
            CameraUpdateFactory.newCameraPosition(myPosition));
        break;

    case R.id.menu_lineconnecttwopoints:
        //---add a marker at Apple---
        map.addMarker(new MarkerOptions()
                .position(APPLE)
                .title("Apple")
                .snippet("Cupertino")
                .icon(BitmapDescriptorFactory.defaultMarker(
                          BitmapDescriptorFactory.HUE_AZURE)));

        //---draw a line connecting Apple and Golden Gate Bridge---
        map.addPolyline(new PolylineOptions()
            .add(GOLDEN_GATE_BRIDGE, APPLE).width(5).color(Color.RED));
        break;
    }
    return true;
 }
}

I had tried many method but nothing worked as what I need.... Please help..

Upvotes: 1

Views: 2571

Answers (3)

David Boho
David Boho

Reputation: 2716

At first set a OnMapClickListener to the Map.

googleMap.setOnMapClickListener(new OnMapClickListener(){
        void onMapClick(LatLng point){
            Location location = new Location("Test");
            location.setLatitude(point.latitude);
            location.setLongitude(point.longitude);
            (new GetAddressTask(this)).execute(point);
        }
    });

The GetAddressTask is described here: https://developer.android.com/training/location/display-address.html#DefineTask

Here is a excerpt of this:

protected class GetAddressTask extends AsyncTask<Location, Void, String> {
    Context localContext;
    public GetAddressTask(Context context) {
        super();
        localContext = context;
    }

    @Override
    protected String doInBackground(Location... params) {
        Geocoder geocoder = new Geocoder(localContext, Locale.getDefault());
        Location location = params[0];
        List <Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(location.getLatitude(),
                location.getLongitude(), 1);
        } catch (Exception exception) {
                return "Error Message";
        }
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressText = ((address.getMaxAddressLineIndex() > 0) ?
                                address.getAddressLine(0) : "") +  ", " +
                                address.getLocality() + ", " +
                                address.getCountryName();
            return addressText;
        } else {
            return getString(R.string.no_address_found);
        }
    }

    @Override
    protected void onPostExecute(String address) {
        textView.setText(address);
    }
}

For compatibility to Android Developers example i have simply convert the LatLng object to a Location. To remove this conversion you should extend the GetAddressTask class from AsyncTask<LatLng, Void, String> and adapt to doInBackground(LatLng... latlngs) and the `` to geocoder.getFromLocation(latlng.latitude, latlng.longitude, 1);

Upvotes: 1

Rajat kumar
Rajat kumar

Reputation: 884

To get Physical address from LAT LONG try this link-

http://android-er.blogspot.in/2011/02/get-address-from-location-using.html

To Get LAT LONG on touch event:-

how to get lat and long on touch event from google map?

First tap on Google map and get the lat long then use the geocoder to convert LatLong to Physical Address.

Upvotes: 0

Akash Moradiya
Akash Moradiya

Reputation: 3322

try this may help you,

Address address = getAddressFromLatLong(context,lat,long);
public static Address getAddressFromLatLong(Context context,double lat, double lng) {

        geocoder = new Geocoder(context);

        List<Address> list = null;
        try {
            list = geocoder.getFromLocation(lat, lng, 10);
            return list.get(0);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

Upvotes: 1

Related Questions