javascript - 无法使用 ReactJS 重新渲染 Google 地图
问题描述
我正在尝试根据位置(城市)重新渲染谷歌地图。我在输入类型中输入了城市,但没有任何反应。谁能帮我这个?我已经尝试了很多东西,但没有任何反应。问候,
https://pastebin.pl/view/e31aeb6a [在此处输入链接描述][1]
解决方案
您可能正在寻找类似的东西,您将使用 Geocoding API 从您的输入中对地址进行地理编码,然后一旦地理编码,它将获取坐标并使用 Maps JavaScript API 将其绘制到您的地图上。
您可能还想使用 Maps JavaScript API 检查 Places Autocomplete,它会在其中提供有关您正在搜索的地址的建议,然后在地图上呈现您选择的地点。
请注意,如果您想使用 Google Maps API,您需要使用 API 密钥,并且这些 API 的使用会相应收费。
这是我在 React 上实现它的方法。下面的代码片段:
import React from 'react';
import ReactDOM from 'react-dom';
import './style.css';
var map;
const API_KEY = "PUT_API_KEY_HERE";
class GeocodingApp extends React.Component {
constructor(props) {
super(props);
this.renderMap = this.renderMap.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleClick = this.handleClick.bind(this);
this.state = {
input: ""
};
}
componentDidMount() {
if (!window.google) {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = `https://maps.googleapis.com/maps/api/js?key=` + API_KEY + `&libraries=geometry,places`;
script.id = 'googleMaps';
script.async = true;
script.defer = true;
document.body.appendChild(script);
script.addEventListener('load', e => {
this.renderMap()
})
} else {
this.renderMap()
}
}
renderMap() {
const coords = { lat: 41.375885, lng: 2.177813 };
const el = document.getElementById("map");
if (el) {
map = new google.maps.Map(el, {
zoom: 16,
center: {
lat: coords.lat,
lng: coords.lng
}
});
return map;
} else {
return null;
}
}
handleInputChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleClick(event) {
const geocoder = new google.maps.Geocoder();
this.codeAddress(geocoder);
event.preventDefault();
}
//Handles Geocoding part
codeAddress(geocoder) {
var address = this.state.input;
geocoder.geocode({ address: address }, function(results, status) {
if (status === "OK") {
//'results[0].geometry.location' is the coordinates of the address you want to find
map.setCenter(results[0].geometry.location);
} else {
return null;
}
});
}
render() {
return (
<div >
<h1>ADD YOUR API KEY TO MAKE IT WORKIN</h1>
<input
id="input"
name="input"
value={this.state.input}
onChange={this.handleInputChange}
/>
<button id="submit" onClick={this.handleClick}>
{" "}
Search
</button>
<div id="map" />
</div>
);
}
}
ReactDOM.render(<GeocodingApp />, document.getElementById("app"));
推荐阅读
- php - 无法使用 Twitter API 使不记名令牌无效
- javascript - 如何将值为 Id 的复选框列表保存到数据库中?
- python - psycopg2 错误:在数据中找到文字回车
- arrays - 通过 Google Script 多次创建包含另一个数组元素的真实副本的新数组
- firebase - 我需要为 Firebase 动态链接添加额外的 Firebase SDK 吗?
- microsoft-graph-api - 无法立即获得有关新租户的报告
- curl - 使用 cURL 下载受密码保护的 Dropbox 链接
- bluez - 使用 Meshctl 进行蓝牙 Mesh 配置:“连接”不起作用
- r - Seewave:读取数据框中的多个 .wav 文件
- symfony4 - 启动 symfony 本地 Web 服务器时设置自定义端口