我正在尝试将Google Places(自动填充字段)与我的具有Material UI样式的reactjs网站集成在一起。 我确实在Material UI文档中找到了这个演示 Google Maps place 但是当我对输入内容进行更改时,它对我没有用
谢谢,希望您能得到我要解释的内容
答案 0 :(得分:0)
嘿,请尝试以下代码:
// Imports
import React, { Component } from 'react';
// Import Search Bar Components
import SearchBar from 'material-ui-search-bar';
// Import React Scrit Libraray to load Google object
import Script from 'react-load-script';
class Search extends Component {
// Define Constructor
constructor(props) {
super(props);
// Declare State
this.state = {
city: '',
query: ''
};
}
handleScriptLoad = () => {
// Declare Options For Autocomplete
const options = {
types: ['(cities)'],
};
// Initialize Google Autocomplete
/*global google*/ // To disable any eslint 'google not defined' errors
this.autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'),
options,
);
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components and formatted
// address.
this.autocomplete.setFields(['address_components', 'formatted_address']);
// Fire Event when a suggested name is selected
this.autocomplete.addListener('place_changed', this.handlePlaceSelect);
}
handlePlaceSelect = () => {
// Extract City From Address Object
const addressObject = this.autocomplete.getPlace();
const address = addressObject.address_components;
// Check if address is valid
if (address) {
// Set State
this.setState(
{
city: address[0].long_name,
query: addressObject.formatted_address,
}
);
}
}
render() {
return (
<div>
<Script
url="https://maps.googleapis.com/maps/api/js?key=your_api_key&libraries=places"
onLoad={this.handleScriptLoad}
/>
<SearchBar id="autocomplete" placeholder="" hintText="Search City" value={this.state.query}
style={{
margin: '0 auto',
maxWidth: 800,
}}
/>
</div>
);
}
}
export default Search;
如有疑问,请点击链接:
答案 1 :(得分:0)
如果您查看该演示的Console
,将会看到错误:
Google Maps JavaScript API错误:InvalidKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error
Google Maps仅使用有效的API密钥,出于安全目的,该演示中默认提供的密钥是无效的,您必须生成自己的密钥,可以在此处进行操作:
https://developers.google.com/maps/documentation/javascript/get-api-key
答案 2 :(得分:0)
我确实忘记安装lodash 现在工作正常