How to Request Location Updates in Android Studio - android

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

Related

How to get the place address from specified latitude and longitude with Google Place API

I'm making a cab booking app like Uber,
User drag the map to choose his location with the pin,
And I grab the LatLng of that pin.
This is my code:
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
pinLocation = mMap.getCameraPosition().target;
setPickupLocationPrefs(pinLocation);
}
});
//Initialize Google Play Services
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
updateLocationUI();
}
}
else {
buildGoogleApiClient();
updateLocationUI();
}
}
I want to get the place address of that pin to show to my users if the app operate in that location or not (like uber does).
How can I get that address from pin location coordinate?
Use Reverse Geocoding. First get Latitude and Longitude from pin point. better to handle this in background thread. otherwise it will block UI.
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
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());
}
String Address=sb.toString());
}catch(Exception E);
SOLUTION TO FIX UI BLOCKING
Full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.
Geocoder call procedure, can be located in a Helper class
public static void getAddressFromLocation(
final Location location, 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> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality();
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to Geocoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
Here is the call to this Geocoder procedure in your UI Activity/Fragment:
getAddressFromLocation(PinPointLocation, mContext, new GeocoderHandler());
And the handler class within Activity/Fragment to show the results in your UI:
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String result;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
result = bundle.getString("address");
break;
default:
result = null;
}
// replace by what you need to do
myLabel.setText(result);
}
}

How to get timezone based on current latitude and longitude?

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..!");
}
}

Failed to retrieve street address from cordinates

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

Retrieve user current location using Google play service in not working

I'm using new Google API for retrieving current location, and I got the current location. However, if the location services are not enabled in the app by default, and if I enable any location service using location intend, the client does not reconnect, in onActivityResult method, and I cannot fetch the current location.
public void onConnected(Bundle bundle) {
// TODO Auto-generated method stub
System.out.println(R.string.connected);
System.out.println("error");
startPeriodicUpdates();
if (mUpdatesRequested) {
startPeriodicUpdates();
}
if (!locationServiceEnabled)
return;
if(mLocationClient.isConnected()&& servicesConnected())
{
fetchlocation = new FetchingLocation(getActivity());
// mLocationClient = new LocationClient(getActivity(), this,this );
Location currentLocation = mLocationClient.getLastLocation();
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>" +
mLocationClient.getLastLocation());
latitude=currentLocation.getLatitude();
System.out.println(currentLocation.getLatitude());
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
+ String.valueOf(latitude));
}
else
{
}
}
But I can't get the location. As the app crashes, it shows the error:
client not connected wait for connect
Any ideas on how to solve this issue?
You have to get longitude and latitude value and then juste use that function
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 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();
}
return address;
}
Refer to this tutorial
http://www.codeproject.com/Articles/112044/GPSLocator-App-to-Find-Current-Nearest-Location-us
public void setLatLong(double lat, double lng) {
Longitude = lng;
Latitude = lat;
}
public double getLatitude() {
return Latitude;
}
public double getLongitude() {
return Longitude;
}
public void getLocation() {
locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Utility obj = new Utility(context);
if (obj.isGPSAvailable() && obj.isInternetAvailable())
{
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, locListener);
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0, 0, locListener);
}
else
Toast.makeText(context, "Internet or GPS not available",
Toast.LENGTH_LONG).show();
if (locManager != null)
{
Location loc = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc!=null)
{
setLatLong(loc.getLatitude(), loc.getLongitude());
}
else
{
loc = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(loc!=null)
{
setLatLong(loc.getLatitude(), loc.getLongitude());
}
}
}
}
Use above code for retrieving current location and you could get more help # following link:
http://www.vogella.com/articles/AndroidGoogleMaps/article.html

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