在地图框中获取两点之间的方向?



我最近在 react native 上使用 mapbox gl 而不是 Google 地图, 我正在尝试添加一个在地图上显示从 A 点到 B 点的方向的功能。

或者在我的 React Native 应用程序中使用 Mapbox 方向 API

这是我尝试过的代码,但是在屏幕安装后,该应用程序成功崩溃:D

import MapboxGL from '@react-native-mapbox-gl/maps';
import React from 'react';
import {View} from 'react-native';
MapboxGL.setAccessToken(
'....',
);
class TwoPoints extends React.Component {
constructor(props) {
super(props);
this.featureCollection = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
id: '9d10456e-bdda-4aa9-9269-04c1667d4552',
properties: {
icon: 'example',
},
geometry: {
type: 'Point',
coordinates: [-73.989, 40.733],
},
},
{
type: 'Feature',
id: '9d10456e-bdda-4aa9-9269-04c1667d4552',
properties: {
icon: 'airport-15',
},
geometry: {
type: 'Point',
coordinates: [-74, 40.733],
},
},
{
type: 'Feature',
id: '9d10456e-bdda-4aa9-9269-04c1667d4552',
properties: {
icon: 'pin',
},
geometry: {
type: 'Point',
coordinates: [-74, 40.733],
},
},
],
};
}
render() {
return (
<View style={{flex: 1}}>
<MapboxGL.MapView
ref={c => (this._map = c)}
zoomEnabled={true}
style={{flex: 1}}>
<MapboxGL.ShapeSource shape={this.featureCollection}>
<MapboxGL.SymbolLayer
style={{iconColor: 'red'}}
minZoomLevel={25}
/>
</MapboxGL.ShapeSource>
</MapboxGL.MapView>
</View>
);
}
}
export default TwoPoints;

您可以从mapbox-gl-directioning导入方向,如下所示:

import React, { useState, useRef, useCallback } from 'react'
import MapGL from 'react-map-gl'
import Directions from 'react-map-gl-directions'
// Ways to set Mapbox token: https://uber.github.io/react-map-gl/#/Documentation/getting-started/about-mapbox-tokens
const MAPBOX_TOKEN =
'pk.eyJ1IjoiaGVucmlxdWVub2JyZSIsImEiOiJja3dkZ3c2YmoydzdhMzBvMGRtdWVnd3J2In0.xdCkUviv0yGpX-t8L7ZKQ'
const MapBox = () => {
const [viewport, setViewport] = useState({
latitude: -16.6906,
longitude: -43.8054,
zoom: 8
})
const mapRef = useRef()
const handleViewportChange = useCallback(
(newViewport) => setViewport(newViewport),
[]
)
const handleGeocoderViewportChange = useCallback((newViewport) => {
const geocoderDefaultOverrides = { transitionDuration: 1000 }
return handleViewportChange({
...newViewport,
...geocoderDefaultOverrides
})
}, [])
return (
<div style={{ height: '100%' }}>
<MapGL
ref={mapRef}
{...viewport}
width="100%"
height="100%"
mapStyle="mapbox://styles/mapbox/streets-v11"
onViewportChange={handleViewportChange}
mapboxApiAccessToken={MAPBOX_TOKEN}
>
<Directions
mapRef={mapRef}
mapboxApiAccessToken={MAPBOX_TOKEN}
position="top-left"
unit="metric"
language="pt-BR"
/>
</MapGL>
</div>
)
}
export default MapBox

最新更新