传单,并使用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="&copy <a href="http://osm.org/copyright">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>
);
}
}
答案 0 :(得分:1)
由于this.state.haveUsersLocation
始终为false,并且未在组件中的任何位置将其设置为true,因此从未调用Marker组件的原因。如果仅在haveUsersLocation
为true时才渲染Marker组件,则需要将haveUsersLocation
更改为true以渲染Marker,否则请删除条件
您需要在componentWillMount中将haveUsersLocation设置为true,然后标记将成功呈现
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 }));
}
要强制做出反应以重新呈现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>
) : ""}