Get Longitude and Latitude from a Google Places Result - android

I am writing an Android App using Xamarin which uses Xamarin.GooglePlayServices.Maps Nuget Package. I need to get to a particular place on the map using the name of the place. For this purpose I loaded Xamarin.GooglePlayServices.Places. I am able to pass a partial place name to the GetAutocompletePredictionsAsync as so:
var autocompletePredictions = await
PlacesClass.GeoDataApi.GetAutocompletePredictionsAsync(
Adapter.googleApiClient, constraint.ToString(),
Adapter.bounds, Adapter.autoCompleteFilter);
The result I get back is basically a collection of IAutocompletePrediction. The only item in this object that has to do with location is the PlaceId. I cannot find any way to use this on the Google Maps API. I tried seeing if I could get any more information by calling the GetPlaceById:
var place = PlacesClass.GeoDataApi.GetPlaceById(googleApiClient, item.PlaceId);
But I didn't see any location information at all in that result. Does anyone know how to get LatLng information from the Google Places API?
Update: I used information from several responses to get the answer:
Task.Run(async () =>
{
PlaceBuffer places = await PlacesClass.GeoDataApi.GetPlaceByIdAsync(googleApiClient, item.PlaceId);
if (places.Status.IsSuccess)
{
foreach (var place in places)
try
{
//IPlace place = (IPlace)places.Get(0);
MarkOnMap(place.NameFormatted.ToString(), place.AddressFormatted.ToString(), place.LatLng);
UpdateCameraPosition(place.LatLng);
}
catch (Exception ex)
{
Log.Error("WhatNow", ex.ToString());
}
}
places.Dispose();
});
The odd thing was when I enumerated the places in the foreach, the place was an IPlace type. However
IPlace place = (IPlace)places.Get(0);
Did not cast to an IPlace. Who knows? I just hope that Dispose() releases the buffer as recommended in the Docs. Xamarin is always just a little different from Java.
Thanks to everyone who helped.

I have used this, you can try this code.
I am using autoCompleteTextView.
dropLocationEt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final PlaceAutoCompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
Log.i(TAG, "Autocomplete item selected: " + item.description);
/*
Issue a request to the Places Geo Data API to retrieve a Place object with additional
details about the place.
*/
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(googleApiClient, placeId);
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
// Request did not complete successfully
Log.e(TAG, "Place query did not complete. Error: " + places.getStatus().toString());
places.release();
return;
}
// Get the Place object from the buffer.
final Place place = places.get(0);
latLngDrop = place.getLatLng();
StaticMethods.hideKeyboard(getActivity());
dropLocationEt.setSelection(0);
}
});
}
});
From the latlngDrop, you can retrieve the lat and lng, eg: latlngDrop.getLatitude, latlngDrop.getLongitude

Related

migrating to Places API, cannot resolve GEO_DATA_API GeoDataApi

