Android studio Geocoder get location category - java

I am using the Geocoder class in android studio and I am able to get country name and address by doing
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
userCountry = addresses.get(0).getCountryName();
userAddress = addresses.get(0).getAddressLine(0);
}
What I want to do now is to categorize the location.
Let`s say if I'm near a park I will translate the latitude and longitude to "park" or if I'm at the beach it will categorize the location as "beach".
Is there anything I can use to categorize these places automatically using longitude and latitude?
I thought maybe
addresses.get(0).getLocality()
but it just gives me city name
and when I tried
addresses.get(0).getFeatureName()
it just gives me a number so I'm not sure what that number is.

You could use your longitude and latitude along with Google Places API .
Through the API you will be able to tell if a user is near a city-based location such as a gym or a park.
You can find more information about this API here.

Geocoder can't give you the types.
Also, geocoder isn't avaiable on all devices.
Instead, I would recommend to use the Google Geocoding API.
It returns types of places along with their names.
For more information, read here:
https://developers.google.com/maps/documentation/geocoding/intro

Related

Can Google's Places API findCurrentPlace method be used to get the exact current address, rather than the address of the closest 'Place'?

I am currently using the Google Places API within my (Java) Android application to get the current device location and display it into an editText. Currently when I make the call to placesClient.findCurrentPlace(request), a list of the closest places and the likelihood of the device being there are returned, like so:
Place 'XXXXXXX' has likelihood: 0.600000
Place 'YYYYYYY' has likelihood: 0.0500000
Place 'ZZZZZZZ' has likelihood: 0.00000
Where the places are things like "Thames River" or "Telus Stadium". I can then get the address from each of these from the response. My question is, is there any way to get back the address of the phones current location, opposed to the address of the closest 'Place'?
I have done something similar with the Places Autocomplete so that it suggests addresses rather than places, which works very well. Getting the current place is done in a slightly different way though, and therefore I can't seem to make the same change.
The reason that I am attempting to do this using the Places API is because I have a start and end location AutoCompleteEditText which the user can type into. They can choose to have their current location shown in the Start Location AutoCompleteEditText, and I was hoping to show the address in the same format as it would be in if they had typed in the address and clicked it using the Places AutoComplete.
Here is the code currently being used to get the address of the closest place, which I would like to modify to get the address the phone is currently at.
List<Place.Field> placeFields = Collections.singletonList(Place.Field.ADDRESS);
FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(placeFields);
...
Task<FindCurrentPlaceResponse> placeResponse = placesClient.findCurrentPlace(request);
placeResponse.addOnCompleteListener(new OnCompleteListener<FindCurrentPlaceResponse>() {
#Override
public void onComplete(#NonNull Task<FindCurrentPlaceResponse> task) {
if (task.isSuccessful()) {
FindCurrentPlaceResponse response = task.getResult();
for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) {
Log.i(LOG_TAG, String.format("Place '%s' has likelihood: %f",
placeLikelihood.getPlace().getAddress(),
placeLikelihood.getLikelihood()));
}
} else {
Log.e(LOG_TAG, "Error finding current location");
}
}
});
Forget having to use the Google Places API for this - It's simple to do without having to interact with any API.
Simply get the current location using a FusedLocationProviderClient to return the last known latitude and longitude of the device (as seen here), and then use an instance of Geocoder to get addresses from that latitude and longitude using the getFromLocation method. This can then easily be converted into a string which matches what the Google Places API would have returned (as seen here).

How to get Place ID using coordinates (lat, lon) in Android

I use Google Maps API and need to get details of the place using lat and lon.
I've tried to get via Geocoder, but Class "Address" has no
parameters PLACE_ID
Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(52.2641, 76.9597, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses.size() > 0) {
Toast.makeText(this, addresses.get(0).getPlaceID(), Toast.LENGTH_SHORT).show();
}
else {
// do your stuff
}
To get a place ID from coordinate you should execute a reverse geocoding lookup using a REST API.
The native Android API geocoder doesn't support getting place ID in getFromLocation() results. Unfortunately, Google Maps Android SDK doesn't provide built-in Geocoder neither. The feature request exists for a long time, but it looks like it doesn't have high priority:
https://issuetracker.google.com/issues/35823852
So, to obtain a place ID you are stick to the REST API. There is a Java client library for Google Maps API Web Services that you can find on github:
https://github.com/googlemaps/google-maps-services-java
You can use this library to call Geocoding API from your Java code.
GeoApiContext context = new GeoApiContext.Builder()
.apiKey("AIza...")
.build();
GeocodingResult[] results = GeocodingApi.newRequest(context)
.latlng(new LatLng(52.2641, 76.9597)).await();
System.out.println(results[0].placeId);
Note that API key for web services must be different from an API key that you use in Google Maps Android SDK, because web services don't support Android app restriction.
Also take into account this important note from the library documentation
The Java Client for Google Maps Services is designed for use in server applications. This library is not intended for use inside of an Android app, due to the potential for loss of API keys.
If you are building a mobile application, you will need to introduce a proxy server to act as intermediary between your mobile application and the Google Maps API Web Services. The Java Client for Google Maps Services would make an excellent choice as the basis for such a proxy server.
I hope this helps!
you can get place Id on the bases of the marker. something like this:
mGoogleMap.setOnPoiClickListener(new GoogleMap.OnPoiClickListener() {
#Override
public void onPoiClick(PointOfInterest pointOfInterest)
{
addOrSaveMarkerToMap(pointOfInterest.latLng.latitude, pointOfInterest.latLng.longitude, pointOfInterest.name, "", pointOfInterest.placeId, true, true);
//Toast.makeText(GoogleMapsActivity.this,""+pointOfInterest.name+" (lat: "+pointOfInterest.latLng.latitude+", long: "+pointOfInterest.latLng.longitude+") " +" is added in your favorite list",Toast.LENGTH_LONG).show();
}
});
If you want to read more about what is point of interest is please take a look at this documentation link.
https://developers.google.com/maps/documentation/android-sdk/poi
Best way is to use google places API. It will give you the whole information about a specific place.
If you want to use google places API then follow this link:
How to get place or placeid by latLng in android using google places api?
FYI
Geocoder did't provide getPlaceID().
Supply a placeId to find the address for a given place ID. The place
ID is a unique identifier that can be used with other Google APIs
The GeocoderRequest object literal contains the following fields:
{
address: string,
location: LatLng,
placeId: string,
bounds: LatLngBounds,
componentRestrictions: GeocoderComponentRestrictions,
region: string
}
You should read Retrieving an Address for a Place ID.
/**
* Requests the details of a Place.
*
* <p>We are only enabling looking up Places by placeId as the older Place identifier, reference,
* is deprecated. Please see the <a
* href="https://web.archive.org/web/20170521070241/https://developers.google.com/places/web-service/details#deprecation">
* deprecation warning</a>.
*
* #param context The context on which to make Geo API requests.
* #param placeId The PlaceID to request details on.
* #return Returns a PlaceDetailsRequest that you can configure and execute.
*/
public static PlaceDetailsRequest placeDetails(GeoApiContext context, String placeId) {
PlaceDetailsRequest request = new PlaceDetailsRequest(context);
request.placeId(placeId);
return request;
}
try this one
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
// Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0);
// If any additional address line present than only, check with max
available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
// Only if available else return NULL

Google Calendar API: add latitude longitude to Calendar Event programmatically in android?

I retrieve the lat & long for the event detail. And I want to send lat long to calendar using intent. I search it on google but didn't find any solution? Please help.
You could attain this using CalendarContract class. Adding location is possible using this class; CalendarContract.Events.EVENT_LOCATION
More info here Adding event with reminders to calendar with 'Intent.putExtra()' way of doing
Using the Google API with other languages, I have been able to pass the Latitude and Longitude as a string and the map link in the Calendar Event drops a pin in the correct position. I would imagine that that API has the same behavior for all languages.
Source: Latitude and Longitude of the White House
C# psuedo code
var latitude = "38.8976763";
var longitude = "-77.0365298";
new Event
{
// beginning parameters
...
// The comma is optional and replaceable with a single space
Location = $"{latitude}, {longitude}",
...
// final parameters
}
image from Event detail added by Google API:
Resulting Link when clicking map from the Calendar Event:
 map

Is there any way that the android user run the application from UK?

I am trying to develop an android mobile application. I have a function which different from country localization. It will only UK country and other. Now my query how I will check that the user run the application from the UK.I s there any option to check out this user run the application from the UK. Please help me how will I check this.
If you are having the current latitude and longitude, then you can get the complete address of your current location by the following code:
String country="";
try{
Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lon,1);
if (addresses.size() > 0)
{
Log.e("address",addresses.toString());
country=addresses.get(3).getFeatureName();
}
}
It will give you the country, and you can run your function if the country is UK.

How does the Google Maps for Mobile "My Location" feature work?

I've installed the Google Maps Java 2 ME app on my Nokia N73 which supports the Location API (JSR 179), but does not have an in-built GPS sensor. The "My Location" features works correctly, and is able to pinpoint my position within the city.
When I tried to access the CellID, LAC and other related data, I got nulls. So how is Maps able to calculate my position? Is it because their app is signed with a certificate? (mine isn't)
What it does is measure the signal strength of WiFi, 3G and GSM Base Stations/Access Points in the area. Since all WiFi access points have a unique MAC address, and 3G and GSM Base Stations also have unique identifications, it now knows which base stations you are close to and approximately how close to them you are, based on the strength.
There are now a few ways to find the distance. If it knows where the Access Point/Base Station is, then it can triangulate your position, based on the signal strength. For this to work it needs to have access to at least 3 AP/BS. With GSM it can also use the Timer Advance, which is an estimation of how far away you are from the base station, with an accuracy of approximately 1km. With 3G it's even better.
Another approach (used by Google and others) is that all your signal strength data is sent to a server. If you have a GPS then your GPS info is also sent along. The server can then build a map of signal strengths to different AP/BS at different coordinates. Since you don't have a GPS it now compares the signal strengths you have passed along and tries to find the closest match in its database, and then finds the location at that closest point.
This is easy to do in J2ME using the APIs defined by JSR 179. There's a simple example here: JavaME Location API Example application with Source Code (that page is broken at the time of writing; here's the Google Cache version).
That sample works perfectly on my Nokia E63, which like your N97 N73 doesn't have a GPS but does support cell-based positioning. Here's the core of it:
public void checkLocation() throws Exception
{
String string;
Location l;
LocationProvider lp;
Coordinates c;
// Set criteria for selecting a location provider:
// accurate to 500 meters horizontally
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(500);
// Get an instance of the provider
lp = LocationProvider.getInstance(cr);
// Request the location, setting a one-minute timeout
l = lp.getLocation(60);
c = l.getQualifiedCoordinates();
if(c != null ) {
// Use coordinate information
double lat = c.getLatitude();
double lon = c.getLongitude();
string = "\nLatitude : " + lat + "\nLongitude : " + lon;
} else {
string ="Location API failed";
}
midlet.displayString(string);
}
#Marius is right about how the technology works, but the JSR 179 APIs hide all that detail from you. #JaanusSiim is wrong that you can't do this from J2ME.
Note that the sample application doesn't require signing to work - the phone will pop up a prompt asking whether to allow the unsigned application to access your location information.

Categories

Resources