Jon*_*man 3 google-maps-api-3 react-native
我已经为我的地址字段实现了自动完成功能,但从 Google 地图地点自动完成功能返回的 json 不包含这些地点的地理编码坐标。
有一些答案似乎不合适。例如,这个指的是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 });
}
Run Code Online (Sandbox Code Playgroud)
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",
],
}
Run Code Online (Sandbox Code Playgroud)
ham*_*ifi 11
我找到了同样的解决方案 -
就像这样使用-
<GooglePlacesAutocomplete
GooglePlacesDetailsQuery={{ fields: "geometry" }}
fetchDetails={true} // you need this to fetch the details object onPress
placeholder="Search"
query={{
key: "API_KEY_GOES_HERE",
language: "en", // language of the results
}}
onPress={(data: any, details: any = null) => {
console.log("data", data);
console.log("details", details);
console.log(JSON.stringify(details?.geometry?.location));
}}
onFail={(error) => console.error(error)} />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12462 次 |
| 最近记录: |