gpt4 book ai didi

javascript - 从 API 加载 geoJSON 标记 - React Leaflet

转载 作者:行者123 更新时间:2023-11-29 23:16:19 26 4
gpt4 key购买 nike

传单和使用 GeoJSON。一旦数据存储在状态中,我试图从获取的 GeoJSON API 中获取标记以在 map 上呈现。我已经尝试使用标记组件来显示来自 API 的标记,但没有任何内容呈现到页面。我愿意使用标记组件或任何其他方式来显示标记。谢谢!

import React, { Component } from "react";
import "./App.css";
import { Map, TileLayer, Marker, Popup, GeoJSON } from "react-leaflet";
import L from "leaflet";

class App extends Component {
constructor(props) {
super(props);

this.state = {
location: {
lat: 51.505,
lng: -0.09
},
zoom: 2,
bikes: null,
haveUsersLocation: false,
};

componentWillMount() {
fetch(
"https://bikewise.org:443/api/v2/locations/markers?proximity_square=10"
)
.then(response => response.json())
.then(data => this.setState({ bikes: data }));
}

render() {
const position = [this.state.location.lat, this.state.location.lng];

return (
<div className="App">
<Menu />
<Map className="map" center={position} zoom={this.state.zoom}>
<TileLayer
attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>

<GeoJSON addData={this.state.bikes} />

{this.state.haveUsersLocation ? (
<Marker position={position} icon={myIcon}>
<Popup>Your current location</Popup>
</Marker>
) : (
""
)}
</Map>
</div>
);
}
}

最佳答案

Marker 组件从未被调用的原因是 this.state.haveUsersLocation 始终为 false,并且您没有在组件的任何位置将其设置为 true。如果你只想在 haveUsersLocation 为 true 时渲染 Marker 组件,那么你需要将 haveUsersLocation 更改为 true 以渲染 Marker 否则删除条件

您需要在 componentWillMount 中将 haveUsersLocation 设置为 true,Marker 才能成功渲染

componentWillMount() {
fetch(
"https://bikewise.org:443/api/v2/locations/markers?proximity_square=10"
)
.then(response => response.json())
.then(response => this.setState({ haveUsersLocation: true, bikes: response.data.features }));
}

要强制使用react以重新呈现 GeoJSON 数据,您需要将一些数据唯一键传递给组件。查看下面的 github 问题以获取更多详细信息

   <GeoJSON key={`geojson-01`} addData={this.state.bikes} /> 

https://github.com/PaulLeCam/react-leaflet/issues/332#issuecomment-304228071

还需要为标记添加一个唯一的键

   {this.state.haveUsersLocation ? (
<Marker key={`marker-01`} position={position} icon={myIcon}>
<Popup>Your current location</Popup>
</Marker>
) : ""}

关于javascript - 从 API 加载 geoJSON 标记 - React Leaflet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52672149/

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