I am searching the place in my apps using the google autocomplete place api and now I want to get latitude and longitude of the place that i have searched. How to get latitude and longitude from the result returned by autocomplete place api by google in android?
The following code snippet which uses Google Places API for android worked for me
Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId)
.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (places.getStatus().isSuccess()) {
final Place myPlace = places.get(0);
LatLng queriedLocation = myPlace.getLatLng();
Log.v("Latitude is", "" + queriedLocation.latitude);
Log.v("Longitude is", "" + queriedLocation.longitude);
}
places.release();
}
});
Visit Google Places API for Android for a full list of methods to retrieve data from a place
Google Place Details is the answer.
From the place_id
you got, query Place Details something like https://maps.googleapis.com/maps/api/place/details/json?placeid={placeid}&key={key}
and you can get the lat
and lng
from result.geometry.location
JSON.
Each place returned in the place-autocomplete response has an Id and a reference string as explained here.
Use either (preferably Id since reference is deprecated) to query Places API for the full information about that place (including lat/lng): https://developers.google.com/places/documentation/details#PlaceDetailsRequests
Regarding shyam's comment - Geocoding will work only if you got a full address in the autocomplete response which is not always the case. Also Geocoding gives a list of possible results since the place description you get in the autocomplete response is not unique. Depending on your needs, geocoding might be enough.
Geocoding is a very indirect solution, and like the second responder said, if you do "Apple Store" it may not return the full address. Instead:
Place_ID contains everything you need. I am assuming you know how to get the place_id from the Places API (they have a full example if not).
Then pull a second request for the place details (including latitude and longitude under the geometry section) using the place_id following this documentation: https://developers.google.com/places/documentation/details?utm_source=welovemapsdevelopers&utm_campaign=mdr-devdocs
Ref :- https://developers.google.com/places/android/place-details#get-place The above link gives a place object which will have lat and long . The place object is deirved from placeid that one gets from place autocomplete.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constant.REQUEST_LOCATION_CODE) {
Place place = PlaceAutocomplete.getPlace(this, data);
if (place != null) {
LatLng latLng = place.getLatLng();
mStringLatitude = String.valueOf(latLng.latitude);
mStringLongitude = String.valueOf(latLng.longitude);
EditTextAddress.setText(place.getAddress());
}
}
}
With the code above, you can get the LatLng as well as the String address. Use the LatLng wherever you want.
do provide Place.Field.LAT_LNG to get the latitude and longitude for the place.
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID,
Place.Field.NAME,Place.Field.LAT_LNG));
then get LatLng
LatLng destinationLatLng = place.getLatLng();
and can see through toast
destlat = destinationLatLng.latitude;
destLon = destinationLatLng.longitude;
Toast.makeText(getApplicationContext(), "" + destlat + ',' + destLon, Toast.LENGTH_LONG).show();
This snippet allows obtain the latitude and longitude of a place according to the identifier back into the auto complete
public class PlacesDetails {
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String TYPE_DETAIL = "/details";
private static final String OUT_JSON = "/json";
//private static final String API_KEY = "------------ make your specific key ------------; // cle pour le serveur
public PlacesDetails() {
// TODO Auto-generated constructor stub
}
public ArrayList<Double> placeDetail(String input) {
ArrayList<Double> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_DETAIL + OUT_JSON);
sb.append("?placeid=" + URLEncoder.encode(input, "utf8"));
sb.append("&key=" + API_KEY);
URL url = new URL(sb.toString());
//Log.e("url", url.toString());
System.out.println("URL: "+url);
System.out.println("******************************* connexion au serveur *****************************************");
//Log.e("nous sommes entrai de test la connexion au serveur", "test to connect to the api");
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
System.out.println("le json result"+jsonResults.toString());
} catch (MalformedURLException e) {
//Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
//Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
System.out.println("******************************* fin de la connexion*************************************************");
}
try {
// Create a JSON object hierarchy from the results
//Log.e("creation du fichier Json", "creation du fichier Json");
System.out.println("fabrication du Json Objet");
JSONObject jsonObj = new JSONObject(jsonResults.toString());
//JSONArray predsJsonArray = jsonObj.getJSONArray("html_attributions");
JSONObject result = jsonObj.getJSONObject("result").getJSONObject("geometry").getJSONObject("location");
System.out.println("la chaine Json "+result);
Double longitude = result.getDouble("lng");
Double latitude = result.getDouble("lat");
System.out.println("longitude et latitude "+ longitude+latitude);
resultList = new ArrayList<Double>(result.length());
resultList.add(result.getDouble("lng"));
resultList.add(result.getDouble("lat"));
System.out.println("les latitude dans le table"+resultList);
} catch (JSONException e) {
///Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PlacesDetails pl = new PlacesDetails();
ArrayList<Double> list = new ArrayList<Double>();
list = pl.placeDetail("ChIJbf7h4osSYRARi8SBR0Sh2pI");
System.out.println("resultat de la requette"+list.toString());
}
}
Based on the latest version of AutoComplete documentation
Option 1: Embed an AutocompleteSupportFragment
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment
.setPlaceFields(Arrays.asList(Place.Field.ID,
Place.Field.NAME,Place.Field.LAT_LNG,Place.Field.ADDRESS));
Option 2: Use an intent to launch the autocomplete activity
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME,Place.Field.LAT_LNG,Place.Field.ADDRESS);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields)
.build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
whichever fields you are interested in, you have to mention as mentioned above.
You'll get result as below:
onPlaceSelected:
{
"a":"#90, 1st Floor, Balaji Complex, Kuvempu Main Road, Kempapura, Hebbal
Kempapura, Bengaluru, Karnataka 560024, India",
"b":[],
"c":"ChIJzxEsY4QXrjsRQiF5LWRnVoc",
"d":{"latitude":13.0498176,"longitude":77.600347},
"e":"CRAWLINK Networks Pvt. Ltd."
}
Note: The result displayed is by parsing the Place object to json
add these line under function
autocomplete.addListener('place_changed', function() {});
var place = autocomplete.getPlace();
autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address']);
var lng = place.geometry.location.lng();
var lat = place.geometry.location.lat();
var latlng = {lat , lng};
console.log(latlng);
Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId)
.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (places.getStatus().isSuccess() && places.getCount() > 0) {
final Place myPlace = places.get(0);
Log.i(TAG, "Place found: " + myPlace.getName());
LatLng latlangObj = myPlace.getLatLng();
Log.v("latitude:", "" + latlangObj.latitude);
Log.v("longitude:", "" + latlangObj.longitude);
} else {
Log.e(TAG, "Place not found");
}
places.release();
}
});
Use this method for getting lat and lang from placeid.
来源:https://stackoverflow.com/questions/25928948/get-lat-lang-from-a-place-id-returned-by-autocomplete-place-api