Get user's current Lat Long using Places API - android

Is it possible to get user's current Lat Long using Places API, instead of Maps API? I'm sure there's a process that involves user's current Lat Long but is it possible to get them?
Currently I'm creating activities that use Places API, and now I need user's current Lat Long, I think it's not worth to add Maps API only for that function.

If your requirement is to fetch only the Lat Long of the current location, then you don't need to use any Api. You may follow the below tutorial to implement it without using Place Api
https://www.androidhive.info/2015/02/android-location-api-using-google-play-services/
If you still want to use Place Api then you need to use Places.PlacesDetectionApi.getCurrentPlace method to create a PendingIntent that returns with a PlaceLikelihoodBuffer. First define the GoogleApiClient and use the below code to fetch the location -
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi.getCurrentPlace( mGoogleApiClient, null );
result.setResultCallback( new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult( PlaceLikelihoodBuffer likelyPlaces ) {
PlaceLikelihood placeLikelihood = likelyPlaces.get( 0 );
String content = "";
if( placeLikelihood != null && placeLikelihood.getPlace() != null && !TextUtils.isEmpty( placeLikelihood.getPlace().getName() ) )
content = "Most likely place: " + placeLikelihood.getPlace().getLatLng()+ "\n";
if( placeLikelihood != null )
content += "Percent change of being there: " + (int) ( placeLikelihood.getLikelihood() * 100 ) + "%";
mTextView.setText( content );
likelyPlaces.release();
}
});
For more info, refer to this article - https://code.tutsplus.com/articles/google-play-services-using-the-places-api--cms-23715

Related

How to update Mapbox Android Symbol layer with new markers

I'm using the Mapbox Android SDK and want to populate the map with markers whose locations are stored in a Firebase database common to all users of my application. Each marker is stored in a unique record and each record contains the Latitude & Longitude of the marker along with a boolean value indicating if the location has been verified. I have successfully done this using the Mapbox iOS SDK using Annotations.
When the Android App is launched I create a feature list of all markers in the database using symbolOptions as shown below inside of the Firebase "childAdded" listener (other listeners are also implemented as part of the ChildEventListener):
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference markerRef = dbRef.child("markers");
//load all markers when app starts
//child added returns all markers, then listens for new additions
//Log.i(TAG, "Database Reference: " + dbRef);
List<SymbolOptions> options = new ArrayList<> ();
markerRef.addChildEventListener ( new ChildEventListener () {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
markerRead = markerRead+1;
markerKey = dataSnapshot.getKey();
Log.i(TAG, "Adding Markers: ");
Log.i(TAG, "Marker Key: " + markerKey);
x = (Double)dataSnapshot.child ( "x" ).getValue();
y = (Double) dataSnapshot.child ( "y" ).getValue();
v = (Boolean) dataSnapshot.child ( "v" ).getValue();
Log.i(TAG, "Marker Data - x: " + x + " y: " + y + " v: " + v);
if(v == true) {
options.add(new SymbolOptions ()
.withLatLng ( new LatLng (y,x))
.withIconImage ( "verified" )
.withIconAnchor ( "bottom" )
.withDraggable ( false )
);
} else {
options.add(new SymbolOptions ()
.withLatLng ( new LatLng (y,x))
.withIconImage ( "unverified" )
.withIconAnchor ( "bottom" )
.withDraggable ( false )
);
}
if (markerRead == 1) {
symbols = symbolManager.create(options);
}
}
The above code does populate the feature list, but since I have no way of knowing when the Firebase "childAdded" function has completed the initial read of the database, the above only adds the first marker.
I have tried to find Mapbox documentation on how to add annotations analogous to the iOS SDK but have been unsuccessful. The tutorial videos have not been updated and use "addMarker" which has been deprecated.
I need to add markers to the map and I also need to assign a unique ID (the "markerKey" in the above code) to each marker so that an individual marker can be changed or deleted in the future. Also the map needs to display new markers that are added and detected by the "child Added" listener. I have not found a way to have additions to the feature list be displayed when added and the symbols created.
Once the markers are initially added to the Map, the App "Listens" to the Firebase database for the following events:
A new marker is added
An existing marker is moved to a new location
An existing marker is deleted
When a marker is moved or deleted the appropriate database listener is notified and passed the record number (key) of the marker ("markerKey" in above code) that was moved (or deleted). If the marker was moved, the record will then contain the new Latitude & Longitude information.
Thanks in advance for the help.

Extract duration from Google-distance url

I'm in the middle of developping a map app that enables user to send duration data that it takes him to get to another place, to the database (MySQL) , for this reason I tried to extract the double value of duration directely from url as it's showing in the method below :
#Override
public void setDouble(String result) {
String res[]=result.split(",");
Double min=Double.parseDouble(res[0])/60;
int dist=Integer.parseInt(res[1])/1000;
Duree.setText("Duration= " + (int) (min / 60) + " hr " + (int) (min % 60) + " mins");
Distance.setText("Distance= " + dist + " kilometers");
}
In this method it worked, but when I tried to do it like this :
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+latt+","+lngg+"&destinations="+lt+","+lg+"&mode=driving&language=fr-FR&avoid=tolls&key=API_KEY";
String res[]=url.split(",");
Double duration=Double.parseDouble(res[0])/60;
It showed me that it's not a valid double value, knowing that I need to send this value when I click a button showed on a popup window after marker click (So the problem of inner class is posed).
Can you help me know what is the right way to do it ,if that is possible !
Don't expect your first result-field contains the duration but make your parsing a little more intelligent. Use, by example, the org.json library (introduction on json
Following code snippet should help a little:
LOGGER.debug("---google duration in seconds = {}", jsonElement.opt("duration") == null ? 0 : jsonElement.getJSONObject("duration").get("value"));
transportInfo.setDuration(jsonElement.opt("duration") == null ? 0 : (Integer) jsonElement.getJSONObject("duration").get("value"));
And, btw, I would recommend removing your API key ASAP from your post .... Be aware this key could be used by other people.

Get all places around 2 kilometers using Google's PlaceDetectionApi

I am using following API to get all places from current location,
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
Log.v("App",
"2. likelyPlaces.getCount() : "
+ likelyPlaces.getCount() + ", placeType : "
+ placeType);
places.clear();
GooglePlace place;
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
place = new GooglePlace();
place.setAddress(placeLikelihood.getPlace()
.getAddress());
place.setId(placeLikelihood.getPlace().getId());
place.setLatLng(placeLikelihood.getPlace()
.getLatLng());
place.setName(placeLikelihood.getPlace().getName());
place.setPhoneNumber(placeLikelihood.getPlace()
.getPhoneNumber());
place.setPriceLevel(placeLikelihood.getPlace()
.getPriceLevel());
place.setRating(placeLikelihood.getPlace()
.getRating());
places.add(place);
}
mAdapter.notifyDataSetChanged();
likelyPlaces.release();
}
});
This one returns only 20 places, and also no photo of the place. So I want to know how to get all places around 2 kilometers from current location. Also how to get the place image.
I know we can get more than 20 results by using
https://maps.googleapis.com/maps/api/place/search/xml?location=Enter Latitude,Enter Longitude&radius=10000&types=store&hasNextPage=true&nextPage()=true&sensor=false&key=enter google_map_key &pagetoken="Enter the first page token Value"
But for this API we have to provide Server IP for get API key. So need to know how can we get more than 20 results by using
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
Any help will be highly appreciable.
Don't know if you found answer already but you should check this out if not:
The Places API will return up to 20 establishments per query; however, each search can return as many as 60 results, split across three pages
https://stackoverflow.com/a/9627664/3677394

