2017-04-10 96 views
0

我想通過將place_id傳遞給Places.GeoDataApi來獲取地點,但它不返回任何內容,並且我確信place_id是正確的。Geo Data API不返回任何結果

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

    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(Places.GEO_DATA_API) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this).build(); 

    String placeId = "ChIJja4QaeH0GjkRKK5cBjTfKQo"; 

    Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId) 
      .setResultCallback(new ResultCallback<PlaceBuffer>() { 
       @Override 
       public void onResult(@NonNull PlaceBuffer places) { 
        if(places.getStatus().isSuccess() && places.getCount()>0){ 
         final Place myPlace = places.get(0); 
         Log.i(String.valueOf(MainActivity.this), 
           "Place found: " + myPlace.getName() + "\n Address: " + myPlace.getAddress()); 
        } else { 
         Log.i(String.valueOf(MainActivity.this),"Place not found!"); 
        } 
        places.release(); 
       } 
      }); 
} 

編輯:新增manifest.xml文件

AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?> 

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.INTERNET" /> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:roundIcon="@mipmap/ic_launcher_round" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <activity android:name=".MainActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <meta-data 
     android:name="com.google.android.geo.API_KEY" 
     android:value="MY_API_KEY"/> 

</application> 

+0

發表您的清單... – rafsanahmad007

+0

張貼@ rafsanahmad007 –

+1

@GautamHans不推薦將您的API密鑰公開給公衆,請儘快隱藏它... !!!! –

回答

1

代碼非常類似一個我implemented..except一件事。

你忘了打電話給mGoogleApiClient.connect();

在你的代碼:

mGoogleApiClient = new GoogleApiClient.Builder(this) 
     .addApi(Places.GEO_DATA_API) 
     .addConnectionCallbacks(this) 
     .addOnConnectionFailedListener(this).build(); 

mGoogleApiClient.connect(); //add this 

//now call the placeID codes Result callback 

編輯

小幅更新的條件:

if(places.getStatus().isSuccess()){ 
    final Place myPlace = places.get(0); 
    Log.i(String.valueOf(MainActivity.this), 
      "Place found: " + myPlace.getName() + "\n Address: " + myPlace.getAddress()); 
} else { 
    Log.i(String.valueOf(MainActivity.this),"Place not found!"); 
} 
+0

謝謝。有效! :) 但即使place_id正確,我仍在日誌中找到Place Not Found。 –

+0

它將返回...指定的placeID .. – rafsanahmad007

+0

是的,我指定placeId像 String placeId =「ChIJja4QaeH0GjkRKK5cBjTfKQo」; 即使那個地方沒有找到。 我已經嘗試了另一個ID「ChIJfapwfcT0GjkR6aj2WIaRdIk」 它應該返回「Virk醫院和產婦之家」 但它會轉到其他部分。 –