How to save LaTLang in Android - android

Hi dears I am searching location from google map and getting it.Now I want to save it so that I can use it again by getting from database. Now tell me How I save it and How I retrieve it from database in LatLang form
here is My code for for searching location from map.
LatLng latLng;
btn_find.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Getting user input location
String location = etLocation.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
}
}
});
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));
}
}
}
now tell me please that how I save this location by save button ?

I think you can use SharedPrefrence for this like the following
declare SharedPreferences settings;
settings = context.getSharedPreferences("myprefs", 0); //global declaration in oncreate
inside onPost of assync task
#Override
protected void onPostExecute(List 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());
SharedPreferences.Editor editor = settings.edit();
editor.putString("latitude", Double.toString(address.getLatitude().toString()));'
editor.putString("longitude", Double.toString(address.getLongitude()));
editor.commit();
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));
}
}
}
to get the values
String latitude=settings.getString("latitude","0");
String longitude=settings.getString("longitude","0");
double lati = Double.parseDouble(lat);
double lngi = Double.parseDouble(lng);
LatLng LOCATION = new LatLng(lati, lngi);

To save in the database;
DBLocation helper1=new DBLocation(getBaseContext());
database = helper1.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ONLINELOCATION_lATITUDE, latitude);
values.put(ONLINELOCATION_LONGITUDE, longitude);
Log.i("Insert Into Database","Insert");
database.insert(ONLINELOCATION_TABLE, null, values);
To retrieve:
Cursor callpending_cursor=null;
database=helper1.getReadableDatabase();
callpending_cursor=database.query(ONLINELOCATION_TABLE, new String[] {ONLINELOCATION_ID,ONLINELOCATION_AID_ID,ONLINELOCATION_USERID_ID,ONLINELOCATION_lATITUDE,ONLINELOCATION_LONGITUDE,ONLINELOCATION_ID +" DESC"}, null, null, null, null, null);
Log.i("step8","step8");
//callpending_cursor.moveToLast();
if(!callpending_cursor.isAfterLast()) {
callpending_cursor.moveToFirst();
do{
Log.i("step9","step9");
String callpending_id=callpending_cursor.getString(0);
Aid_ID=callpending_cursor.getString(1);
USER_Id=callpending_cursor.getString(2);
USER_Latitude=callpending_cursor.getString(3);
USER_Longitude=callpending_cursor.getString(4);
callpending_cursor.moveToNext();

Related

Google Maps taking minutes to return address

I'm using Maps API to return an address. This was working fine, then sometime last week, w/o changing anything, it started taking 26 minutes to return an address. I traced it and found that after I hit the search button, it took 26 minutes for the Geocoder to be called, not that it was taking the Geocoder 26 minutes to retrieve the address. I don't think this is a coding issue, but maybe something else that someone else has experienced. I've included the code below. I'm testing on a Samsung GalaxyTab 8 (SM-T550) Android: 6.0.1
Button setup in fragment:
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String address = addressEdit.getText().toString();
//remove text from address
addressEdit.setText("");
//hide keyboard
final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
//submit address if one has been typed in
if(address != null && !address.equals("")){
//submit address to be found
new GeocoderTask().execute(address);
//submit the latlng of the marker on the map if not null
} else if (latLng != null){
address = getCompleteAddressString(latLng.latitude, latLng.longitude);
new GeocoderTask().execute(address);
//no address was entered
} else {
Toast.makeText(getContext(), R.string.no_address_entered, Toast.LENGTH_LONG).show();
}
}
});
Geocoder class:
public class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
private static final String TAG = "GeocoderTask";
#Override
protected List<Address> doInBackground(String... locationName){
Geocoder geocoder = new Geocoder(getContext());
List<Address> addresses = null;
try{
//return only 1 address
addresses = geocoder.getFromLocationName(locationName[0], 1);
}catch (IOException e){
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getContext(), R.string.no_location, Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
map.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());
// get the string address based on the retrieved latlng
String addressText = getCompleteAddressString(latLng.latitude, latLng.longitude);
/* convert address from list into string
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
*/
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
map.addMarker(markerOptions);
// Locate the first location
if(i==0) {
//map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
//call dialog fragment to confirm patient address
FragmentManager fragmentManager = getFragmentManager();
//load latlng and string address google maps returns
ConfirmAddressDialogFragment dialogFragment = ConfirmAddressDialogFragment.newInstance(addressText, latLng, patientName);
//set target fragments and show dialog
dialogFragment.setTargetFragment(MapFragment.this, REQUEST_ADDRESS);
dialogFragment.show(fragmentManager, DIALOG_ADDRESS);
}
}
}
}

