我正在尝试使用react-map-gl库在两个点之间画一条线。我在官方文档中找不到示例,所以我尝试从以下使用Mapbox库的代码片段中重现相同的行为
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-122.486052, 37.830348],
zoom: 15
});
map.on('load', function() {
map.addSource('route', {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'LineString',
'coordinates': [
[-122.483696, 37.833818],
[-122.493782, 37.833683]
]
}
}
});
map.addLayer({
'id': 'route',
'type': 'line',
'source': 'route',
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': '#888',
'line-width': 8
}
});
});这是沙箱,我在控制台上看不到任何错误,但没有显示这一行:
https://codesandbox.io/s/draw-line-between-two-point-v0mbc?file=/src/index.js:214-226
发布于 2021-08-17 20:32:26
沙箱中的代码实际上是有效的(对我来说是这样的),但它具有误导性,因为绘制的线离视区很远。
有几件事需要注意,坐标是一个以长的形式给出的数组,这可能不是大多数人会假设的。例如,如果你剪切并粘贴来自旧金山谷歌地图的long,你会得到37.77909036739809,-122.41510269913951。然后,您必须反转它们,并将它们放入:
const dataOne = {
type: "Feature",
properties: {},
geometry: {
type: "LineString",
coordinates: [
[-122.41510269913951, 37.77909036739809],
[39.5423, -77.0564]
]
}
};此外,示例代码中也有一些不完善之处。编辑变量dataOne,而不是其他未使用的地方。
现在你会看到一条线,从旧金山到南极洲中部的某个随机地点,这真的很容易错过。
以防链接出错,完整的代码是:
import React, { Component } from "react";
import { render } from "react-dom";
import ReactMapGL, { Source, Layer } from "react-map-gl";
class App extends Component {
constructor(props) {
super(props);
this.state = {
viewport: {
latitude: 38.63738602787579,
longitude: -121.23576311149986,
zoom: 6.8,
bearing: 0,
pitch: 0,
dragPan: true,
width: 600,
height: 600
}
};
}
render() {
const { viewport } = this.state;
const MAPBOX_TOKEN =
"pk.eyJ1Ijoic21peWFrYXdhIiwiYSI6ImNqcGM0d3U4bTB6dWwzcW04ZHRsbHl0ZWoifQ.X9cvdajtPbs9JDMG-CMDsA";
const dataOne = {
type: "Feature",
properties: {},
geometry: {
type: "LineString",
coordinates: [
[-122.41510269913951, 37.77909036739809],
[39.5423, -77.0564]
]
}
};
return (
<ReactMapGL
{...viewport}
mapboxApiAccessToken={MAPBOX_TOKEN}
onViewportChange={(newViewport) => {
this.setState({ viewport: newViewport });
}}
>
<Source id="polylineLayer" type="geojson" data={dataOne}>
<Layer
id="lineLayer"
type="line"
source="my-data"
layout={{
"line-join": "round",
"line-cap": "round"
}}
paint={{
"line-color": "rgba(3, 170, 238, 0.5)",
"line-width": 5
}}
/>
</Source>
</ReactMapGL>
);
}
}
render(<App />, document.getElementById("root"));https://stackoverflow.com/questions/67842338
复制相似问题