Android 从自动完成位置 api 返回的 place_id 中获取 Lat Lang

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25928948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:51:09  来源:igfitidea点击:

get Lat Lang from a place_id returned by autocomplete place api

androidgoogle-mapsgoogle-maps-android-api-2latitude-longitudegoogle-places-api

提问by Sajal

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?

我正在使用 google autocomplete place api 在我的应用程序中搜索该地点,现在我想获取我搜索过的地点的纬度和经度。如何从谷歌在android中自动完成地方api返回的结果中获取纬度和经度?

回答by droidmad

The following code snippet which uses Google Places API for android worked for me

以下使用 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();
  }
});

Visit Google Places API for Androidfor a full list of methods to retrieve data from a place

访问适用于 Android 的 Google Places API获取从地点检索数据的完整方法列表

回答by CallMeLaNN

Google Place Detailsis the answer.

Google 地方详情就是答案。

From the place_idyou got, query Place Details something like https://maps.googleapis.com/maps/api/place/details/json?placeid={placeid}&key={key}and you can get the latand lngfrom result.geometry.locationJSON.

place_id你得到的,查询 Place Details 之类的https://maps.googleapis.com/maps/api/place/details/json?placeid={placeid}&key={key},你可以从JSON 中获取lat和。lngresult.geometry.location

回答by nitzanj

Each place returned in the place-autocomplete response has an Id and a reference string as explained here.

在这个地方,自动完成响应返回的每个地方都有一个ID和解释参考串这里

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

使用任一(最好是 Id,因为参考已弃用)查询 Places API 以获取有关该地点的完整信息(包括 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.

关于 shyam 的评论 - 只有在自动完成响应中获得完整地址时,地理编码才会起作用,但情况并非总是如此。此外,地理编码提供了可能结果的列表,因为您在自动完成响应中获得的地点描述不是唯一的。根据您的需要,地理编码可能就足够了。

回答by Fahry Mohammed

@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 LatLngas well as the String address. Use the LatLng wherever you want.

使用上面的代码,您可以获得LatLng以及字符串地址。随时随地使用 LatLng。

回答by Ravi Rajput

Based on the latest version of AutoComplete documentation

基于最新版本的 AutoComplete 文档

Option 1: Embed an AutocompleteSupportFragment

选项 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));

Option 2: Use an intent to launch the autocomplete activity

选项 2:使用意图启动自动完成活动

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

注:显示的结果是将Place对象解析为json

回答by Muhammad Yasir

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);

回答by rachna patwal

do provide Place.Field.LAT_LNG to get the latitude and longitude for the place.

请提供 Place.Field.LAT_LNG 以获取该地点的纬度和经度。

 autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, 
 Place.Field.NAME,Place.Field.LAT_LNG));

then get LatLng

然后得到 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();

回答by Sal

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:

地理编码是一种非常间接的解决方案,就像第二个响应者所说的那样,如果您执行“Apple Store”,它可能不会返回完整地址。反而:

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).

Place_ID 包含您需要的一切。我假设您知道如何从 Places API 获取 place_id(如果没有,他们有一个完整的示例)。

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

然后使用以下文档的 place_id 拉取对地点详细信息(包括几何部分下的纬度和经度)的第二个请求:https: //developers.google.com/places/documentation/details?utm_source =welovemapsdevelopers&utm_campaign =mdr-devdocs

回答by rohitsakala

Ref :- https://developers.google.com/places/android/place-details#get-placeThe 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.

参考:- https://developers.google.com/places/android/place-details#get-place上面的链接给出了一个地方对象,它将具有 lat 和 long 。地点对象源自人们从地点自动完成获得的地点 ID。

回答by Blaise Siani

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());
    }    
}