Ada*_*m.V 11 javascript google-maps-api-3 reactjs
我想在我的react组件中有一个自动完成位置搜索栏,但是不知道如何实现它。该文件说包括
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
Run Code Online (Sandbox Code Playgroud)
在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;
Run Code Online (Sandbox Code Playgroud)
Vad*_*hev 14
通过静态加载Google Maps API import
:
import "https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places&callback=initMap";
Run Code Online (Sandbox Code Playgroud)
不支持,为此您需要考虑其他选项:
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places"></script>
现在关于SearchBar
组件,下面的示例演示如何基于此官方示例实现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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9807 次 |
最近记录: |