从 API 加载 geoJSON 标记 - React 传单



Leaflet 并使用 GeoJSON。一旦数据存储在状态上,我正在尝试从获取的 GeoJSON API 中获取标记以在地图上呈现。我尝试使用标记组件来显示来自 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>
);
}
}

标记组件永远不会被调用的原因this.state.haveUsersLocation因为它总是 false,并且您没有在组件中的任何位置将其设置为 true。如果只想在haveUsersLocation为 true 时渲染标记组件,则需要将haveUsersLocation更改为 true 以渲染标记,否则删除条件

您需要在组件中使haveUsersLocation变为trueWillMount和标记将成功渲染

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 数据,您需要将一些 data-uniq 键传递给组件。查看下面的 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>
) :  ""}

最新更新