我正在使用Google自动完成地点API在我的应用程序中搜索地点,现在我想获取我搜索的位置的纬度和经度。如何从Google在Android中返回的自动完成地点API结果中获取纬度和经度?
我正在使用Google自动完成地点API在我的应用程序中搜索地点,现在我想获取我搜索的位置的纬度和经度。如何从Google在Android中返回的自动完成地点API结果中获取纬度和经度?
以下代码片段使用Google Places API for android 对我很有用
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();
}
});
访问Google Places API for Android以获得从地点检索数据的完整方法列表。
从您获取的place_id
,查询类似这样的Place Details https://maps.googleapis.com/maps/api/place/details/json?placeid={placeid}&key={key}
,并且您可以从result.geometry.location
JSON 中获取lat
和lng
。
使用Place.Field.LAT_LNG可以获取地点的纬度和经度。
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID,
Place.Field.NAME,Place.Field.LAT_LNG));
然后获取经纬度
LatLng destinationLatLng = place.getLatLng();
并且可以透过吐司看到
destlat = destinationLatLng.latitude;
destLon = destinationLatLng.longitude;
Toast.makeText(getApplicationContext(), "" + destlat + ',' + destLon, Toast.LENGTH_LONG).show();
根据最新版本的AutoComplete文档
选项1:嵌入一个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));
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);
无论您对哪个领域感兴趣,都需要按照上述所述进行提及。
您将获得以下结果:
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."
}
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);
@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());
}
}
}
使用上述代码,您可以获取LatLng以及字符串地址。随时在需要的地方使用LatLng。
参考链接:- https://developers.google.com/places/android/place-details#get-place 上面的链接提供了一个地点对象,其中包含纬度和经度。该地点对象是从地点自动完成获取到的地点ID派生出来的。
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());
}
}