【发布时间】:2019-09-12 02:34:34
【问题描述】:
我已为我的地址字段实现了自动完成功能,但从 Google 地图地点自动完成功能返回的 json 不包括这些地点的地理编码坐标。
那里有一些似乎不合适的答案。例如,this one 指的是 google.maps.places.Autocomplete(input, options); 之类的东西,我认为这在 React Native 中不是一个东西。
其他答案似乎基于react-native-google-places-autocomplete,但我自己实现了这个,我不想再使用那个模块。
这是我调用 API 的方法。
async handleAddressChange() {
const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${GoogleAPIKey}&input=${this.state.address}`;
try {
const result = await fetch(url);
const json = await result.json();
this.setState({ addressPredictions: json.predictions });
} catch (err) {
console.error(err);
}
}
setAddress(prediction) {
this.setState({ address: prediction.description, showPredictions: false });
}
API 响应上没有任何 place 或 geometry 属性:
Object {
"description": "1234 Some Avenue Northeast, Washington, DC, USA",
"id": "4c79fba1b3a5ad33478b79b54896a75a4d56ca53",
"matched_substrings": Array [
Object {
"length": 4,
"offset": 0,
},
],
"place_id": "ChIJneQ1fBO5t4kRf8mTw4ieb4Q",
"reference": "ChIJneQ1fBO5t4kRf8mTw4ieb4Q",
"structured_formatting": Object {
"main_text": "1234 Some Avenue Northeast",
"main_text_matched_substrings": Array [
Object {
"length": 4,
"offset": 0,
},
],
"secondary_text": "Washington, DC, USA",
},
"terms": Array [
Object {
"offset": 0,
"value": "1600",
},
Object {
"offset": 5,
"value": "Maryland Avenue Northeast",
},
Object {
"offset": 32,
"value": "Washington",
},
Object {
"offset": 44,
"value": "DC",
},
Object {
"offset": 48,
"value": "USA",
},
],
"types": Array [
"street_address",
"geocode",
],
}
【问题讨论】:
-
除了预测之外,响应中应该还有其他属性,这些属性仅适用于用户实际选择其中之一之前的建议
-
使用此数据,向 Places API 创建一个 Place Details Request,并返回
place_id,在上面的示例中为ChIJneQ1fBO5t4kRf8mTw4ieb4Q。 -
@MrUpsidown 这似乎是最好的方法。如果您将其发布为答案,很高兴将其标记为 答案。
-
给你!见下文:)
标签: react-native google-maps-api-3