You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android新版Places Autocomplete如何设置Location Bias?

解决新版Places SDK中setLocationBias()的参数问题

嘿,我刚好在迁移到新版New Places SDK时遇到过一模一样的困惑!其实完全不用自己去实现LocationBias接口——Google已经为我们封装好了两个现成的实现类,直接拿来用就行:

1. 用矩形范围限定位置偏好(RectangularBounds)

如果想把搜索范围限定在某个矩形区域内(比如某座城市的大致范围),可以用RectangularBounds。只需要传入区域西南角和东北角的经纬度坐标:

import com.google.android.libraries.places.api.model.LatLng;
import com.google.android.libraries.places.api.model.RectangularBounds;
import com.google.android.libraries.places.api.model.LocationBias;

// 定义矩形范围:西南角坐标 → 东北角坐标
LocationBias locationBias = RectangularBounds.newInstance(
    new LatLng(39.9042, 116.4074), // 示例:北京天安门附近西南角
    new LatLng(40.0042, 116.5074)  // 对应区域的东北角
);

2. 用圆形范围限定位置偏好(CircularBounds)

如果需要以某个点为中心,限定半径范围内的搜索结果,就用CircularBounds,参数是中心点坐标和半径(单位为米):

import com.google.android.libraries.places.api.model.CircularBounds;

// 定义圆形范围:中心点 + 5公里半径
LocationBias locationBias = CircularBounds.newInstance(
    new LatLng(39.9042, 116.4074), // 中心点坐标
    5000 // 半径,单位是米
);

完整的Autocomplete Intent构建示例

把上面生成的LocationBias实例传入Autocomplete.IntentBuilder即可完成配置:

import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
import com.google.android.libraries.places.api.model.Place;
import java.util.Arrays;

// 构建Autocomplete界面的Intent
Intent intent = new Autocomplete.IntentBuilder(
        AutocompleteActivityMode.OVERLAY, // 可选OVERLAY(悬浮层)或FULLSCREEN(全屏)模式
        Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG) // 指定需要返回的Place字段
    )
    .setLocationBias(locationBias) // 设置位置偏好
    .build(getApplicationContext());

// 启动Autocomplete界面,记得提前定义请求码YOUR_AUTOCOMPLETE_REQUEST_CODE
startActivityForResult(intent, YOUR_AUTOCOMPLETE_REQUEST_CODE);

额外说明

  • RectangularBounds和CircularBounds都是LocationBias接口的官方实现类,已经帮我们处理了Parcelable的序列化逻辑,完全满足SDK的要求,不用自己再写接口实现。
  • 只有当你需要自定义不规则区域的位置偏好时,才需要手动实现LocationBias接口,但绝大多数业务场景下,这两个现成的类足够覆盖需求了。

内容的提问来源于stack exchange,提问作者Sorin Bolos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:37:47