Selecting correct ArcGisFeatureLayer to query onSingleTap event?

My problem: I'm working on a Android (ArcGis) Attribute Editor following the sample code from their tutorials. The problem occurs when I have more than 1 ArcGisDynamicLayer and, more important, more than 1 ArcGisFeatureLayer.
My question: What is the (correct) approach to IDENTIFY the right Feature Layer to query when I tap on a "field" displayed on the map?
I read a similar question (Arcgis SDK for Android - Query multiple feature layers), but I didn't understand how to use IdentifyTask using only a single tap.
EDIT: I tried to get the graphics that I tapped on to compare it to the graphics from every feature layer. If they are equal, that's the feature layer that I'm looking for. But that's not working, because my feature layers don't seem to have any graphics.
mapView.setOnSingleTapListener(new OnSingleTapListener() {
public void onSingleTap(float x, float y) {
/*...construct query...*/
Graphic g = null;
for (Layer layer : mapView.getLayers()) {
if (layer instanceof ArcGISFeatureLayer) {
ArcGISFeatureLayer fLayer = (ArcGISFeatureLayer) layer;
// Get the Graphic at location x,y
final int[] ids = fLayer.getGraphicIDs(x, y, 10, 1);
if (ids != null && ids.length != 0) {
g = fLayer.getGraphic(ids[0]);
System.out.println("Graphic: " + g);
}
}
/*...loop through every FeatureLayer and verify like :...*/
for(...)
if(layer.getGraphic(g.getUid()) != null && && g.equals(layer.getGraphic(g.getUid()))) {
/* call the select features method and implement the callbacklistener */
/* rest of the story */
}
}

returning null when implementing Geocoder

I'm trying to find the address(location) using Geocoder.
I have the following code:
double lat = (double) (coord.getLat() * (1e-6));
double lon = (double) (coord.getLon() * (1e-6));
try {
List<Address> list = geocoder.getFromLocation(lat, lon,1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
result = address.getAddressLine(0) + ", "
+ address.getLocality();
}
System.out.println("adresa returnata folosind geocoder:"
+ result);
}
The data that I pass to geocoder is in this format:
2.449548
48.950518
But when trying to println() the first address returned by Geocoder it returns null. This is how my logcat looks like:
reverseGeocode()`: no feature in
GLocation
And my System.out.println() displays :null. I have internet acces and also internet permssion added to my manifest file. Does someone know what I'm doing wrong??
As Geobits said, your coordinates belong to place in the Arabian Sea. You cant get an Address from there, so your list is empty and your result is null.

Categories

Resources