当我使用多线坐标的第一个和最后一个索引在标记上显示时,我试图使用坐标在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);发布于 2019-12-21 03:27:31
检查(mapa === null)是否总是返回false,因为mapa被初始化为[] not null。所以初始渲染是采用空数组。将其修改为if (mapa.length === 0)或if(!mapa.length)。
让我知道这是否解决了问题。如果是这样的话,我建议您参考ecma文档或任何在线可信资源(如mdn )中的双重相等强制。
https://stackoverflow.com/questions/59425062
复制相似问题