【发布时间】:2016-11-01 19:33:39
【问题描述】:
我正在创建一个反应组件,该组件具有一个表单,该表单使用地点来帮助用户更轻松地填写他们的地址。它一直运行良好,但是我想知道是否有办法阻止地点输入显示整个地址,因为我想将其用作地址字段(如果可能的话,只包含街道地址)。
现在我只是在用户最初搜索并在其中选择后将其隐藏,但是当用户想要返回并更改字段或我需要管理的任何内容时,将其设置回位置字段(再次显示在地址栏的位置)以及所有状态和焦点/单击/向下键(这是可能的,但我想知道是否有更简单的方法)。
所以 - 如果在我选择一个时谷歌位置输入没有显示整个地址,我可以解决这个问题。也许有一种方法可以拦截地点详细信息结果,我无法通过阅读 API 文档来判断。到目前为止,这是我的实现:
import React from 'react';
import ShippingAddress from './shippingAddress.jsx';
import _ from 'lodash';
function reducePlaces(memo, item) {
return {
...memo,
[item.types[0]]: {
long_name: item.long_name,
short_name: item.short_name
}
};
}
export default class MyCheckoutShipping extends React.Component {
constructor(props) {
super(props);
this.geolocate = this.geolocate.bind(this);
this.initAutocomplete = this.initAutocomplete.bind(this);
this.fillInAddress = this.fillInAddress.bind(this);
}
componentDidMount() {
this.initAutocomplete();
}
initAutocomplete() {
// eslint-disable-next-line no-undef
const autocomplete = new google.maps.places.Autocomplete((this.refs.autoCompletePlaces), {types: ['geocode']});
autocomplete.addListener('place_changed', this.fillInAddress);
this.setState({ autocomplete });
}
fillInAddress() {
const place = this.state.autocomplete.getPlace();
const addressObj = _.reduce(place.address_components, reducePlaces, { street_address: place.name });
this.props.updateShippingAddress(addressObj);
}
geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
const geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
// eslint-disable-next-line no-undef
const circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
this.state.autocomplete.setBounds(circle.getBounds());
});
}
}
render() {
let autoCompleteStyle;
if (this.props.user.checkout.shipping.address) {
autoCompleteStyle = { 'display': 'none'};
}
return (
<div className="col-xs-12 My-checkout-shipping">
<div className="col-sm-12 col-md-8 shipping-information">
<form>
<div className="form-group" style={autoCompleteStyle}>
<input
type="text"
className="form-control"
placeholder="Street Address"
onFocus={this.geolocate}
ref="autoCompletePlaces"
/>
</div>
<ShippingAddress address={this.props.user.checkout.shipping.address} />
</form>
</div>
</div>
);
}
}
MyCheckoutShipping.displayName = 'MyCheckoutShipping';
MyCheckoutShipping.propTypes = {
user: React.PropTypes.object,
updateShippingAddress: React.PropTypes.func
};
所以它只是在组件安装时初始化,我的 google api 脚本在我的 index.html 上有键 - 这一切都很好。有谁知道让places字段只输入街道地址而不是完整地址的方法,这样我就不必对所有用户状态进行微观管理?感谢阅读!
【问题讨论】:
标签: javascript google-maps reactjs google-places-api