get Lat Lang from a place_id returned by autocomplete place api

前端 未结 12 1453
情深已故
情深已故 2021-02-02 05:58

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 a

相关标签:
12条回答
  • 2021-02-02 06:17

    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

    0 讨论(0)
  • 2021-02-02 06:17
    @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.

    0 讨论(0)
  • 2021-02-02 06:22

    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.

    0 讨论(0)
  • 2021-02-02 06:27

    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.

    0 讨论(0)
  • 2021-02-02 06:28

    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);
    
    0 讨论(0)
  • 2021-02-02 06:28

    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());
      }
    }
    
    0 讨论(0)
提交回复
热议问题