gpt4 book ai didi

reactjs - 获取谷歌地图时遇到问题

转载 作者:行者123 更新时间:2023-12-03 08:40:13 31 4
gpt4 key购买 nike

googlemapapi我在获取谷歌地图时遇到问题,它说页面无法正确加载,我的控制台上也有一些错误。我不明白我做错了什么,我应该能够进行查询并在建议中显示位置,但我做错了。这是我的组件,我还附上了一张照片。欢迎所有帮助[

import React, { Component } from "react";
import { Map, Marker, GoogleApiWrapper } from "google-maps-react";

const apiKey = process.env.REACT_APP_GOOGLE_API_KEY;



const center = {
lat: 51.5074,
lng: 0.1278,
};

let service = null;

export class MapContainer extends Component {
constructor(props) {
super(props);

this.state = {
input: "",
suggestions: [],
places: [],
};
}

savePlace = (place) => {
this.setState({ places: [...this.state.places, place] });
};

handleChange = (e) => {
this.setState({ input: e.target.value });
};

handleKeyPress = (event) => {
if (event.key === "Enter") {
this.search();
}
};



search = () => {
const {input} = this.state;
service.textSearch({query: input}, (suggestions) => {
this.setState({suggestions});
})

};

initPlaces(mapProps, map) {
const { google } = mapProps;
service = new google.maps.places.PlacesService(map);
}

render() {

const { suggestions, places } = this.state;



return (
<div className="container">
<div className="row">
<div className="col">
<div className="form-inline d-flex justify-content-between mb-4">
<input
type="text"
value={this.state.input}
onChange={this.handleChange}
className="form-control flex-grow-1"
placeholder="Search for places on Google Maps"
onKeyPress={this.handleKeyPress}
/>
<button onClick={this.search} className="btn btn-primary ml-2">
Search
</button>
</div>
<h3>Suggestions</h3>
<ul className="list-group">
{suggestions.map((place, i) => (
<li
key={i}
className="list-group-item d-flex justify-content-between align-items-center"
>
<div>
<div>
<strong>{place.name}</strong>
</div>
<span className="text-muted">
{place.formatted_address}
</span>
</div>

<button
className="btn btn-outline-primary"
onClick={() => this.savePlace(place)}
>
Show
</button>
</li>
))}
</ul>
</div>
<div className="col">

<Map google={this.props.google} zoom={14} initialCenter={center} onReady={this.initPlaces}></Map>

</div>
</div>
</div>
);
}
}

export default GoogleApiWrapper({
apiKey,
})(MapContainer);


] 2

最佳答案

我检查了你的代码,如果你直接把你的 API key 放在你的const apiKey = "PUT_YOUR_API_KEY_HERE"; ,它将正确显示您的 map 。

您似乎将变量放在 .env file 中(引用 here 如何添加自定义环境变量)。确保您将 .env file在 src 文件夹之外并将其设置在您的 .env 文件中:REACT_APP_GOOGLE_API_KEY=API_KEY_VALUE_HERE .这对我有用。

您可以在 link 中找到示例代码.

确保更改 REACT_APP_GOOGLE_API_KEY 的值在 .env 文件中添加到您的 API key 。

希望这可以帮助!

关于reactjs - 获取谷歌地图时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62220653/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com