React-native - MapViewDirections 未显示

问题描述 投票:0回答:5

我尝试在谷歌地图上使用 MapViewDirections 来提供方向,但它没有显示在地图上。有任何想法吗?

constructor(props) {
    this.state = {
     {.....}
    coordinates: [
      {
      latitude: 37.3317876,
      longitude: -122.0054812,
    },
    {
      latitude: 37.771707,
      longitude: -122.4053769,
<MapView 
  style={styles.map}
  region ={{
    latitude:this.state.latitude,
    longitude:this.state.longitude,
    latitudeDelta: 0.1,
    longitudeDelta: 0.1,
  }}
>
  <MapViewDirections
    origin={this.state.coordinates[0]}
    destination={this.state.coordinates[1]}
    apikey={apikey}
    strokeWidth={3}
    strokeColor="hotpink"
  />
</MapView>
javascript reactjs google-maps react-native
5个回答
0
投票

试试这个,它对我有用。 您必须使用谷歌方向 API 来获取出发地和目的地之间所有可能的位置点。

一旦获得所有点,您可以使用多边形连接这些点,它将在您的起点和目的地之间绘制路线。

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,Dimensions
} from 'react-native';
import MapView from 'react-native-maps';


const mode = 'driving'; // 'walking';
const ASPECT_RATIO = width / height;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const SPACE = 0.01;
const DEFAULT_PADDING = { top: 100, right: 100, bottom: 100, left: 100 };
const { width, height } = Dimensions.get('window');

export default class App extends Component<{}> {

  constructor(props) {
    super(props);  
    this.mapRef = null;    
  }

  state = {    
    MARKERS : null,
    origin :'22.9962,72.5996',
    destination :'23.0134,72.5624',    
    destMarker : '',
    startMarker :'',
    imageloaded:false,
  }

  componentWillMount()
  {
    this.getRoutePoints(this.state.origin,this.state.destination);
  }

  /**
   * This method will give you JSON response with all location points between 2 location
   */
  getRoutePoints(origin,destination) {
    console.log("-----getRoutePoints-----")    
    const url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin}&destination=${destination}&key=YOUR API KEY&mode=${mode}`;
    console.log("URL -- >>" + url);

    fetch(url)
      .then(response => response.json())
      .then(responseJson => {
        if (responseJson.routes.length) {
          var cortemp = this.decode(responseJson.routes[0].overview_polyline.points) // definition below;
          var length = cortemp.length - 1;

          var tempMARKERS = []; 
          tempMARKERS.push(cortemp[0]) ;   //start origin        
          tempMARKERS.push(cortemp[length]); //only destination adding

          console.log("tempMARKERS : " + JSON.stringify(tempMARKERS));

          this.setState({
            coords: cortemp,            
            MARKERS:tempMARKERS,
            destMarker : cortemp[length],
            startMarker:cortemp[0],
          });

        }
      }).catch(e => { console.warn(e) });
  }

  /**
   * This method will transforms something like this geocFltrhVvDsEtA}ApSsVrDaEvAcBSYOS_@... to an array of coordinates
   */

  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]
      }
    })
  }

  /**
   * After loading custome image of marker it will render map and refresh map will image
   */
  forceUpdateMap() {
    console.log("-----forceUpdateMap------")
    this.setState({ imageloaded: true });
  }

  /**
   * This method will fit all markers point into single screen 
   */
  fitAllMarkers() {
    const temMark = this.state.MARKERS;
    console.log( "------fitAllMarkers------")
    this.setState({loading:false});
    if (this.mapRef == null) {
      console.log("map is null")
    } else {
      //option:1  
      console.log("temMark : " + JSON.stringify(temMark));
      this.mapRef.fitToCoordinates(temMark, {
        edgePadding: DEFAULT_PADDING,
        animated: false,
      });              
    }
  }


  render() {

    return (
      <View style={styles.container}>
        {
          (this.state.coords != null) ?
            <MapView
              ref={ref => { this.mapRef = ref; }}
              style={styles.map}
              onLayout={() => this.fitAllMarkers()}>

              {/*used to drae line on rout point of locations*/}
              < MapView.Polyline
                coordinates={this.state.coords}
                strokeWidth={2}
              />

              {/*start point marker*/}
              <MapView.Marker
                key={1}
                coordinate={this.state.startMarker}
              />

              {/*end point marker*/}
              <MapView.Marker
                key={2}
                coordinate={this.state.destMarker}
              >                
              </MapView.Marker>
            </MapView> : null
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});

0
投票
import MapViewDirections from 'react-native-maps-directions';
const origin = { latitude: 23.053150, longitude: 72.517100 };
const destination = { latitude: 23.053177, longitude: 72.517365 };
<MapView>
 <MapViewDirections
                    origin={origin}
                    destination={destination}
                    apikey={GOOGLE_MAPS_APIKEY}
                    strokeWidth={3}
                    strokeColor="rgb(0,139,241)" />
</MapView>

0
投票

您可以使用另一个库,例如:https://www.npmjs.com/package/lazyfox-map-direction

我在上一个项目中使用了这个库,它真的很棒,它可以在react-js和react-native上工作。


0
投票

尝试在 Android 上禁用调试模式。似乎调试模式会以某种方式影响它。


0
投票

假设您的 Google API 没问题,并且您有权使用 Google 的地图视图方向。

给任何人的提示。 React Native Maps 在功能组件中成功渲染,但此包的某些功能可能无法在功能组件中按预期工作。尤其是 MapViewDirections 对我来说不起作用;让它发挥作用是不可能的。我必须在我的驱动程序应用程序中使用基于类的组件,才能继续支持 MapViewDirections。

这个软件包对我来说效果很好: "react-native-maps": "^1.8.3", “react-native-maps-directions”:“^1.9.0”,

© www.soinside.com 2019 - 2024. All rights reserved.