Getting different latitude and longitude value for same location by searching through EditText and by clicking on the map

public class AddNewLocationActivity extends Activity {
GoogleMap googleMap;
EditText edtLocation;
Marker marker;
List<Address> addressList = null;
VibRIngDatabase vibRIngDatabase;
double latitude, longitude;
Geocoder geocoder;
LatLng latLng;
String locationAddress, name, mode;
AlertDialog.Builder dialogBuilder;
double lati1, longi1;
TextView lat, longi, location_name;
RadioButton selectedModeRadioButton;
RadioGroup rg;
Button setMode;
int selectedId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addnewlocation);
createMapView();// Rendering the Google Map in the fragment
addMarkerAtCurrent(); // Adding marker at the current location of the device
mapClick(); // On clicking the map
vibRIngDatabase = new VibRIngDatabase(this);
}
//Display the Google Map inside the fragment
private void createMapView() {
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.setMyLocationEnabled(true); //To See my current location
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Error creating map", Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception) {
Log.e("mapApp", exception.toString());
}
}
// Adding marker to the current location
public void addMarkerAtCurrent() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
latitude = myLocation.getLatitude();
// Get longitude of the current location
longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
String address = getLocationAddress(latitude, longitude);
marker = googleMap.addMarker(
new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(address));
// Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
}
public LatLng search(View v) {
edtLocation = (EditText) findViewById(R.id.edtLocation);
String location = edtLocation.getText().toString();
if (location != null) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
// To get address from list<Address>
Address address = addressList.get(0);
String locality = address.getLocality();
String adminArea = address.getAdminArea();
String locationAddress = locality + " " + adminArea;
latitude = address.getLatitude();
longitude = address.getLongitude();
latLng = new LatLng(latitude, longitude);
googleMap.clear();
marker = googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
}
return latLng;
}
// Clicking the GoogleMap
public LatLng mapClick() {
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng arg) {
latLng = arg;
latitude = latLng.latitude;
longitude = latLng.longitude;
String name = getLocationAddress(latitude, longitude);
googleMap.clear();
marker = googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
return latLng;
}
public String getLocationAddress(double lat, double longi) {
latitude = lat;
longitude = longi;
geocoder = new Geocoder(getApplicationContext());
try {
addressList = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
String addressLine = address.getAddressLine(0);
String locality = address.getLocality();
String adminArea = address.getAdminArea();
locationAddress = addressLine + " " + locality + " " + adminArea;
return locationAddress;
}
// On clicking add button openDialog method will be called
public void openDialog(View v) {
dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_dialog, null, false);
dialogBuilder.setTitle("Set Mode");
dialogBuilder.setView(view);
AlertDialog dialog = dialogBuilder.create();
dialog.show();
lat = (TextView) view.findViewById(R.id.lblLatitude);
longi = (TextView) view.findViewById(R.id.lblLongitude);
location_name = (TextView) view.findViewById(R.id.lblLocationName);
setMode = (Button) view.findViewById(R.id.btnSetMode);
latLng = marker.getPosition();
lati1 = latLng.latitude;
longi1 = latLng.longitude;
name = getLocationAddress(lati1, longi1);
lat.setText(Double.toString(lati1));
longi.setText(Double.toString(longi1));
location_name.setText(name);
rg = (RadioGroup) view.findViewById(R.id.modesRadioGroup);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.vibrationRadioButton:
Toast.makeText(getApplicationContext(), "Vibration clicked", Toast.LENGTH_LONG).show();
break;
case R.id.muteRadioButton:
Toast.makeText(getApplicationContext(), "Mute clicked", Toast.LENGTH_LONG).show();
break;
case R.id.ringingRadioButton:
Toast.makeText(getApplicationContext(), "Ringing clicked", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
});
}
}
Here in this code ,I am using the concept of Google Map.We can search a location by entering location name through EditText and then clicking on Search Button which call search() method .Here i will get the latitude and logitude of entered location.Also i can click on map which will call onMapClick() method.Here also i can get the latitude and longitude of the clicked position.While executing this code , i am getting different latitude and longitude value using these 2 methods for the same location.Just focus on search() and onMapClick() method .Please help me the resolve the issue.

