Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

javascript - Directions between Two-point location in mapbox-gl - React Native?

I have two point i get it from database and i want to render a line From start point to end point

what I got is the Straight line in two points without consideration the routes and directions on the maps

So how can i handle it to take a look for routes and Directions on the map?

here's what i got

one

here's what i expect

two

here is my code

import MapboxGL from '@react-native-mapbox-gl/maps';
import React, {Component} from 'react';
import {PermissionsAndroid, StyleSheet, View} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

export default class Mapbox extends Component {
  constructor(props) {
    super(props);
    this.startPoint = [34.4999, 31.5542];
    this.finishedPoint = [34.4979, 31.5512];
    this.state = {
      center: [],
      // initialCoords: undefined,
      initialCoords: [-77.034084, 38.9],
      acceptedPermations: false,

      // Two point state
      route: {
        type: 'FeatureCollection',
        features: [
          {
            type: 'Feature',
            properties: {},
            geometry: {
              type: 'LineString',
              coordinates: [
                this.startPoint, //point A "current" ~ From
                this.finishedPoint, //Point B ~ to
              ],
            },
            style: {
              fill: 'red',
              strokeWidth: '10',
              fillOpacity: 0.6,
            },
            paint: {
              'fill-color': '#088',
              'fill-opacity': 0.8,
            },
          },
        ],
      },
    };
    this.onRegionDidChange = this.onRegionDidChange.bind(this);
  }

  async componentDidMount() {
    const isGranted = await MapboxGL.requestAndroidLocationPermissions();
    this.setState({isGranted: isGranted});
    MapboxGL.setAccessToken(
      '....',
    );
  }

  async onRegionDidChange() {
    const center = await this._map.getCenter();
    this.setState({center}, () =>
      console.log('onRegionDidChange', this.state.center),
    );
  }

  renderCurrentPoint = () => {
    return (
      <>
        <MapboxGL.UserLocation
          renderMode="normal"
          visible={false}
          onUpdate={location => {
            const currentCoords = [
              location.coords.longitude,
              location.coords.latitude,
            ];
            // console.log(location); // current location is here
            this.setState({
              initialCoords: currentCoords,
            });
          }}
        />

        {/* current Provider location */}
        <MapboxGL.PointAnnotation
          selected={true}
          key="key1"
          id="id1"
          coordinate={this.startPoint}>
          <Icon name="ios-pin" size={45} color="#00f" />
          <MapboxGL.Callout title="My" />
        </MapboxGL.PointAnnotation>
        {/* user From DB location */}
        <MapboxGL.PointAnnotation
          selected={true}
          key="key2"
          id="id2"
          coordinate={this.finishedPoint}>
          <Icon name="ios-pin" size={45} color="#0f0" />
          <MapboxGL.Callout title="User" />
        </MapboxGL.PointAnnotation>
        <MapboxGL.ShapeSource id="line1" shape={this.state.route}>
          <MapboxGL.LineLayer
            id="linelayer1"
            style={{
              lineColor: 'red',
              lineWidth: 10,
              lineCap: 'round',
            }}
          />
        </MapboxGL.ShapeSource>
        <MapboxGL.Camera
          zoomLevel={16}
          centerCoordinate={this.state.initialCoords}
          // centerCoordinate={[-5.803457464752711, 35.769940811797404]}
        />
      </>
    );
  };
  render() {
    if (!this.state.isGranted) {
      return null;
    }

    return (
      <View style={styles.page}>
        <MapboxGL.MapView
          styleURL={MapboxGL.StyleURL.Street}
          ref={c => (this._map = c)}
          onRegionDidChange={this.onRegionDidChange}
          zoomEnabled={true}
          style={styles.map}>
          {this.renderCurrentPoint()}
        </MapboxGL.MapView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  page: {
    flex: 1,
    // justifyContent: 'center',
    // alignItems: 'center',
    // backgroundColor: '#F5FCFF',
  },
  container: {
    height: 500,
    width: 500,
    backgroundColor: 'tomato',
  },
  map: {
    flex: 1,
  },
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Google Maps Direction API where you will get encoded polyline and you can decode that encoded Polyline using following function

decode(t, e) {
        for (
            var n,
            o,
            u = 0,
            l = 0,
            r = 0,
            d = [],
            h = 0,
            i = 0,
            a = null,
            c = Math.pow(10, e || 5);
            u < t.length;

        ) {
            (a = null), (h = 0), (i = 0);
            do (a = t.charCodeAt(u++) - 63), (i |= (31 & a) << h), (h += 5);
            while (a >= 32);
            (n = 1 & i ? ~(i >> 1) : i >> 1), (h = i = 0);
            do (a = t.charCodeAt(u++) - 63), (i |= (31 & a) << h), (h += 5);
            while (a >= 32);
            (o = 1 & i ? ~(i >> 1) : i >> 1),
                (l += n),
                (r += o),
                d.push([l / c, r / c]);
        }
        return (d = d.map(function (t) {
            return { latitude: t[0], longitude: t[1] };
        }));
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...