Places SDK for Android(旧版)支持当前地点(旧版)。如果您熟悉“当前地点(旧版)”,那么附近搜索(新)会进行以下更改:
采用新的价格模式。如需了解所有 API 的价格信息,请参阅 Places SDK for Android(新)。
您必须通过调用
Places.initializeWithNewPlacesApiEnabled()
方法来初始化应用。如需详细了解如何选择 Places API 服务,请参阅设置 Google Cloud 项目。必须进行字段遮盖。您必须指定要在响应中返回哪些字段。没有默认的返回字段列表。如果您省略此列表,这些方法会返回错误。
附近搜索(新)不支持
PlaceLikelihood
。 借助“附近搜索(新)”,您可以使用结果顺序来确定最有可能的位置。
“附近搜索”(新)示例
如需了解详情以及如何使用“附近搜索(新)”的示例,请参阅附近搜索(新)文档。
使用附近搜索(新版)获取当前地点
以下示例演示了如何通过将 PlacesClient.findCurrentPlace()
的使用替换为 PlacesClient.searchNearby()
,使用附近搜索(新)获取当前地点:
public class MainActivity extends 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, 10);
List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.DISPLAY_NAME);
SearchNearbyRequest.Builder request = SearchNearbyRequest.builder(circle, placeFields);
placesClient
.searchNearby(request.build())
.addOnSuccessListener(response ->
List<Place> places = response.getPlaces();)
.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);
}
}
}