I am getting current latitude and longitude in map box, I need current timezone based on current latitude and longitude.
For example.My device time is the USA but my location showing in India so I need India timezone.Can you please help me.
#Override
public void onLocationChanged(Location location) {
try {
mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
Log.i("EE","mLatLngmLatLng"+mLatLng);
String time = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS").format(location.getTime());
Log.i("EE","time----"+time);
Log.i("EE","vlocation.getTime()----"+location.getTime());
updateCamera();
if (mMarker != null) {
updateMarker();
}else{
addMarker();
}
} catch (Exception e) {
e.printStackTrace();
}
Get address by Geocoder and identify country, When you will get the country name It will be easy for you to identify the time Zone.
private void getAddressFromLocation(double latitude, double longitude) {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append(" ");
}
txtLocationAddress.setText(strAddress.toString());
} else {
txtLocationAddress.setText("Searching Current Address");
}
} catch (IOException e) {
e.printStackTrace();
printToast("Could not get address..!");
}
}
Related
Hi, I am fetching users current location and complete Address in my app. I am getting Latitude and Longitude using this code :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
private void getCurrentLocation() {
Task<Location> task = client.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
//when success
public void onSuccess(final Location location) {
if (location != null) {
//sync map
Log.e("Getting Lat", String.valueOf(location.getLatitude()));
Log.e("Getting Long", String.valueOf(location.getLongitude()));
String address = getCompleteAddressString(location.getLatitude(), location.getLongitude());
userLocation.setText(aa.trim());
}
}
Output :
Getting Lat :26.1738506
Gettig Long :91.7741039
This is the code for getting complete address from latitude and longitude:
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
Log.e("My loction address", strReturnedAddress.toString());
} else {
Log.e("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.e("My Current loction address", "Canont get Address!");
}
return strAdd;
}
I am getting the complete address as well , but the Issue is this code executes only after I try for 10-15 times.
Also, please note, this code executes on onCreateView method and runs on the mainThread . What should I do , so that this i can get the current location everytime I launch the app
UPDATE : I realised getLastLocation() might be null. So, what is the workaround here ? Pls help
I am working on an app which works with latitude and and longitude after a user input an address. I'm utilizing Geocoder to get the latitude and longitude from the Input address. But the issue is both are returned with associated address from the Geocoder but I'm only able to read one of them. following is the code I'm using:
Geocoder geocoder = new Geocoder(this);
List<Address> addresses;
double[] cordinates = new double[2];
try {
addresses = geocoder.getFromLocationName(locName, 1);
if (addresses.size() > 0) {
cordinates[0] = addresses.get(0).getLatitude();
cordinates[1] = addresses.get(0).getLongitude();//unable to get this one
return cordinates;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
in the above cases I'm able to get latitude but unable to get the longitude. I known this after debugging. Now when I swap them like
cordinates[1] = addresses.get(0).getLongitude();
cordinates[0] = addresses.get(0).getLatitude();
Now I get Longitude but not the latitude.
what is the problem here?
This is working fine. Since you are debugging your code with breakpoints when it encounters the
return cordinates; it goes to
return null;
It only happens while debugging. It always returns the correct value. You can check returned values by inserting a log statement.
{
.....
double[] coordinates = getLongLat("Your address");
Log.wtf(TAG,"Lat:"+coordinates[0]+" Long:"+coordinates[1]);// This will log the correct values
.....
}
public double[] getLongLat(String address){
Geocoder geocoder = new Geocoder(this);
List<Address> addresses;
double[] cordinates = new double[2];
try {
addresses = geocoder.getFromLocationName(address, 1);
if (addresses.size() > 0) {
Address address1 = addresses.get(0);
cordinates[0] = address1.getLatitude();
cordinates[1] = address1.getLongitude();
return cordinates;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Try this working code :
AutoCompleteTextView acGooglePlaces = (AutoCompleteTextView) findViewById(R.id.ac_edit_my_event_places);
acGooglePlaces.setAdapter(new GooglePlacesAutocompleteAdapter(GooglePlaces.this, R.layout.auto_complete_text_layout));
acGooglePlaces.requestFocus();
btnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
List<Address> returnedaddresses = geoCoder.getFromLocationName(acGooglePlaces.getText().toString(),1);
if(!returnedaddresses.isEmpty()){
String latForVol = String.valueOf(returnedaddresses.get(0).getLatitude());
String longForVol = String.valueOf(returnedaddresses.get(0).getLongitude());
Log.e("Lat", latForVol);
Log.e("Long", longForVol);
Log.e("Location", acGooglePlaces.getText().toString());
}else {
Log.e("Check", "Please give the correct address");
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
public static LatLng reverseGeocoding(Context context, String locationName){
if(!Geocoder.isPresent()){
Log.w("zebia", "Geocoder implementation not present !");
}
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(locationName, 1);
} catch (IOException e) {
Log.d(Geocoding.class.getName(), "not possible finding LatLng for Address : " + locationName);
}
if(addresses.size() > 0){
Log.d("zebia", "reverse Geocoding : locationName " + locationName + "Latitude " + addresses.get(0).getLatitude() );
return new LatLng(addresses.get(0).getLatitude(), addresses.get(0).getLongitude());
}else{
//use http api
}
return null;
}
I am trying to get the full address by providing longitude and latitude coordinates. for now i succedd to get the coordinates correctly
this is what i get:
my coordinates﹕ 32.6653854,35.1051237
now when i use getCompleteAddressString()
i get all the time exception:
Current location address﹕ Can not get Address!
this is my getCompleteAddressString function:
public String getCompleteAddressString(double LATITUDE, double LONGITUDE, Context ctx) {
String strAdd = "";
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
Log.w("My Current location address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current location address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current location address", "Can not get Address!");
}
return strAdd;
}
and this is the class where i try to run it:
#Override
public void updateUI() {
Log.d("my location","updateUI");
Log.d("get coordinates","my location");
String realAddress = myLocManager.getCompleteAddressString(myLocManager.getmLastLocation().getLatitude(),myLocManager.getmLastLocation().getLatitude(),this.getActivity().getApplicationContext());
Log.d("my coordinates", String.valueOf(myLocManager.getmLastLocation().getLatitude()+","+myLocManager.getmLastLocation().getLongitude()));
Log.d("my real address",realAddress);
if(realAddress != null)
streetAddress.setText(realAddress);
}
i try to run updateUI also with getActivity() method but still i got the same error.
when i used LocationManager in other app it was work good.
it was my mistake i call the method with the wrond parameters:
getmLastLocation().getLatitude(),myLocManager.getmLastLocation().getLatitude()
i pass the Latitude param twice
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 try to get place(ex: locality, country, postal code) form google map using
latitude and longitude. The following is my code that got null data:
Edit:
public void onLocationChanged(Location location) {
geocoder = new Geocoder(this, Locale.getDefault());
if (location != null) {
try {
addresses = geocoder.getFromLocation(location.getLatitude()/1E6,
location.getLongitude()/1E6, 1);
if (addresses.size() > 0) {
resultAddress = addresses.get(0);
locality = resultAddress.getLocality();
sublocality = resultAddress.getSubLocality();
postalcode = resultAddress.getPostalCode();
country = resultAddress.getCountryName();
adminarea = resultAddress.getSubAdminArea();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I tried to assign latitude and longitude manually, but got nothing.
Any one can correct my mistakes ? Thank you
I think the problem is on the parameters of the method. I guess that location is a GeoPoint In that case, instead of
addresses = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
try this:
addresses = geocoder.getFromLocation(location.getLatitude()/1E6,
location.getLongitude()/1E6, 1);
because the coordinates in a geopoint are represented in microdegrees
Edit
I copied your code and tried it. Assuming your "location" object is a GeoPoint, the code that works is as follows:
GeoPoint location = new GeoPoint(lat, lon);
if (location != null) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitudeE6()/1E6,
location.getLongitudeE6()/1E6, 1);
if (addresses.size() > 0) {
Address resultAddress = addresses.get(0);
String locality = resultAddress.getLocality();
String sublocality = resultAddress.getSubLocality();
String postalcode = resultAddress.getPostalCode();
String country = resultAddress.getCountryName();
String adminarea = resultAddress.getSubAdminArea();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
however, if you are testing it on the emulator, be sure you have internet connection. Otherwise, the method "getFromLocation" cannot find out the address and won't display anything. If you don't have any error in the logcat and the problem is only that nothing is displayed, that is the problem: no network.
Do you have the <uses-permission android:name="android.permission.INTERNET" /> in manifest.xml?