I'm going through the process of migrating from depricated Places SDK to the Places API as described here, using the compatibility library. Everything had been working fine prior to attempting the migration. I've
1) Updated my dependencies
2) Changes my import statements
3) Min SDK was already 21
I am getting two (seemingly related) errors. cannot find symbol variable GEO_DATA_API and cannot find symbol variable GeoDataApi
the code
googleApiClient = new GoogleApiClient.Builder(PlacesActivity.this)
.addApi(Places.GEO_DATA_API) //***HERE***
.enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
.addConnectionCallbacks(this)
.build();
and
private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) {
if (googleApiClient !=null) {
PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi.getAutocompletePredictions( // ***AND HERE***
googleApiClient,
constraint.toString(),
latLngBounds,
autocompleteFilter
);
// Wait for predictions, set the timeout.
AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
//auto complete fail
autocompletePredictions.release();
return null;
}
//auto complete success
Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
ArrayList<PlaceAutocomplete> resultList = new ArrayList<>(autocompletePredictions.getCount());
while (iterator.hasNext()) {
AutocompletePrediction prediction = iterator.next();
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(), prediction.getFullText(null)));
}
// Buffer release
autocompletePredictions.release();
return resultList;
}
return null;
}
An entire re write of code is required. Here is working code for getting lat, lng, and name (for example)
public class MainActivity extends AppCompatActivity {
String TAG = "placeautocomplete";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize Places.
Places.initialize(getApplicationContext(), "YOUR_API_KEY");
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
// Initialize the AutocompleteSupportFragment.
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
// Specify the types of place data to return.
autocompleteFragment.setPlaceFields(Arrays.asList(
Place.Field.NAME,
Place.Field.LAT_LNG
));
// Set up a PlaceSelectionListener to handle the response.
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
String name = place.getName();
double lat, lng;
if (place.getLatLng() !=null){
lat =place.getLatLng().latitude;
lng =place.getLatLng().longitude;
}
//do something
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
}
}
example xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<android.support.v7.widget.CardView
android:id="#+id/idCardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardCornerRadius="4dp"
>
<fragment
android:id="#+id/autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
/>
</android.support.v7.widget.CardView>
</LinearLayout>
Problem 1: cannot find symbol variable GEO_DATA_API
Solution 1:
First of all lets understand the usage of Places.GEO_DATA_API
It says that "The Geo Data API provides access to getting information about places by place ID, autocompleting a user's search query by name or address, and adding new places to Google's Places database."
source (https://developers.google.com/android/reference/com/google/android/gms/location/places/GeoDataApi)
So if we want to get place information from place id then we have to
use below code:
// Define a Place ID.
String placeId = "INSERT_PLACE_ID_HERE";
// Specify the fields to return (in this example all fields are returned).
List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// Construct a request object, passing the place ID and fields array.
FetchPlaceRequest request = FetchPlaceRequest.builder(placeId, placeFields).build();
placesClient.fetchPlace(request).addOnSuccessListener((response) -> {
Place place = response.getPlace();
Log.i(TAG, "Place found: " + place.getName());
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
int statusCode = apiException.getStatusCode();
// Handle error with given status code.
Log.e(TAG, "Place not found: " + exception.getMessage());
}
});
Problem 2: cannot find symbol variable GeoDataApi
Solution 2: As new places api indicates that "Use findAutocompletePredictions() to return place predictions in response to user search queries. findAutocompletePredictions() functions similarly to getAutocompletePredictions()."
source (https://developers.google.com/places/android-sdk/client-migration)
So to get auto complete predictions we can use below code:
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
// and once again when the user makes a selection (for example when calling fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
// Create a RectangularBounds object.
RectangularBounds bounds = RectangularBounds.newInstance(
new LatLng(-33.880490, 151.184363),
new LatLng(-33.858754, 151.229596));
// Use the builder to create a FindAutocompletePredictionsRequest.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
// Call either setLocationBias() OR setLocationRestriction().
.setLocationBias(bounds)
//.setLocationRestriction(bounds)
.setCountry("au")
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(query)
.build();
placesClient.findAutocompletePredictions(request).addOnSuccessListener((response) -> {
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPlaceId());
Log.i(TAG, prediction.getPrimaryText(null).toString());
}
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.e(TAG, "Place not found: " + apiException.getStatusCode());
}
});
Replace GoogleApiClient with GeoDataClient
mGoogleApiClient = Places.getGeoDataClient(this, null);
Replace AutocompletePredictionBuffer with AutocompletePredictionBufferResponse
private ArrayList getAutocomplete(CharSequence constraint) {
if (mGoogleApiClient != null) {
// Submit the query to the autocomplete API and retrieve a PendingResult that will
// contain the results when the query completes.
Task<AutocompletePredictionBufferResponse> results = mGoogleApiClient.getAutocompletePredictions(constraint.toString(), null, mPlaceFilter);
// This method should have been called off the main UI thread. Block and wait for at most 60s
// for a result from the API.
try {
Tasks.await(results, 60, TimeUnit.SECONDS);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
Utils.handleException(e);
}
AutocompletePredictionBufferResponse autocompletePredictions = results.getResult();
// Freeze the results immutable representation that can be stored safely.
return DataBufferUtils.freezeAndClose(autocompletePredictions);
}
return null;
}

