how to get current Location with android studio - android

I want get current location then i press one button in the app but it dont give me that instead it give unknown address but if i change my location to USA it gives the address? I dont get any errors everything is working good only the address dont show up? here is my code, If you could help me I would appreciate it.
try {
Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(currentLocation.getCoordinates().latitude, currentLocation.getCoordinates().longitude, 1);
if (addresses.isEmpty()) {
autocompleteFragmentFrom.setText(R.string.waiting_for_location);
} else {
addresses.size();
if (addresses.get(0).getThoroughfare() == null) {
pickupLocation.setName(addresses.get(0).getLocality());
} else if (addresses.get(0).getLocality() == null) {
pickupLocation.setName("unknown address");
} else {
pickupLocation.setName(addresses.get(0).getLocality() + ", " + addresses.get(0).getThoroughfare());
}
autocompleteFragmentFrom.setText(pickupLocation.getName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
enter image description here

After request location permission and enable GPS use FusedLocationProviderClient.
private val mFusedLocationProviderClient: FusedLocationProviderClient by lazy {
LocationServices.getFusedLocationProviderClient(requireActivity())
}
mFusedLocationProviderClient.lastLocation?.addOnSuccessListener(this) { location:Location? ->
val lat = location?.latitude
val lon = location?.longitude
}

Related

.NET MAUI GeolocationRequest - What settings to provide?

I am using the following code to get the Lat/Long and display.
labelLatLong.Text = "Checking Lat Long. Please wait...";
var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(15));
CancellationTokenSource cts = new CancellationTokenSource();
try
{
var location = Geolocation.GetLocationAsync(request, cts.Token);
if (location != null)
{
labelLatLong.Text = $"Latitude: {location.Result.Latitude}, Longitude: {location.Result.Longitude}, Altitude: {location.Result.Altitude}";
}
}
catch {
labelLatLong.Text = "Unable to get location.";
}
For some reason, I am not getting the location value and there is no exception thrown and I cannot debug beyond the line 'GetLocationAsync', and the application says "App not responding"
I am using Visual Studio 17.4.3, Pixel 5 (API 33) android emulator.
I already gave permissions 'All the time' in the android emulator.
My laptop also has the location enabled.
Are there any other settings, I should be looking at?
Any suggestions? Appreciate your help. Thank you!
In your xaml.cs:
private async void Button_Clicked(object sender, EventArgs e)
{
try
{
var location = await Geolocation.GetLastKnownLocationAsync();
if (location == null)
{
location = await Geolocation.GetLocationAsync(new GeolocationRequest()
{
DesiredAccuracy = GeolocationAccuracy.High, Timeout = TimeSpan.FromSeconds(30)
});
}
if (location == null)
{
labelLatLong.Text = "Unable to get location.";
}
else
{
labelLatLong.Text = $"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}";
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Android Geocoder returns null city name

I am new to Android development, following is my code about use Geocoder to get city name of current location, it returns null:
private void updateCurrentLocation(Location location) {
double lat = 0.0, lng = 0.0;
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Log.i("tag", "Latitute is" + lat + ", Longtitute is" + lng);
} else {
City_Name = "Unavailable";
}
List<Address> list = null;
Geocoder geocoder = new Geocoder(this.getActivity());
try {
list = geocoder.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
//may provide multiple locations.
if (list != null && list.size() > 0) {
Address address = list.get(0);
City_Name = address.getLocality();
}
Log.i("Try", "CityName:" + City_Name);
//send empty message
handler.sendEmptyMessage(1);
}
I opened GPS services, add ACCESS_FINE_LOCATION and INTERNET permission in Manifest already. Also, I searched similar questions in Stackoverflow about Geocoder returns null, but haven't found useful solutions. One of them is analyze JSON from Geocoder website, but it doesn't work either.
Can anyone help with this? Thank you!
BTW, is there any better solution to receive a city name? Thank you!
If the "getFromLocation" method gives you an empty set then it's because the server that is being looked up doesn't have the address information for the coordinates you're passing it. This is also noted in the docs. So I think that you should let it go and use another service like the Google Maps geocoding service or another one like Nominatim from the OpenStreetMap project.

Reverse GeoCoordinate Class gives Location Not found error

i m using google Reverse Geocoding API in my app, i m succussfully able to get get coordinate using google geolocation API. Now i m trying to get Location Name from Reverse Geocoding API , but always returns Location not found error
here is my code:
Geocoder geocoder= new Geocoder(MainActivity.this, Locale.ENGLISH);
if(geocoder.isPresent()){
List<Address> list;
try {
list = geocoder.getFromLocation(37.42279, -122.08506,1);
Address address = list.get(0);
Log.d("this is working","thsi sis working");
StringBuffer str = new StringBuffer();
str.append("Name: " + address.getLocality() + "\n");
str.append("Sub-Admin Ares: " + address.getSubAdminArea() + "\n");
str.append("Admin Area: " + address.getAdminArea() + "\n");
str.append("Country: " + address.getCountryName() + "\n");
str.append("Country Code: " + address.getCountryCode() + "\n");;
String strAddress = str.toString();
JsonDatas.setText(strAddress);
Log.d("Address", strAddress);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i have several question
how google know that which app requested the API and how google determine of Quota that app. in google API developer Console, google gave Quota for app API
Why i m getting location not found error but searching on google map location is showing
do i need to add google Geocoder APi key into my app - right now i m only Geolocation API key using for retrieve Coordinates
Please correct me if i m wrong, Please give suggestion so my code will work fine
thanks
Make sure you have latest Google play library in your project. I am using this code and working for me.
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",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(1) : "", "", "");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return addressText;
}
#Override
protected void onPostExecute(String addressText) {
}
}
Where LatLng is Latitude and longitute, check this for doc.
and to use write down new ReverseGeocodingTask(this).execute(latlng); where you want to get data.
Make sure you are adding permission into your manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

How to get Latitude Longitude from more than 500 addresses?

I have more than 700 addresses in database.
I want to plot them region wise.
I have implement this code :
public LatLng getSingleLocationFromAddress(String strAddress)
{
Geocoder coder = new Geocoder(this, Locale.getDefault());
List<Address> address = null;
Address location = null;
GeoPoint p1 = null;
LatLng temp = null;//new LatLng(26.0000, 121.0000);
String strAddresNew = strAddress.replace(",", " ");
try
{
address = coder.getFromLocationName(strAddresNew, 1);
if (!address.isEmpty())
{
location = address.get(0);
location.getLatitude();
location.getLongitude();
temp = new LatLng(location.getLatitude(), location.getLongitude());
Log.d("Latlng : ", temp + "");
} else
{
arrTemp.add(strAddress);
System.out.println(arrTemp);
}
} catch (IOException e)
{
Toast.makeText(mContext, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
return temp;
}
But the problem is when I call this method in loop like this:
Marker TP1 = googleMap.addMarker(new MarkerOptions().position(getSingleLocationFromAddress(fullAddress)));
The line coder.getFromLocationName(strAddresNew, 1); returns null for some addresses, for example if I have an ArrayList of 7 addresses then I get only 4-5 LatLong values.
Use below lines of code...It can be helpful for you
Declare these variables above yours Oncreate or OncreatView
List<Address> From_geocode = null;
private double sLat, sLong;
private Geocoder geocoder;
Than inside yours oncreate or oncreateVIew use these lines of code
geocoder = new Geocoder(getActivity());
try {
From_geocode = geocoder.getFromLocationName("PUT THE ADDRESS HERE", 1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (From_geocode.size() > 0) {
System.out.println("2");
From_geocode.get(0).getLatitude(); // getting
// latitude
From_geocode.get(0).getLongitude();
sLat = From_geocode.get(0).getLatitude();
sLong = From_geocode.get(0).getLongitude();
System.out.println("LATITUTE====="+sLat+" LONGITUTE====="+sLong);
}
And provide the entry inside the manifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Although the google database is extensive it is possible that some of the addresses that you have supplied could not be geocoded. Hence you will not get a lat/lon for those addresses. You could probably check the status of the response.
As mentioned in the link below
https://developers.google.com/maps/documentation/geocoding/#StatusCodes
The "status" field within the Geocoding response object contains the status of the request, and may contain debugging information to help you track down why geocoding is not working. The "status" field may contain the following values:
"OK" indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned.
"ZERO_RESULTS" indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a non-existent address.

Android: App crashes while entering invalid location

In my app, I have to find whether a given location comes under a specified area. I am taking Connaught Place, New Delhi as center point. and I got the addresses which come under area of 200 miles from center point. But, if I enter any invalid location, like "abcdfdfkc", the app crashes, because it is trying to find coordinates of this location and I want to avoid this.
Below I am posting the code:
public static boolean isServicedLocation(Context _ctx, String strAddress){
boolean isServicedLocation = false;
Address sourceAddress = getAddress(_ctx, "Connaught Place, New Delhi, India");
Location sourceLocation = new Location("");
sourceLocation.setLatitude(sourceAddress.getLatitude());
sourceLocation.setLongitude(sourceAddress.getLongitude());
Address targetAddress = getAddress(_ctx, strAddress);
Location targetLocation = new Location("");
if (targetLocation != null) {
targetLocation.setLatitude(targetAddress.getLatitude());
targetLocation.setLongitude(targetAddress.getLongitude());
float distance = Math.abs(sourceLocation.distanceTo(targetLocation));
double distanceMiles = distance/1609.34;
isServicedLocation = distanceMiles <= 200;
//Toast.makeText(_ctx, "Distance "+distanceMiles, Toast.LENGTH_LONG).show();
}
return isServicedLocation;
}
getAddress method:
public static Address getAddress(Context _ctx, String addressStr) {
Geocoder geoCoder = new Geocoder(_ctx, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(addressStr,
1);
if (addresses.size() != 0) {
return addresses.get(0);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
It's because when you don't find an address from the GeoCoder (ie, if addresses.size() == 0), you return null.
Then, regardless of that, you dereference the value, which is what's crashing your app.
Address targetAddress = getAddress(_ctx, strAddress);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:
if (targetLocation != null) {
targetLocation.setLatitude(targetAddress.getLatitude());
^^^^^^^^^^^^^
You should probably also be checking targetAddress for null to avoid this (either in addition to (likely), or instead of (less likely), the check of targetLocation).
So I'd be looking at changing:
if (targetLocation != null) {
into:
if ((targetLocation != null) && (targetAddress != null)) {
That way, an invalid address automatically becomes an unserviced location.

Categories

Resources