Android 版 Places SDK (舊版) 支援目前位置 (舊版)。如果您熟悉 Current Place (舊版),Nearby Search (新版) 會進行下列變更:
採用新的定價模式。如要瞭解所有 API 的價格資訊,請參閱「 Places SDK for Android (新版)」。
您必須呼叫
Places.initializeWithNewPlacesApiEnabled()方法來初始化應用程式。如要進一步瞭解如何選取 Places API 服務,請參閱「設定 Google Cloud 專案」一文。必須遮蓋欄位。您必須指定要在回應中傳回的欄位。系統不會預設傳回任何欄位。如果省略這份清單,方法會傳回錯誤。
Nearby Search (新推出) 不支援
PlaceLikelihood。使用「鄰近搜尋 (新版)」時,您可以根據結果順序判斷最有可能的地點。
Nearby Search (新推出) 範例
如需更多資訊,以及如何使用 Nearby Search (新版) 的範例,請參閱 Nearby Search (新版) 說明文件。
使用 Nearby Search (新版) 取得目前地點
下列範例示範如何使用「鄰近搜尋 (新版)」取得目前地點,方法是將 PlacesClient.findCurrentPlace() 替換為 PlacesClient.searchNearby():
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient fusedLocationProviderClient;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
// ...
// get permission
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
// get location and search
fusedLocationProviderClient
.getLastLocation()
.addOnSuccessListener(
this,
location -> {
if (location != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CircularBounds circle = CircularBounds.newInstance(latLng, 100);
List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.DISPLAY_NAME);
// Define a list of types to exclude. Adjust this list to suit each application.
final List<String> excludedTypes = Arrays.asList("public_bathroom", "beach");
SearchNearbyRequest request
= SearchNearbyRequest.builder(/* location restriction = */ circle, placeFields)
.setExcludedTypes(excludedTypes)
.setRankPreference(SearchNearbyRequest.RankPreference.DISTANCE)
.build();
placesClient
.searchNearby(request)
.addOnSuccessListener(
response -> {
List<Place> places = response.getPlaces();
// do more on the results
})
.addOnFailureListener(
exception -> {
// handle failure
});
} else {
// failed to get location.
}
})
.addOnFailureListener(
e -> {
// handle error
});
} else {
ActivityCompat.requestPermissions(
this,
new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_CODE);
}
}
}