【发布时间】:2020-05-10 07:01:58
【问题描述】:
我已经设法使用 google.maps.places.AutocompleteService() 获取谷歌地点预测列表,当我在控制台中打印一个预测时,我得到如下输出:
现在通过使用 place_id,我已经使用服务 google.map.places.PlacesService.getDetails 获取了放置的详细信息
predictionSelected = (prediction) => {
let placeDetails= this.googlePlaces.getDetails(
{ placeId: prediction.place_id },
function (results, status) {
console.log(results);
return results;
}
);
console.log(placeDetails); // results undefined
}
现在的问题是我无法在 getDetails 中使用 this.state,所以我尝试返回结果。由于 getDetails 是异步的,我无法正确返回结果。
无论如何要在 getDetails 中使用 this.state 还是等到响应到来并在异步响应之后执行以下操作?
这是我的全部课程
import React from "react";
/* global google */
export default class AddressPredictionsClass extends React.Component {
constructor(props) {
super(props);
this.componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
postal_code: 'short_name'
};
this.state = {
street_number: '',
route: '',
locality: '',
administrative_area_level_1: '',
postal_code: '',
is_disabled: true,
is_search_disabled: false,
predictions: [],
suggestions: [],
text: '',
setIndex: -1
};
/** preserve initial state */
this.baseState = this.state;
this.autocompleteService = React.createRef();
this.googlePlaces = '';
this.onKeyDown = this.onKeyDown.bind(this);
}
onKeyDown = (e) => {
/** some code **/
}
componentDidMount() {
if (!this.autocompleteService.current) {
this.autocompleteService.current = new google.maps.places.AutocompleteService();
}
let map = new google.maps.Map(document.createElement('div'));
this.googlePlaces = new google.maps.places.PlacesService(map);
}
getPlacePredictions = (input) => {
if (input === null) {
console.log('null input');
return false;
}
var request = {
input: input,
componentRestrictions: { country: 'au' },
types: ["geocode"]
}
this.autocompleteService.current.getPlacePredictions(
request,
predictions => {
if (predictions === null) {
this.setState(
{ predictions: [] }
)
} else {
this.setState(
{ predictions: predictions.map(prediction => prediction) }
)
}
}
);
}
predictionSelected = (prediction) => {
let placeDetails=this.googlePlaces.getDetails(
{ placeId: prediction.place_id },
function (results, status) {
return results;
}
);
console.log(placeDetails);
}
changeStateValue(type, val) {
/** some code **/
}
}
onChange = (e) => {
/** some code **/
}
renderSuggestions() {
/** some code **/
}
render() {
return (
<div>
<table id="address">
<tbody>
<tr>
<td className="">Street address</td>
<td className="">
<input onChange={event => this.getPlacePredictions(event.target.value)} className=""/>
{this.renderSuggestions()}
</td>
</tr>
</tbody>
</table>
</div>
);
}
}
【问题讨论】:
-
给出调用
predictionSelected的代码,让我们修复它。
标签: javascript reactjs google-maps google-maps-api-3 async-await