2017-10-17 51 views
0

即使用戶搜索城市中的任何地點,輸出也應該是城市的名稱。如何在使用Google API時將輸出作爲城市名稱而不是整個地址輸入到我的應用中?

package com.example.rajat.location; 

import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.TextView; 

import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlaceAutocomplete; 

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 

    /* 
    * In this method, Start PlaceAutocomplete activity 
    * PlaceAutocomplete activity provides-- 
    * a search box to search Google places 
    */ 
    public void findPlace(View view) { 
     try { 
      Intent intent = 
        new PlaceAutocomplete 
          .IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN) 
          .build(this); 
      startActivityForResult(intent, 1); 
     } catch (GooglePlayServicesRepairableException e) { 
      // TODO: Handle the error. 
     } catch (GooglePlayServicesNotAvailableException e) { 
      // TODO: Handle the error. 
     } 
    } 

    // A place has been received; use requestCode to track the request. 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == 1) { 
      if (resultCode == RESULT_OK) { 
       // retrive the data by using getPlace() method. 
       Place place = PlaceAutocomplete().getPlace(this, data); 
       Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber()); 

       ((TextView) findViewById(R.id.searched_address)) 
         .setText(place.getName()+",\n"+ 
           place.getAddress() +"\n" + place.getPhoneNumber()); 

      } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) { 
       Status status = PlaceAutocomplete.getStatus(this, data); 
       // TODO: Handle the error. 
       Log.e("Tag", status.getStatusMessage()); 

      } else if (resultCode == RESULT_CANCELED) { 
       // The user canceled the operation. 
      } 
     } 
    } } 
+0

你得到一個JSON字符串,不是?請參閱:https://developers.google.com/places/web-service/details – jdv

回答

0

您需要使用特定於Google Places API的鍵從您的JSON響應對象中檢索城市名稱。

此鏈接顯示你正在回JSON響應(鍵值對) https://developers.google.com/places/web-service/details

檢查你的JSON響應對象(我相信這是你的「地方」的對象)。

在這行代碼上運行調試語句。 Place place = PlaceAutocomplete()。getPlace(this,data);

一旦你知道城市的關鍵,抓住城市的價值,只填充您的用戶界面與城市值。

+0

由於整個地址存儲在密鑰**地址**中,我無法獲得城市的密鑰。對於不同的城市或州來說,沒有關鍵。 –

相關問題