javascript - 映射到 React 中的函数
问题描述
我对反应比较陌生,我正在尝试将位置列表映射到谷歌地图 API。我不知道如何将每个参数传递给谷歌 API 的函数。任何帮助都会很棒。提前致谢。
export class Mapping extends React.Component {
state = {
zoom: 1,
}
render() {
Geocode.fromAddress("Eiffel Tower").then(
response => {
const { lat, lng } = response.results[0].geometry.location;
console.log(lat, lng);
},
error => {
console.error(error);
}
);
return (
<div>
<Map className="Map" center={[47, -29]} zoom={this.state.zoom}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
/>
{this.fromAddress}
{data.features.map((loc, i) =>
<Marker key={i} position={[
loc.geometry.coordinates[0],
loc.geometry.coordinates[1]
]}/>
)}
</Map>
</div>
)
}
}
export default Mapping;
解决方案
考虑将Geocode.fromAddress
调用放入componentDidMount
method,这样一旦位置被解析并保存到state
,组件就会重新渲染。
Geocode.fromAddress
这是一个示例,它演示了如何显示从方法确定位置的标记 :
class App extends Component {
state = {
position: null
};
componentDidMount() {
Geocode.fromAddress("Eiffel Tower").then(
response => {
this.setState({position : response.results[0].geometry.location})
},
error => {
console.error(error);
}
);
}
render() {
return (
<Map center={[48.8583736, 2.2922926]} zoom={17}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
{this.state.position && <Marker position={this.state.position} />}
</Map>
);
}
}
推荐阅读
- r - 将子字符串移动到R中的字符串末尾
- java - 我对这个 Object 数组和 getter / setter 方法做错了什么?
- pandas - 使用日期时间的 isoweekday 创建新的数据框列
- powershell - 在目录中递归列出不需要的文件 - Powershell
- python - 关于 _thread.start_new_thread 方法的问题
- python - 为什么我在导入 scipy 后不能使用 scipy.linalg?
- reactjs - 安装 UI React 脚手架后下拉菜单不起作用
- javascript - 有没有办法为 Chrome 的新标签页设置样式?
- javascript - 加载页面时折叠导航栏
- c# - 我怎样才能使这个 EF Core 查询更好?