如何在React Native中的Mapbox地图上绘制导航线?

10

我正在尝试使用npm包中的mapbox-sdk for react-native获取导航方向:

"@mapbox/mapbox-sdk": "^0.11.0"

为了渲染mapbox-sdk返回的方向,我正在使用以下npm包:

"@react-native-mapbox-gl/maps": "^8.1.0-rc.8",

我使用以下代码来检索方向:

import MapboxGL from '@react-native-mapbox-gl/maps'
// Mapbox SDK related package
import MapboxDirectionsFactory from '@mapbox/mapbox-sdk/services/directions'
import { lineString as makeLineString } from '@turf/helpers'
import GeoLocationService from '../../services/geolocation/GeoLocationService';
import GeoLocationCore from '@react-native-community/geolocation'

const accessToken = "ACESS_TOKEN_FROM_MAPBOX_API_DASHBOARD"
const directionsClient = MapboxDirectionsFactory({accessToken})


  constructor(props) {
    super(props);
    this.state = {
        longitude: 0,
        latitude: 0,
        orderLongitude: 0,
        orderLatitude: 0,
        route: null,
    };
  }

async componentDidMount() {
      
      const {route} = this.props

      // Lets say route.params contains the below object:
      // { "longitude": "33.981982", "latitude": "-6.851599"}
      console.log("Params from other screen: ", route.params)

      MapboxGL.setAccessToken(accessToken)
      MapboxGL.setConnected(true);
      MapboxGL.setTelemetryEnabled(true);
      const permission = await MapboxGL.requestAndroidLocationPermissions();

      let latitude, longitude;
      if(Platform.OS == "android") {
          GeoLocationService.requestLocationPermission().then(() => {
            GeoLocationCore.getCurrentPosition(
                info => {
                    const { coords } = info
    
                    latitude = coords.latitude
                    longitude = coords.longitude
                    
                    //this.setState({longitude: coords.longitude, latitude: coords.latitude})
                    this.setState({longitude: -6.873795, latitude: 33.990777, orderLongitude: route.params.longitude, orderLatitude: route.params.latitude})
                    console.log("your lon: ", longitude)
                    console.log("your lat", latitude)
                    this.getDirections([-6.873795, 33.990777], [route.params.longitude, route.params.latitude])

                },
                error => console.log(error),
                {
                    enableHighAccuracy: false,
                    //timeout: 2000,
                    maximumAge: 3600000
                }
            )
        })
      }
  }

  getDirections = async (startLoc, destLoc) => {
      const reqOptions = {
        waypoints: [
          {coordinates: startLoc},
          {coordinates: destLoc},
        ],
        profile: 'driving',
        geometries: 'geojson',
      };
      const res = await directionsClient.getDirections(reqOptions).send()
      //const route = makeLineString(res.body.routes[0].geometry.coordinates)
      const route = makeLineString(res.body.routes[0].geometry.coordinates)
      console.log("Route: ", JSON.stringify(route))
      this.setState({route: route})
      
  }

我使用的代码用于呈现Mapbox SDK获取的道路方向:

  renderRoadDirections = () => {
    const { route } = this.state
    return route ? (
      <MapboxGL.ShapeSource id="routeSource" shape={route.geometry}>
        <MapboxGL.LineLayer id="routeFill" aboveLayerID="customerAnnotation" style={{lineColor: "#ff8109", lineWidth: 3.2, lineCap: MapboxGL.LineJoin.Round, lineOpacity: 1.84}} />
      </MapboxGL.ShapeSource>
    ) : null;
  };

我用来渲染地图和路线的代码:

render() {
   return (
       <View style={{ flex: 1 }}>
         <MapboxGL.MapView
                ref={(c) => this._map = c}
                style={{flex: 1, zIndex: -10}}
                styleURL={MapboxGL.StyleURL.Street}
                zoomLevel={10}
                showUserLocation={true}
                userTrackingMode={1}
                centerCoordinate={[this.state.longitude, this.state.latitude]}
                logoEnabled={true}
                >
                    {this.renderRoadDirections()}
            <MapboxGL.Camera
                zoomLevel={10}
                centerCoordinate={[this.state.longitude, this.state.latitude]}
                animationMode="flyTo"
                animationDuration={1200}
            />
        </MapboxGL.MapView>
       </View>
    )
}

现在当我尝试渲染获取的GeoJson时,道路方向线没有显示在地图上,所以我想也许是我的GeoJson出了问题,但是我从这里测试了一下,看起来没问题:

https://geojsonlint.com/

我测试过的并且看起来没问题的GeoJson:

{"type":"Feature","properties":{},"geometry":{"type":"LineString","coordinates":[[-6.880611,33.9916],[-6.882194,33.990166],[-6.882439,33.99015],[-6.882492,33.990028],[-6.882405,33.98991],[-6.878006,33.990299],[-6.87153,33.990978],[-6.871386,33.990925],[-6.871235,33.991016],[-6.869793,33.991165],[-6.870523,33.990292]]}}

我想要实现的示例:

在此输入图片描述

我的代码有什么问题导致道路方向线没有显示在地图上?


嘿,如果你改成这个怎么样呢?<MapboxGL.ShapeSource id="routeSource" shape={route.geometry.coordinates}> - flaky
@flaky 我认为它期望一个形状对象,但我尝试了并没有起作用。 - 0x01Brain
1个回答

3
找到了导致地图上的 <LineLayer/> 不显示的原因,解决方法是从以下代码中删除属性 aboveLayerID
<MapboxGL.LineLayer id="routeFill" aboveLayerID="customerAnnotation" style={{lineColor: "#ff8109", lineWidth: 3.2, lineCap: MapboxGL.LineJoin.Round, lineOpacity: 1.84}} /> 

那么它就变成了:

<MapboxGL.LineLayer id="routeFill" style={{lineColor: "#ff8109", lineWidth: 3.2, lineCap: MapboxGL.LineJoin.Round, lineOpacity: 1.84}} />

结果:

输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接