当我使用折线坐标的第一个和最后一个索引显示在标记上,并且我一直不知道错误在哪里的时候,我一直在键入type错误,我正在尝试使用坐标在React-Leaflet地图上显示标记。我也尝试创建特定的开始和结束坐标,但是我一直都在解决相同的错误。这是我的代码。
import React, { Component } from "react";
import config from "../Main";
import { Map, TileLayer, Polyline, Marker, Popup } from "react-leaflet";
import { withRouter } from "react-router-dom";
class Mapp1 extends Component {
constructor(props) {
super(props);
this.state = {
mapa: [],
center: [52.3197, 21.0152],
cords: [],
start: [],
end:[],
};
}
async componentDidMount() {
let authToken = localStorage.getItem("Token");
try {
const res = await fetch(
`${config.apiUrl.carmapN}${this.props.match.params.id}/`,
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + JSON.parse(authToken)
}
}
);
const mapa = await res.json();
// console.log(mapa);
this.setState({
mapa,
cords: mapa.coordinates,
//start: mapa.coordinates[0],
//end: mapa.coordinates[-1]
});
} catch (e) {
console.log(e);
}
}
render() {
const { mapa } = this.state;
const { cords } = this.state;
if (mapa === null) return <p>Loading ....</p>;
const center = this.state.center;
console.log("StarPint ", this.state.start);
return (
<div className="container" style={{ marginTop: "20px" }}>
<div className="headerr">
<h2 style={{ marginTop: "20px" }} className="font-weight-bolder">
MAPS
</h2>
<div className="row" style={{ marginTop: "30px" }}>
<div className="col-sm-5">
<Map
center={center}
zoom={9}
style={{ width: "520px", height: "480px" }}
>
// This is for startpoint marker and its showing error
<Marker position={cords[0]} color="red">
<Popup>
This is your Starting <br /> point at 8:45
</Popup>
</Marker>
// This is for endpoint marker and its showing error
<Marker position={cords[-1]} color="green">
<Popup>
{mapa.endPlace} <br /> point at {mapa.endTime}
</Popup>
</Marker>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
<Polyline
positions={cords}
color={"red"}
lineJoin={"round"}
lineCap={"round"}
opacity={1}
weight={5}
// dashArray={"9"}
// dashOffset={"3"}
fill={false}
stroke={true}
fillRule={"evenodd"}
onMouseOver={e => e.target.openPopup()}
onMouseOut={e => e.target.closePopup()}
></Polyline>
</Map>
</div>
</div>
</div>
</div>
);
}
}
export default withRouter(Mapp1);
您检查(mapa === null)是否总是返回false,因为mapa初始化为[]而不为null。因此初始渲染采用空数组。修改为if(mapa.length === 0)或if(!mapa.length)。
让我知道这是否解决了问题