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
Related
I am new to Java and android development. I have a app and I need to purchase history using Anjlab library.
On git I found this page
https://github.com/anjlab/android-inapp-billing-v3
and it mentions the following:
BillingProcessor bps;
bps = BillingProcessor.newBillingProcessor(this, getResources().getString(R.string.play_console_license), this);
public List<BillingHistoryRecord> getPurchaseHistory(String type, Bundle extraParams)
I am unfamiliar on how to use
public List<BillingHistoryRecord> getPurchaseHistory(String type, Bundle extraParams)
and I am not entirely sure how to use it.
My goal is to print out the transaction history eg the token and orderid etc
Thank You
To get the token you can do something like this:
BillingProcessor bps;
bps = BillingProcessor.newBillingProcessor(this, getResources().getString(R.string.play_console_license), this);
bps.loadOwnedPurchasesFromGoogle();
bps.getPurchaseListingDetails("yourproductcode");
String token = Objects.requireNonNull(bps.getSubscriptionTransactionDetails("yourproductcode")).purchaseToken;
You may want to add to empty checks around this
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).
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
I want to read Gmail mails in my own android app. Is there anyway to do it using android sdk? If not, what are the other options? parsing gmail atom?
I ask and answer that question here.
You need Gmail.java code (in the question there are a link) and you must understand that you shouldn't use that undocumented provider
Are there any good short code examples that simply read a new gmail message?
It's possible using the GMail API, here are some steps I found helpful.
Start with the official sample to get the GMailAPI started, see here
When following the instructions I found it helpful to read about the app signing here in order to get Step1+2 in the sample right.
With the sample running you can use the information here to access messages. You can e.g. replace the implementation in MakeRequestTask.getDataFromApi
Be sure to add at least the read-only scope for proper permissions. In the sample the scopes are defined in an array:
private static final String[] SCOPES = { GmailScopes.GMAIL_LABELS, mailScopes.GMAIL_READONLY };
My intention was to read all subjects. I used the following code (which is the adapted getDataFromApi method from the official sample):
private List<String> getDataFromApi() throws IOException {
// Get the labels in the user's account. "me" referes to the authentized user.
String user = "me";
List<String> labels = new ArrayList<String>();
ListMessagesResponse response = mService.users().messages().list(user).execute();
for (Message message : response.getMessages()) {
Message readableMessage = mService.users().messages().get(user, message.getId()).execute();
if (readableMessage.getPayload() != null) {
for (MessagePartHeader header : readableMessage.getPayload().getHeaders()) {
if (header.getName().compareToIgnoreCase("Subject") == 0) {
labels.add(header.getValue());
}
}
}
}
return labels;
}
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.