I am trying to get address using lat ,lng .
But its not working pasting the code below.
I really appreciate any help.
I am getting exception all the time and not the value whats the mistake?
Thanks in Advance.
googleMap.setOnMapClickListener((OnMapClickListener) new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
final LatLng pt = point;
marker2 = googleMap.addMarker(new MarkerOptions()
.position(pt)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
final ProgressDialog progressDialog = ProgressDialog.show(
MainActivity.this,
"Searching Location....", "Please wait....");
new Thread(new Runnable(){
public void run(){
try {
Toast.makeText(getBaseContext(), GeocoderUtil.getAddress(marker2.getPosition(), MainActivity.this), 5).show();
}catch(Exception e)
{
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
Toast.makeText(getBaseContext(),"error.", 5).show();
}
});
}}}
).start();
Exception:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.maps.maps.MainActivity$1.onMapClick(MainActivity.java:442)
at com.google.android.gms.maps.GoogleMap$.onMapClick(Unknown Source)
at com.google.android.gms.maps.internal.h$a.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:297)
at bor.a(SourceFile:93)
at maps.af.q.b(Unknown Source)
at maps.ap.bo.b(Unknown Source)
at maps.ap.bk.onSingleTapConfirmed(Unknown Source)
at maps.bt.g.onSingleTapConfirmed(Unknown Source)
at maps.bt.i.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4945)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
ADDRESS::FROM LAT N LONG IN MAP V2:
String address = "";
Geocoder geoCoder = new Geocoder( getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(latitude ,longitude , 1);
if (addresses.size() > 0)
{
for (int index = 0;
index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " "; }
}
catch (IOException e) {
e.printStackTrace();
}
googleMap_v2.animateCamera(CameraUpdateFactory.zoomTo(15));
current_location.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
current_address.setText("current Address :" + address );
googleMap_v2.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("current status"));
}}
Follow this code to get address:
final TextView address = (TextView) infoWindow.findViewById(R.id.Address);
address.setText(GeoCoderUtil.getAddress(marker.getPosition(), CurrentActivity.this));
GeoCoderUtil.java:
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
public class GeoCoderUtil {
public static String getAddress(LatLng latLng, Context context) {
Geocoder geocoder = new Geocoder(context);
double latitude = latLng.latitude;
double longitude = latLng.longitude;
String address = "";
try {
Log.i("Address Info","Address based opn geocoder");
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
if (addresses != null && !addresses.isEmpty()) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder();
int addressLineIndex = returnedAddress.getMaxAddressLineIndex();
int addressLinesToShow = 2;
// To get address in limited lines
if (addressLineIndex < 2) {
addressLinesToShow = addressLineIndex;
}
for (int p = 0; p < addressLinesToShow; p++) {
strReturnedAddress
.append(returnedAddress.getAddressLine(p)).append(
"\n");
}
address = strReturnedAddress.toString();
} else {
address = "Address not available";
}
} catch (IOException e) {
e.printStackTrace();
address = "Address not available";
Log.e("Address not found","Unable to get Address in info window");
}
return address;
}
public static String getDistanceByUnit(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
float[] distance = new float[1];
Log.i("Distance","Distance from source to end");
Location.distanceBetween(startLatitude, startLongitude, endLatitude,
endLongitude, distance);
String distanceByUnit = "Not Available";
DecimalFormat d = new DecimalFormat("0.00");
if (distance[0] > 999.99) {
distance[0] = distance[0] / 1000;
distanceByUnit = String.valueOf(d.format(distance[0])) + " Km";
} else {
distanceByUnit = String.valueOf(d.format(distance[0])) + " m";
}
return distanceByUnit;
}
}
Use this.
Geocoder coder;
public String PointToLoc(LatLng pos )
{
String address="";
try {
List<Address>addresses=coder.getFromLocation(pos.latitude,pos.longitude,1);
if (addresses.size()>0)
{
for (int index=0;index<addresses.get(0).getMaxAddressLineIndex();index++)
address += addresses.get(0).getAddressLine(index)+"";
Log.d("Address",""+ address); //full address
Log.d("Address1",""+ addresses.get(0).getLocality()); //city
Log.d("Address2",""+ addresses.get(0).getSubLocality()); //area
}
}
catch (IOException e)
{
e.printStackTrace();
}
return address;
}
#Override
public void onInfoWindowClick(Marker marker) {
String cur_address=PointToLoc(marker.getPosition());
//Toast the above string.You will get it.
}
Use this:
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if(i==0)
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
Related
I am developing an app,In this I'm using google map to show users current location.
Following code I am using but it doesn't give the result of street address only shows the current location in map and shows longitude and latitude.How do I show the current street address in text field from current longitude and latitude?
//java
public class LocationActivity extends Activity {
private TextView locationText;
private TextView addressText, textview;
private GoogleMap map;
String mob_no;
private boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
locationText = (TextView) findViewById(R.id.location);
addressText = (TextView) findViewById(R.id.address);
// textview=(TextView)findViewById(R.id.textView_euser);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
mob_no = sharedPreferences.getString(Config.PHONE_SHARED_PREF, "Not Available");
// textview.setText(String.valueOf(mob_no));
//replace GOOGLE MAP fragment in this Activity
replaceMapFragment();
}
private void replaceMapFragment() {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
map.setMyLocationEnabled(true);
//set "listener" for changing my location
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Marker marker;
marker = map.addMarker(new MarkerOptions().position(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");
//get current address by invoke an AsyncTask object
new GetAddressTask(LocationActivity.this).execute(String.valueOf(latitude), String.valueOf(longitude));
// getCompleteAddressString(longitude,latitude);
}
};
}
public void callBackDataFromAsyncTask(String address) {
addressText.setText(address);
}
/* #SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
addressText.setText(strAdd);
Log.w("My Current loction address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
} */
}
//getaddress
public class GetAddressTask extends AsyncTask<String, Void, String> {
private LocationActivity activity;
public GetAddressTask(LocationActivity activity) {
super();
this.activity = activity;
}
#Override
protected String doInBackground(String... params) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(activity, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(Double.parseDouble(params[0]), Double.parseDouble(params[1]), 1);
//get current Street name
String address = addresses.get(0).getAddressLine(0);
//get current province/City
String province = addresses.get(0).getAdminArea();
//get country
String country = addresses.get(0).getCountryName();
//get postal code
String postalCode = addresses.get(0).getPostalCode();
//get place Name
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
return "Street: " + address + "\n" + "City/Province: " + province + "\nCountry: " + country
+ "\nPostal CODE: " + postalCode + "\n" + "Place Name: " + knownName;
} catch (IOException ex) {
ex.printStackTrace();
return "IOE EXCEPTION";
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
return "IllegalArgument Exception";
}
}
/**
* When the task finishes, onPostExecute() call back data to Activity UI and displays the address.
* #param address
*/
#Override
protected void onPostExecute(String address) {
// Call back Data and Display the current address in the UI
activity.callBackDataFromAsyncTask(address);
}
}
You can use Double.toString() to convert a double to a String. Alternatively, you can use +:
"" + latitude
If you need more control over the output, such as the number of decimal places to display, you can use String.format().
public static void getAddressFromLocation(final double latitude, final double longitude,
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> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
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());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n\nAddress:\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n Unable to get address for this lat-long.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
more info please check below link:-
http://javapapers.com/android/android-get-address-with-street-name-city-for-location-with-geocoding/
its helps to you
i want to build a app which shows me user location on google map...but it shows me no address is found ..even when i tried to give fixed value ...
if(location!=null && !location.equals("")){
googleMap.clear();
new GeocoderTask(MainActivityMap.this).execute(location);
}
My Geocoder Asynctask Activity
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
private Context mainContxt;
Geocoder geocoder;
public GeocoderTask(Context con){
mainContxt=con;
}
#Override
protected List<Address> doInBackground(String... locationName) {
Geocoder geocoder = new Geocoder(mainContxt);
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found.Please check
address", Toast.LENGTH_SHORT).show();
return; // add this
}
else{
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
if(i==0) {
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
googleMap.addMarker(markerOptions);
}
}
}
}
i think error in this line
addresses = geocoder.getFromLocationName(locationName[0], 3);
address dosent receive anything
....thx in advance...help me friends
In my App I use This code to get Address...!!! This is for your reference.
Geocoder geocoder;
List<Address> addresses;
double latitude, longitude;
String zip, city, state, country;
googleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng arg0) {
latitude = arg0.latitude;
longitude = arg0.longitude;
String title = "";
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
zip = addresses.get(0).getPostalCode();
city = addresses.get(0).getLocality();
state = addresses.get(0).getAdminArea();
country = addresses.get(0).getCountryName();
if (zip != null) {
title += zip + ",";
}
if (city != null) {
title += city + ",";
}
if (state != null) {
title += state + ",";
}
if (country != null) {
title += country;
}
} else {
title = "Unknown Location";
showPosition.setText("Address Not Found");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// This will put marker and set Address as a marker title
googleMap.addMarker(new MarkerOptions().position(arg0).title(title));
}
});
how to set marker in google map?
MarkerOptions options = new MarkerOptions().position(latLng).title(shortDescStr);
googleMap.addMarker(options);
Hi I am working with android.I had created a GPS app for getting the current location.Now How can I get the country name from the latitude and longitude value ? is it possible ? please help me and thanks :)
here is my code I used
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
String countryCode,countryName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.i("location", " "+latitude+" "+longitude);
// \n is for new line
try
{Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(latitude,longitude, 1);
if (addresses.size() > 0)
Toast.makeText(getApplicationContext(), "name "+addresses.get(0).getLocality(),Toast.LENGTH_SHORT).show();
//System.out.println(addresses.get(0).getLocality());
}
catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude+countryName +" "+countryCode, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
String country_name = null;
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
#SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name = addresses.get(0).getCountryName();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
Finally I got the solution, without lat and long value, i got country name.
String country = getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();
.
Use this:
Geocoder myLocation = new Geocoder(AppContext);
try
{
myList = myLocation.getFromLocation(latitude, longitude, 1);
}
catch (Exception e)
{
e.printStackTrace();
}
if(myList != null)
{
try
{
String country = myList.get(0).getCountryName();}
You can Get Country name from below mentioned json. Just pass your lat-long in address. And look for "long_name" which have "country,political" in "types" array.
i.e. http://maps.googleapis.com/maps/api/geocode/json?address=23.022505,72.5713621&sensor=false
From a Geocoder object, you can call the getFromLocation(double, double, int) method. It will return a list of Address objects that have a method getLocality().
import android.location.Address;
import android.location.Geocoder;
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(1.2, 2.2256, 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
List<Address> addresses=null;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(loc.latitude, loc.longitude, 1);
System.out.println("add in string "+addresses.toArray().toString());
String countryName = addresses.get(0).getCountryName();
String countryCode = addresses.get(0).getCountryCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i am trying to find out the location name from google maps api in android when i have the longitude and latitude of the location. what i want to achieve is, after getting the location name i want to shoot an text message to my friends telling them about my current location. I am not sure if i need to turn on the geocoder service or not.
this is what i have done so far and now i m stuck.
class mylocationlistener implements LocationListener
{
#SuppressLint("NewApi")
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null)
{
Double longi = location.getLongitude();
Double lat = location.getLatitude();
String str = "";
str= "Longitude=" + longi + ", Latitude=" + lat;
Toast.makeText(getApplicationContext(),str,Toast.LENGTH_LONG).show();
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
boolean abc = Geocoder.isPresent();
try {
List<Address> addresses = geocoder.getFromLocation(lat, longi, 1);
if(!addresses.isEmpty())
{
str = addresses.get(0).getLocality() + addresses.get(0).getAddressLine(1)+ addresses.get(0).getAddressLine(2);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),str, Toast.LENGTH_LONG).show();
}
}
}
I think you are almost done with it, how I deal with this before is using the following codes:
public static String getAddressStringFromLocation(Context context, Location location) {
GeoPoint gp = new GeoPoint((int) (location.getLatitude() * 1e6),
(int) (location.getLongitude() * 1e6));
return getAddressStringFromGeoPoint(context, gp);
}
public static String getAddressStringFromGeoPoint(Context context, GeoPoint point) {
StringBuilder sb = new StringBuilder();
Address ad = getAddressFromGeoPoint(context, point);
if(ad != null && ad.getMaxAddressLineIndex() > 0) {
for(int i = 0, max = ad.getMaxAddressLineIndex(); i < max; i++) {
sb.append(ad.getAddressLine(i));
}
sb.append(ad.getThoroughfare());
return sb.toString();
} else {
return null;
}
}
public static Address getAddressFromGeoPoint(Context context, GeoPoint point){
Geocoder geoCoder = new Geocoder(context, Locale.CHINA);
Address address = null;
try {
List<Address> addresses = geoCoder.getFromLocation(point.getLatitudeE6() / 1E6, point.getLongitudeE6() / 1E6, 1);
address = addresses.get(0);
} catch (IOException e) {
e.printStackTrace();
}
return address;
}
I want to do reverse geocoding in my app using map api 2.But i dont know exactly how to do that?Any ideas?
Use Geocoder:
Geocoder geoCoder = new Geocoder(context);
List<Address> matches = geoCoder.getFromLocation(latitude, longitude, 1);
Address bestMatch = (matches.isEmpty() ? null : matches.get(0));
This is how it works for me..
MarkerOptions markerOptions;
Location myLocation;
Button btLocInfo;
String selectedLocAddress;
private GoogleMap myMap;
LatLng latLng;
LatLng tmpLatLng;
#Override
public void onMapLongClick(LatLng point) {
// Getting the Latitude and Longitude of the touched location
latLng = point;
// Clears the previously touched position
myMap.clear();
// Animating to the touched position
myMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
//tmpLatLng = latLng;
btLocInfo.setEnabled(true);
btLocInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double[] coordinates={tmpLatLng.latitude/1E6,tmpLatLng.longitude/1E6};
double latitude = tmpLatLng.latitude;
double longitude = tmpLatLng.longitude;
Log.i("selectedCoordinates", latitude + " " + longitude);
Log.i("selectedLocAddress", selectedLocAddress);
}
});
}
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>{
Context mContext;
public ReverseGeocodingTask(Context context){
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText="";
try {
addresses = geocoder.getFromLocation(latitude, longitude,1);
Thread.sleep(500);
if(addresses != null && addresses.size() > 0 ){
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
}
catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
selectedLocAddress = addressText;
return addressText;
}
#Override
protected void onPostExecute(String addressText) {
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(addressText);
// Placing a marker on the touched position
myMap.addMarker(markerOptions);
}
}
You can do like this to get complete address :
public class MainActivity extends AppCompatActivity {
...
private Geocoder geocoder;
private TextView mAddressTxtVu;
...
// assume that you got latitude and longitude correctly
mLatitude = 20.23232
mLongitude = 32.999
String errorMessage = "";
geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(
mlattitude,
mlongitude,
1);
} catch (IOException e) {
errorMessage = getString(R.string.service_not_available);
Log.e(TAG, errorMessage, e);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = getString(R.string.invalid_lat_long_used);
Log.e(TAG, errorMessage + ". " + "Latitude = " + mlattitude +",
Longitude = " + mlongitude, illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found);
Log.e(TAG, errorMessage);
}
} else {
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
// Fetch the address lines using getAddressLine,
// join them, and send them to the thread.
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
}
// Log.i(TAG, getString(R.string.address_found));
mAddressTxtVu.setText(TextUtils.join(System.getProperty("line.separator"),
addressFragments));
}
Hope it helps!
You don't need to use Google Maps Api for this purpose. Android SKD have a class for it which you can simply use without any registration of API Key and so on. The class is android.location.Geocoder. It have methods for geocoding and reverse geocoding. I was looking in the source code of this class and found that it have a method android.location.Geocoder#getFromLocationName(java.lang.String, int) where first argument is address, and second is max number of results you want. It returns a List<Address>. The Address class have methods like android.location.Address#getLatitude and android.location.Address#getLongitude. They both return double.
Try it and let me know how good it is :-)