我想在我的 react 组件中有一个自动完成位置搜索栏,但不知道我将如何实现它。 documentation说包括
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
在 HTML 文件中,然后有一个指向元素的初始化函数——我将如何使用我的 React 组件/JSX 执行此操作?我想我必须导入 api 链接,但我不知道从那里去哪里。
import React from 'react';
import "https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places&callback=initMap";
const SearchBar = () => (
<input type="text" id="search"/> //where I want the google autocomplete to be
);
export default SearchBar;
最佳答案
通过静态加载 Google Maps API import
:
import "https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places&callback=initMap";
不受支持,您需要为此考虑不同的选项:
- 通过/public/index.html 文件引用 Google Maps API JS 库:
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places"></script>
- 或动态加载JS资源,例如使用this library
现在关于 SearchBar
组件,下面的示例演示了如何基于 this official example 实现一个简单版本的 Place Autocomplete(不依赖于 Google Map 实例)
import React from "react";
/* global google */
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.autocompleteInput = React.createRef();
this.autocomplete = null;
this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
}
componentDidMount() {
this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current,
{"types": ["geocode"]});
this.autocomplete.addListener('place_changed', this.handlePlaceChanged);
}
handlePlaceChanged(){
const place = this.autocomplete.getPlace();
this.props.onPlaceLoaded(place);
}
render() {
return (
<input ref={this.autocompleteInput} id="autocomplete" placeholder="Enter your address"
type="text"></input>
);
}
}
关于javascript - 在 React 中使用 Google Place Autocomplete API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907859/