Location within 100 km using Google Maps within Android

I am working on an Android application and Google Maps in which I am searching for the particular address by using the following code. I want to get the location of the searched address if it is in 100km within my location, and if it outside that limit, it will not show me.
I am trying to get the searched location within my 100km radius.
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 {
//
//24.798406, 54.790448
//25.452403, 55.537519
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 10,
24.861969, 54.857740,25.545368, 55.474347);//.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
mMap.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
LatLng latLng;
// 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.icon(BitmapDescriptorFactory.fromResource(R.drawable.flag));
markerOptions.title(addressText);
mMap.addMarker(markerOptions);
// Locate the first location
if(i==0)
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
You can calculate distance using this code; here, distance is in meters. You can call this function and check where the location is in the range or not.
private boolean checkForArea(int rad, LatLng fromPosition, LatLng toPosition) {
Location locationA = new Location("point A");
locationA.setLatitude(fromPosition.latitude);
locationA.setLongitude(fromPosition.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(toPosition.latitude);
locationB.setLongitude(toPosition.longitude);
int distance = (int) locationA.distanceTo(locationB);
if (distance / 1000 <= rad)
return true;
else
return false;
}

java.util.arraylist cannot be cast to android.location.address

Im trying to put all addresses (Strings) into a list and then get them one by one and populate a map with markers, but i get this error saing that java.util.arraylist cannot be cast to android.location.address. any help?
this is the snipet of code that generates the error
int i = 0;
List<List<Address>> addressList = new ArrayList<List<Address>>();
//while (indirizzi != null) {
while (i <= 3) {
try {
addressList.add(geocoder.getFromLocationName(indirizzi.get(i), 1));
Log.i("indirizzo i-esimo",indirizzi.get(i));
i++;
} catch (IOException e) {
Log.i("geolocation","geolocation IOException");
e.printStackTrace();
}
}
for (int j = 0; j < addressList.size(); j++) {
Address address = (Address) addressList.get(j);
if(address.hasLatitude() && address.hasLongitude()){
latLng = new LatLng(address.getLatitude(), address.getLongitude());
}
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(indirizzi.get(i));
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icn_albero));
Log.i("for", Integer.toString(i));
j++;
googleMap.addMarker(markerOptions);
}
Look at the definition , it is a List of List of Address.
List<List<Address>> addressList = new ArrayList<List<Address>>();
You cannot do this :
Address address = (Address) addressList.get(j);
As this will give you a List<Address> which is not an Address object.
You can possibly do :
Address address = (Address) addressList.get(j).get(someOtherIndex);
Define the List as :
List<Address> addressList = new ArrayList<Address>();
I have Used the below code.
I have called the GeocoderTask class from the oncreate.
ed.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
addresstext = (String) parent.getItemAtPosition(position);
Toast.makeText(getBaseContext(),""+addresstext+ "", Toast.LENGTH_SHORT).show();
if(addresstext!=null && !addresstext.equals("")){
new GeocoderTask().execute(addresstext);
}
}
});
-
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 10 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 10);
System.out.println(" Inside Background Process");
} 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
if(marker!=null){
marker.remove();
}
// 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 latLng = new LatLng(address.getLatitude(), address.getLongitude());
addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
System.out.println(" Inside OnPostExecutemeathod Process");
Toast.makeText(getBaseContext(), ""+address.getLatitude()+" - "+address.getLongitude()+"", Toast.LENGTH_SHORT).show();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to Mountain View
.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));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
marker = map.addMarker(new MarkerOptions()
.position(latLng)
.title(""+addresstext+""));
marker.showInfoWindow();
}
}

How to reverse Geocode in google maps api 2 android

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 :-)

Categories

Resources