如何限制Google Places自动补全搜索至指定城市?使用FaridSafi/react-native-google-places-autocomplete
限制react-native-google-places-autocomplete搜索范围到指定城市的方案
嘿,我对这个组件的用法挺熟的,给你几个实用的办法来把搜索范围锁定在目标城市里:
方案1:通过经纬度+半径圈定范围
如果你能拿到目标城市的中心经纬度,直接用location和radius参数就能把搜索范围限制在该区域内。比如假设你要锁定北京,中心经纬度大概是39.9042, 116.4074,设置半径为5000米(5公里),这样返回的结果会优先这个区域内的地点:
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; <GooglePlacesAutocomplete placeholder='搜索地点' onPress={(data, details = null) => { // 处理选中结果 }} query={{ key: '你的Google Places API密钥', language: 'zh-CN', // 目标城市中心经纬度 location: '39.9042, 116.4074', // 搜索半径,单位米,这里设5公里 radius: 5000, // 可选:强制只返回指定半径内的结果 strictbounds: true }} />
提示:strictbounds设为true的话,会严格只返回半径范围内的结果,不设的话只是优先展示该区域的内容。
方案2:用components参数精准指定城市
如果不想用经纬度,直接通过components参数指定城市(甚至国家、省份),这样API会强制返回符合条件的地点。比如要锁定上海:
<GooglePlacesAutocomplete placeholder='搜索地点' onPress={(data, details = null) => { // 处理选中结果 }} query={{ key: '你的Google Places API密钥', language: 'zh-CN', // 指定国家为中国,城市为上海 components: { country: 'CN', locality: '上海' } }} />
说明:locality对应城市级别的行政区划,administrativeArea可以指定省份,country用两位国家代码(比如CN是中国,US是美国)。组合起来用能进一步缩小范围。
额外技巧:动态获取当前所在城市
如果需要自动锁定用户当前所在的城市,可以先通过地理定位拿到当前坐标,再调用Google的逆地理编码API获取城市名称,最后把城市名称传给components或者把坐标传给location参数。比如用react-native-geolocation-service获取位置:
// 先获取当前位置 import Geolocation from 'react-native-geolocation-service'; Geolocation.getCurrentPosition( (position) => { const { latitude, longitude } = position.coords; // 这里可以把经纬度传给GooglePlacesAutocomplete的location参数 this.setState({ currentLocation: `${latitude}, ${longitude}` }); }, (error) => { console.log(error.code, error.message); }, { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 } ); // 然后在组件中使用 <GooglePlacesAutocomplete query={{ key: '你的API密钥', language: 'zh-CN', location: this.state.currentLocation, radius: 5000, strictbounds: true }} />
最后别忘了确保你的Google Places API密钥已经启用了「Places API」和「Geocoding API」(如果用到逆地理编码的话),不然会返回权限错误哦。
内容的提问来源于stack exchange,提问作者Yasir Aziz
相关产品推荐
相关产品推荐

