【问题标题】:Can Google's Places API findCurrentPlace method be used to get the exact current address, rather than the address of the closest 'Place'?可以使用 Google 的 Places API findCurrentPlace 方法来获取确切的当前地址,而不是最近的“地点”的地址吗?
【发布时间】:2021-04-17 14:15:24
【问题描述】:

我目前在我的 (Java) Android 应用程序中使用 Google Places API 来获取当前设备位置并将其显示到 editText 中。目前,当我调用 placesClient.findCurrentPlace(request) 时,会返回最近地点的列表以及设备存在的可能性,如下所示:

Place 'XXXXXXX' has likelihood: 0.600000
Place 'YYYYYYY' has likelihood: 0.0500000
Place 'ZZZZZZZ' has likelihood: 0.00000

这些地方是“泰晤士河”或“Telus 体育场”之类的地方。然后我可以从响应中获取每个地址。我的问题是,有没有办法找回手机当前位置的地址,而不是最近的“地点”的地址?

我对 Places Autocomplete 进行了类似的操作,以便它建议地址而不是地点,效果很好。不过,获取当前位置的方式略有不同,因此我似乎无法做出同样的改变。

我尝试使用 Places API 执行此操作的原因是因为我有一个用户可以输入的开始和结束位置 AutoCompleteEditText。他们可以选择在 Start Location AutoCompleteEditText 中显示他们的当前位置,我希望显示地址的格式与他们输入地址并使用 Places AutoComplete 单击它时的格式相同。

这是当前用于获取最近地点地址的代码,我想修改它以获取手机当前所在的地址。

List<Place.Field> placeFields = Collections.singletonList(Place.Field.ADDRESS);
FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(placeFields);
...
Task<FindCurrentPlaceResponse> placeResponse = placesClient.findCurrentPlace(request);
placeResponse.addOnCompleteListener(new OnCompleteListener<FindCurrentPlaceResponse>() {
    @Override
    public void onComplete(@NonNull Task<FindCurrentPlaceResponse> task) {
        if (task.isSuccessful()) { 
            FindCurrentPlaceResponse response = task.getResult();
            for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) {
                Log.i(LOG_TAG, String.format("Place '%s' has likelihood: %f",
                placeLikelihood.getPlace().getAddress(),
                placeLikelihood.getLikelihood()));
            }
        } else {
            Log.e(LOG_TAG, "Error finding current location");
        }
    }
});

【问题讨论】:

    标签: java android location google-places-api google-places


    【解决方案1】:

    不必为此使用 Google Places API - 无需与任何 API 交互即可轻松完成。

    只需使用 FusedLocationProviderClient 获取当前位置,以返回设备的最后一个已知纬度和经度(如 here 所示),然后使用 Geocoder 实例使用 getFromLocation 方法从该纬度和经度获取地址。然后可以轻松地将其转换为与 Google Places API 返回的字符串匹配的字符串(如 here 所示)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-14
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多