Turn by turn directions in android app using Mapbox

A colleague of mine is currently working on implementing turn by turn directions into an app that is being developed for the company we are working in. I have been tasked with trying to assist him but neither of us have been able to make any progress.
He is using Mapbox to create the map. I have never used mapbox before so I am not much help.
He has code implemented that should give us turn by turn directions but it does not seem to be doing anything whatsoever.
Sorry if I am bringing up old questions or am not stating my situation clearly but this is the best I can explain myself. We have done much searching but nothing we found seems to help.
Here is the code that he has tried using that is supposed to implement turn by turn directions.
private void getRoute(Waypoint origin, Waypoint destination) throws ServicesException {
MapboxDirections client = new MapboxDirections.Builder()
.setOrigin(origin)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_DRIVING)
.setSteps(true)
// .setOverview(DirectionsCriteria.OVERVIEW_FULL)
.setInstructions(DirectionsCriteria.INSTRUCTIONS_TEXT)
.setAccessToken("pk.eyJ1IjoibnRyY3N2ZyIsImEiOiJCUmc4OHhjIn0.shHWdNg3Q32QUHJ1nOCs3A")
.build();
client.enqueue(new retrofit.Callback<DirectionsResponse>() {
#Override
public void onResponse(Response<DirectionsResponse> response, Retrofit retrofit) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().getRoutes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
}
#Override
public void onFailure(Throwable t) {
Log.e(TAG, "Error: " + t.getMessage());
Toast.makeText(MainActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
public void onResponse(Response<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().getRoutes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
drawRoute(currentRoute);
}
private void drawRoute(DirectionsRoute route) {
// Convert LineString coordinates into LatLng[]
LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
List<Position> coordinates = lineString.getCoordinates();
LatLng[] points = new LatLng[coordinates.size()];
for (int i = 0; i < coordinates.size(); i++) {
points[i] = new LatLng(
coordinates.get(i).getLatitude(),
coordinates.get(i).getLongitude());
}
Polyline polyline = mMapboxMap.addPolyline(new PolylineOptions()
.add(points)
.color(Color.RED)
.width(5));
directionsOn = true;
}
Any help would be very much appreciated.
Thanks in advance.
I'd highly recommend changing from Directions v4 to v5 found in Mapbox Java. Once you make the switch, you can work off this example found on our website. Make sure you are also passing in coordinates in the correct order, longitude is given first followed by latitude.
Dear friend mapbox provides detailed document with sample code snippets as well.
I have build a working app for my requirement by following mapbox turn by turn navigation documents.
please follow the link and let me know if you face any issues.
Link : https://www.mapbox.com/android-docs/navigation/overview/navigation-ui/
Here you can use NavigationView component to customise the mapbox turn by turn features.

Mapbox Offlne (Android)

I'm working on MapBox off line. The code was OK, able to download map but after adding some peice of code which have nothing to do with the map, the download stop to work and the give an HTTP401 Error.
I've noticed that depending on where you call MapboxAccountManager.start sometimes it fails.
Here's the code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
DB_Handler db_ansb = new DB_Handler(Init_Carte.this,null,null,1);
// Get data from DB, about the map
HashMap<String, String> data_mapbox = db_ansb.do_get_mapbox(0);
the_mapbox_token = data_mapbox.get("tmapbox_token");
the_mapbox_style = data_mapbox.get("tmapbox_style");
the_mapbox_zoom_min = Integer.parseInt(data_mapbox.get("tmapbox_zoom_min"));
the_mapbox_zoom_max = Integer.parseInt(data_mapbox.get("tmapbox_zoom_max"));
the_mapbox_inter = Double.parseDouble(data_mapbox.get("tmapbox_inter"));
OfflineManager offlineManager = OfflineManager.getInstance(this);
MapboxAccountManager.start(this,the_mapbox_token);
setContentView(R.layout.activity_init_carte);
// Menu with APP compat
// https://developer.android.com/training/appbar/setting-up.html
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
// Find our truck GPS position for road map
HashMap<String, String> my_truck = db_ansb.do_get_my_truck();
String str_truck_lagps = my_truck.get("frota_lagps");
String str_truck_logps = my_truck.get("frota_logps");
the_lagps_truck = Double.parseDouble(str_truck_lagps);
the_logps_truck = Double.parseDouble(str_truck_logps);
// Find accident location for road map
HashMap<String, String> my_inter = db_ansb.do_get_inter_resume();
String str_inter_lagps = my_inter.get("inter_lagps");
String str_inter_logps = my_inter.get("inter_logps");
the_lagps_inter = Double.parseDouble(str_inter_lagps);
the_logps_inter = Double.parseDouble(str_inter_logps);
// Compute area to get
HashMap<String, Double> data_gps_inter = db_ansb.do_get_bounds_inter(the_lagps_inter,the_logps_inter,the_mapbox_inter);
final double inter_lagps_ne = data_gps_inter.get("inter_max_lagps"); // Nord Est
final double inter_logps_ne = data_gps_inter.get("inter_max_logps");
final double inter_lagps_so = data_gps_inter.get("inter_min_lagps"); // Sud Ouest
final double inter_logps_so = data_gps_inter.get("inter_min_logps");
// Display what we're doing
tmp_id_msg = (TextView) findViewById(R.id.txt_action);
tmp_id_msg.setText(R.string.str_telechargement_carte);
// Create zone
LatLngBounds latLngBounds = new LatLngBounds.Builder()
.include(new LatLng(inter_lagps_ne, inter_logps_ne)) // Northeast
.include(new LatLng(inter_lagps_so, inter_logps_so)) // Southwest
.build();
OfflineTilePyramidRegionDefinition definition = new OfflineTilePyramidRegionDefinition(
the_mapbox_style,
latLngBounds,
the_mapbox_zoom_min,
the_mapbox_zoom_max,
(Init_Carte.this).getResources().getDisplayMetrics().density);
byte[] metadata;
try
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(JSON_FIELD_REGION_NAME, "Carte");
String json = jsonObject.toString();
metadata = json.getBytes(JSON_CHARSET);
} catch (Exception e)
{
Log.e("TAG", "Failed to encode metadata: " + e.getMessage());
metadata = null;
}
// Get data
offlineManager.createOfflineRegion(definition, metadata, new OfflineManager.CreateOfflineRegionCallback()
{
#Override
public void onCreate(OfflineRegion offlineRegion)
{
offlineRegion.setDownloadState(OfflineRegion.STATE_ACTIVE);
// Monitor the download progress using setObserver
offlineRegion.setObserver(new OfflineRegion.OfflineRegionObserver()
{
#Override
public void onStatusChanged(OfflineRegionStatus status)
{
Log.i("DBUG","onStatusChanged");
// Calculate the download percentage and update the progress bar
double percentage = status.getRequiredResourceCount() >= 0 ?
(100.0 * status.getCompletedResourceCount() / status.getRequiredResourceCount()) :
0.0;
long long_pourcentage = Math.round(percentage);
String str_pourcentage = Long.toString(long_pourcentage)+" %";
// Display on screen
tmp_id_valeur = (TextView) findViewById(R.id.val_action);
tmp_id_valeur.setText(str_pourcentage);
Log.i("DBUG",str_pourcentage+"%");
if (status.isComplete())
{
// OK so now, ask the road
do_get_trajet();
}
}
#Override
public void onError(OfflineRegionError error)
{
// If an error occurs, print to logcat
Log.i("DBUG", "onError reason: " + error.getReason());
Log.e("DBUG", "onError message: " + error.getMessage());
}
#Override
public void mapboxTileCountLimitExceeded(long limit)
{
// Notify if offline region exceeds maximum tile count
Log.i("DBUG", "Mapbox tile count limit exceeded: " + limit);
}
});
}
#Override
public void onError(String error)
{
Log.e("TAG", "Error: " + error);
}
});
}
I enter the Aysnc part, get 3 or 4 times
Log.i("DBUG",str_pourcentage+"%");
with a value of 0% then get I get:
I/System.out: [CDS]rx timeout:10000
D/NativeCrypto: ssl=0x619629c8 sslWrite buf=0x41e60068 len=222 write_timeout_millis=0
D/NativeCrypto: ssl=0x619629c8 sslRead buf=0x41e60068 len=8192,timeo=10000
I/DBUG: onError reason: REASON_OTHER
E/DBUG: onError message: HTTP status code 401
D/com.mapbox.mapboxsdk.http.HTTPRequest: [HTTP] Request with response code = 401: Unauthorized
I've noticed same strange behaviour on another page: depending on the fact you perform or not, action before of after MapboxAccountManager.start(this,the_mapbox_token); it works or not.
Notice the token is correct.
Any idea?
After changing the token in our DB, it was OK but only for a short time: I was able to download 26% of the map and then, I get again the HTTP 401 message...
Found. In fact there is a small mistake in the code that help me understand: how can this code work sometimes, as I call
OfflineManager offlineManager = OfflineManager.getInstance(this);
MapboxAccountManager.start(this,the_mapbox_token);
so as I call the init after the use of the Lib? In fact all example at Mapbox are made with one activity performing all the jobs. So when you have more than one activity using Mapbox, you quickly believe you need to put a MapboxAccountManager.start in each ones. Which is wrong. In that case (more than one activity), you must call MapboxAccountManager.start at App level. Like that:
public class App_Start extends Application
{
#Override
public void onCreate()
{
super.onCreate();
String the_mapbox_token = "pk.eyJ1IjoiYW5.....";
MapboxAccountManager.start(this,the_mapbox_token);
}
public void customAppMethod()
{
// Custom application method
}
}
and add this class at application level on your Manifest:
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name" android:theme="#style/AppTheme" android:name="net.ansb_brasil.xxxx.App_Start">
Concerning the fact the second activity was performing two times the download, it came from the fact the if (status.isComplete()) part of the onStatusChanged() is always called two times. Seems to be a bug in the Lib. On some example at Mapbox, they use a boolean flag in order to avoid taking two times this call in account.
As my first activity was downloading one map and then call a second activity for a second map, this "double call" had as result two call for the second activity and so many troubles.
Hope this will avoid headaches to others

Country Specific google place autocomplete

I am following http://examples.javacodegeeks.com/android/android-google-places-autocomplete-api-example/ this tutorial to get google place autocomplete in my app,
Now that it is working fine but I need to keep the place suggestion country specific, I have tried giving country like india , china but it is not showing any result.
Could you please help me out and tell where should I need to change the code to get it done.
Thanks,
Prashant
From Documentation for Places API
To get a list of predicted place names and/or addresses, call
GeoDataApi.getAutocompletePredictions(), passing the following
parameters:
Required: A query string containing the text typed by the user.
Required: A LatLngBounds object, restricting the results to a specific
area specified by latitude and longitude bounds.
When making request
You can specify bounds for India.
This can serve you
String apiKey = getString(R.string.places_api_key);
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), apiKey);
PlacesClient placesClient = Places.createClient(this);
}else{
Toast.makeText(PlaceAutocompleteActivity.this, "-----initialize-----", Toast.LENGTH_LONG).show();
}
// Initialize the AutocompleteSupportFragment.
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
// PlaceFields
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
// autocompleteFragment.setOnPlaceSelectedListener(MapsActivity.this);
try {
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place place) {
displayLocation(place.getLatLng().latitude,place.getLatLng().longitude,place.getName());
Toast.makeText(getApplicationContext(), "getName: " + place.getName() + " getLatLng: "+ place.getLatLng(), Toast.LENGTH_LONG).show();
// Intent i = Intent(this, idnow.se MainActivity.class);
// i.putExtra("getLatLng",place.getLatLng());
// startActivity(i);
// finish();
}
#Override
public void onError(#NonNull Status status) {
Toast.makeText(getApplicationContext(), "" + status.toString(), Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
Toast.makeText(PlaceAutocompleteActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
// PlaceFields - HERE
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
https://github.com/EddyEU/GooglePlaceAutocomplete

Android get lat&long from google address

I have implemented Google Place API autocomplete functionality for my application like this: https://developers.google.com/places/training/autocomplete-android
No it just makes a Toast with that address.
How can I get the latitude and longitude from the selected address?
Use the method
public List<Address> getFromLocationName (String locationName, int maxResults) from Android Geocoder API, pass in the location name and the maximum number of results you would like and you should be good to go.
Eg.
Geocoder coder = new Geocoder(this);
try {
ArrayList<Address> adresses = (ArrayList<Address>) coder.getFromLocationName("Some Address", 10);
for(Address add : adresses){
double longitude = add.getLongitude();
double latitude = add.getLatitude();
}
} catch (IOException e) {
e.printStackTrace();
} catch(IllegalArgumentException e){
e.printStackTrace();
}
If it helps, I've recently created a library in Java for Google Places API.
Autocompletion is as simple as:
GooglePlaces client = new GooglePlace("apiKey");
List<Prediction> predictions = client.getPlacePredictions("Empire");
for (Prediction prediction : predictions) {
String description = prediction.getDescription();
// etc etc
}
And getting a latitude-longitude from an address is as simple as.
List<Place> places = client.getPlacesByQuery(address, GooglePlaces.MAXIMUM_RESULTS);
for (Place place : places) {
if (place.getAddress().equals(address)) {
double lat = place.getLatitude();
double lng = place.getLongitude();
}
}
https://github.com/windy1/google-places-api-java
You can simply use google maps api to get the lat and long
http://maps.google.com/maps/api/geocode/json?address=&sensor=false
In the above link u have to add the address next to "address=" and u can get the json data with lat and long and some other infos.
Try GeoDataClient. Refer GeoDataClient and Place IDs and details.
geoDataClient.getPlaceById(autoCompletePredictionItem.getPlaceId())
.addOnCompleteListener(new OnCompleteListener<PlaceBufferResponse>() {
#Override
public void onComplete(#NonNull Task<PlaceBufferResponse> task) {
if (task.isSuccessful()) {
PlaceBufferResponse places = task.getResult();
Place myPlace = places.get(0);
Log.e(TAG, "Place found: " + myPlace.getLatLng().toString());
places.release();
} else {
Log.e(TAG, "Place not found.");
}
}
});
According to updated documents, GeoDAtaClient is deprecated. New way is to use this:
// Define a Place ID. val placeId = "INSERT_PLACE_ID_HERE"
// Specify the fields to return. val placeFields = listOf(Place.Field.ID, Place.Field.NAME)
// Construct a request object, passing the place ID and fields array. val request = FetchPlaceRequest.newInstance(placeId, placeFields)
placesClient.fetchPlace(request)
.addOnSuccessListener { response: FetchPlaceResponse ->
val place = response.place
Log.i(PlaceDetailsActivity.TAG, "Place found: ${place.name}")
}.addOnFailureListener { exception: Exception ->
if (exception is ApiException) {
Log.e(TAG, "Place not found: ${exception.message}")
val statusCode = exception.statusCode
TODO("Handle error with given status code")
}
}
https://developers.google.com/maps/documentation/places/android-sdk/place-details#maps_places_get_place_by_id-kotlin

Categories

Resources