谁能告诉我如何使用以下类型初始化React Google地图的StandaloneSearchBox组件:'geocode‘(就像在原始google.maps.places.Autocomplete中一样,这样我就可以限制autocomplete对输入的建议了?
发布于 2018-11-20 23:52:47
在alexandar的建议下,我能够做这样的事情。将地址传递到地址搜索中,并使用地理编码执行near by搜索。希望这能有所帮助。
import React from 'react';
import { compose, withProps, lifecycle } from 'recompose';
import { withScriptjs } from 'react-google-maps';
import StandaloneSearchBox from 'react-google-maps/lib/components/places/StandaloneSearchBox';
import get from 'lodash/get';
import head from 'lodash/head';
import { Search } from '../components';
const GOOGLE_API_KEY = '123';
const AddressSearchbox = compose(
withProps(props => {
return {
...props,
googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&v=3.exp&libraries=geometry,drawing,places`,
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
};
}),
withScriptjs,
lifecycle({
componentDidMount() {
const refs = {};
this.setState({
places: [],
searchText: '',
error: null,
onSearchBoxMounted: ref => {
refs.searchBox = ref;
},
onPlacesChanged: () => {
const places = refs.searchBox.getPlaces();
this.setState({
places,
searchText: '',
});
},
});
***
const geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: this.props.placeName }, (results, status) => {
if (status === google.maps.DirectionsStatus.OK) {
const lngs = results[0].geometry.bounds.j;
const lats = results[0].geometry.bounds.l;
this.setState({
boundSearch: new google.maps.LatLngBounds(
new google.maps.LatLng(lats.l, lngs.l),
new google.maps.LatLng(lats.j, lngs.j)
),
});
} else {
this.setState({
error: status,
});
}
***
});
},
})
)(props => {
return (
<div data-standalone-searchbox="">
<StandaloneSearchBox
ref={props.onSearchBoxMounted}
onPlacesChanged={props.onPlacesChanged}
bounds={props.boundSearch}
>
<Search searchText={props.searchText} />
</StandaloneSearchBox>
<div>{get(head(props.places), 'formatted_address')}</div>
</div>
);
});
export default AddressSearchbox;
<AddressSearchbox address="cleveland, oh" />发布于 2018-09-21 04:59:55
StandaloneSearchBox是google.maps.places.SearchBox的包装器。
所以SearchBox的谷歌文档是这样说的:
SearchBox构造函数
有两个参数:
text
结果偏向于但不限于这些边界内包含的地点。
来源:https://developers.google.com/maps/documentation/javascript/places-autocomplete#places_searchbox
所以你可以像这样调用这个组件:
<StandaloneSearchBox
ref={props.onSearchBoxMounted}
bounds={props.bounds}
onPlacesChanged={props.onPlacesChanged}
defaultBounds={new google.maps.LatLngBounds(
new google.maps.LatLng(40.712216, -74.22655),
new google.maps.LatLng(40.773941, -74.12544)
)}其中defaultBounds是表示地理坐标中的矩形的LatLngBounds class。
https://stackoverflow.com/questions/47655178
复制相似问题