首页 > 解决方案 > 如何在 react-native-maps 上的每个折线段上绘制箭头

问题描述

嗨,我想像这张图片一样在每条折线上画一个箭头: 在此处输入图像描述 阅读这篇文章: 如何在 Google Maps V3 上的每个折线段上画一个箭头

这是回答我的问题,但这篇文章是针对 javascript 的

但我使用它,这是我的代码:

<View style={{ height: hp('50%'), width: wp('100%') }}>
            <MapView
              provider={PROVIDER_GOOGLE}
              onLayout={this.onMapLayout}
              style={styles.containerMap}
              initialRegion={{
                latitude: this.props.data ? this.props.data[0].YPOINT : '',
                longitude: this.props.data ? this.props.data[0].XPOINT : '',
                latitudeDelta: 0.0922,
                longitudeDelta: 0.0421,
              }} >
              {this.state.isMapReady && <Polyline
                strokeWidth={2}
                strokeColor="red"
                geodesic={true}
                icons={
                  icon = { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW },
                  offset = '100%'
                }
                coordinates={[...this.props.data.map((value, index) => {
                  return { latitude: value.YPOINT, longitude: value.XPOINT }
                })]}
              />
              }
            </MapView>
          </View>

但运行时出现错误“未定义谷歌”。

更新 这是功能:

 import React, { Component } from 'react'
import { Text, View, StyleSheet, ScrollView, AsyncStorage, ActivityIndicator, Alert, FlatList } from 'react-native'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
//import arrowIcon from '../../../assets/images/icon/Arrow/090.ico'
import SegmentedControlTab from "react-native-segmented-control-tab";
import { Dropdown } from 'react-native-material-dropdown';
import { getTraceOfHardware } from '../../../Store/actions';
import { connect } from 'react-redux';
import MapView, { Marker, PROVIDER_GOOGLE, Polyline } from 'react-native-maps';
import Icon from 'react-native-vector-icons/Entypo';

var moment = require('jalali-moment');

let dataDay = [{
  value: 'امروز',
}, {
  value: 'یک روز پیش',
}, {
  value: 'دو روز پیش',
}, {
  value: 'سه روز پیش',
}, {
  value: 'چهار روز پیش',
}, {
  value: 'پنج روز پیش',
}, {
  value: 'شش روز پیش',
}, {
  value: 'هفت روز پیش',
},];
const airplin = <Icon name="aircraft" size={30}/>

class mainRoutsReport extends Component {
  constructor () {
    super()
    this.state = {
      selectedIndex: 0,
      selectedIndices: [0],
      customStyleIndex: 0,
      daySelected: '',
      isMapReady: false,
      tableHead: ['Head', 'Head2', 'Head3', 'Head4', 'Head5', 'Head6', 'Head7', 'Head8', 'Head9'],
      widthArr: [40, 60, 80, 100, 120, 140, 160, 180, 200],
      data: [],
      latlon: []
      //   tableData: [
      //     ['1', '2', '3', '4', '5', '6'],
      //     ['1', '2', '3', '4', '5', '6']
      // ]

    }
  }
  //GET UDID
  _retrieveUDID = async () => {
    try {
      return await AsyncStorage.getItem('@IranTracking:UDID', (error, result) => { return result })

    } catch (error) {
      // Error retrieving data
      console.log(error)
    }
  };
  //GET  TOKEN
  _retrieveToken = async () => {
    try {
      return await AsyncStorage.getItem('@IranTracking:Token', (error, result) => { return result })
    } catch (error) {
      // Error retrieving data
      console.log(error)
    }
  };
  //This method creat XML to send action.js to get List of Hardware from SOAP
  async _makXML(value, index) {
    udid = await this._retrieveUDID()
    token = await this._retrieveToken()
    var yesterday = moment().locale('fa').subtract(index + 0, 'day').format('YYYY-MM-DD')
    // console.log(yesterday)
    let xml = `<?xml version="1.0" encoding="utf-8"?>\
        <x:Envelope xmlns:x="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tra="http://Trackinguri.org/">\
        <x:Header>\
        <tra:SOAPHeaderContent>\
        <tra:UserName></tra:UserName>\
        <tra:Password></tra:Password>\
        <tra:Token>${token}</tra:Token>\
        <tra:UID>${udid}</tra:UID>\
        </tra:SOAPHeaderContent>\
        </x:Header>\
        <x:Body>\
         <tra:GetTraceByHardwareID>\
            <tra:HardwareID>${this.props.navigation.state.params.HID}</tra:HardwareID>\
            <tra:FromDate>${yesterday} 00:00:00</tra:FromDate>\
            <tra:ToDate>${yesterday} 23:59:59</tra:ToDate>\
            <tra:HijriDates>true</tra:HijriDates>\
            <tra:Time_Zone>Tehran</tra:Time_Zone>\
            <tra:Lang>fa</tra:Lang>\
        </tra:GetTraceByHardwareID>\
          </x:Body>\
        </x:Envelope>`;

    console.log(" xml to get  Tarce reports " + xml)
    this.props.getTraceOfHardware(xml)
  }
  componentWillMount() {
    this._makXML()
    this.props.getTraceOfHardware()
  }
  componentDidMount() {


  }
  //this function use for day 
  _HandelDay(value, index) {

    // var yesterday =  moment().locale('fa').subtract(index,'day').format('YYYY-MM-DD')
    //console.log('index of drop down is : ' + value + ' \nindex is : '+ index + '\n and date is : ' + yesterday)
    //Alert.alert(yesterday)
  }
  handleMultipleIndexSelect = (index: number) => {
    const { selectedIndices } = this.state

    if (selectedIndices.includes(index)) {
      this.setState(prevState => ({
        ...prevState,
        selectedIndices: selectedIndices.filter((i) => i !== index),
      }))
    } else {
      this.setState(prevState => ({
        ...prevState,
        selectedIndices: [
          ...selectedIndices,
          index,
        ],
      }))
    }
  }

  handleCustomIndexSelect = (index: number) => {
    this.setState(prevState => ({ ...prevState, customStyleIndex: index }))
  }
  onMapLayout = () => {
    this.setState({ isMapReady: true });
  }
  _renderItem = ({ item, index }) => (
    // console.log(item)
    <View style={{ flex: 1, height: hp('15%'), flexDirection: 'row', backgroundColor: index % 2 ? '#f3f3f3' : '#dedede', marginHorizontal: 5, alignItems: 'center' }} >
      <View style={{ width: wp('15%'), alignItems: 'center', }}>
        <Text style={{ marginLeft: 4, fontFamily: 'IRANSansMobile', }}>{item.TRUCKSTATE}</Text>
      </View>
      <View style={{ width: wp('12%'), alignItems: 'center' }}>
        <Text style={{ marginLeft: 4, fontFamily: 'IRANSansMobile', }}>{item.SPEED}</Text>
      </View>
      <View style={{ width: wp('50%'), alignItems: 'center' }}>
        <Text style={{ marginLeft: 4, fontFamily: 'IRANSansMobile', }}>{item.POSDESCRIPTION}</Text>
      </View>
      <View style={{ width: wp('10%'), alignItems: 'center' }}>
        <Text style={{ marginLeft: 4, fontFamily: 'IRANSansMobile', }}>{item.SENTDATE}</Text>
      </View>
      <View style={{ width: wp('10%'), alignItems: 'center' }}>
        <Text style={{ marginLeft: 4, fontFamily: 'IRANSansMobile', }}>{index + 1}</Text>
      </View>
    </View>
  );


  _renderHeadr = () => (
    <View style={{ flexDirection: 'row', alignContent: 'space-between', alignItems: 'center', backgroundColor: '#5e9dcb' }}>
      <View style={{ borderWidth: 0.5, width: wp('15%'), alignItems: 'center', borderTopLeftRadius: 5 }}>
        <Text style={{ fontSize: 15, fontFamily: 'IRANSansMobile', }}>وضعیت</Text>
      </View>
      <View style={{ borderWidth: 0.5, width: wp('12%'), alignItems: 'center' }}>
        <Text style={{ fontSize: 15, fontFamily: 'IRANSansMobile', }}>سرعت</Text>
      </View>
      <View style={{ borderWidth: 0.5, width: wp('50%'), alignItems: 'center' }}>
        <Text style={{ fontSize: 15, fontFamily: 'IRANSansMobile', }}>موقعیت</Text>
      </View>
      <View style={{ borderWidth: 0.5, width: wp('10%'), alignItems: 'center' }}>
        <Text style={{ fontSize: 15, fontFamily: 'IRANSansMobile', }}>زمان</Text>
      </View>
      <View style={{ borderWidth: 0.5, width: wp('10%'), alignItems: 'center', borderTopRightRadius: 5 }}>
        <Text style={{ fontSize: 15, fontFamily: 'IRANSansMobile', }}>ردیف</Text>
      </View>
    </View>
  );
  render() {
    const { customStyleIndex } = this.state


    //console.log(this.props.navigation.state.params.HID)
    //console.log(this.props.data)

    return (
      <View style={{ width: wp('100%'), height: hp('100%') }}>
        <Dropdown animationDuration={100}
          dropdownMargins={{ min: 0, max: 0 }}
          dropdownOffset={{ top: 0, left: 0 }}
          style={{ textAlign: 'center' }}
          containerStyle={{ textAlign: 'right', backgroundColor: '#fcee97', borderWidth: 0.5, borderRadius: 13, margin: 8 }}
          absoluteRTLLayout={true}
          data={dataDay}
          dropdownPosition={-5}
          onChangeText={(value, index) => this._makXML(value, index)}
          value={dataDay[0].value} />
        <SegmentedControlTab
          values={['نمایش متنی', 'نمایش نقشه']}
          selectedIndex={customStyleIndex}
          onTabPress={this.handleCustomIndexSelect}
          borderRadius={0}
          tabsContainerStyle={{ height: 50, backgroundColor: '#F2F2F2' }}
          tabStyle={{ backgroundColor: '#ffffff', borderWidth: 0, borderColor: 'transparent' }}
          activeTabStyle={{ backgroundColor: '#5e9dcb', marginTop: 2 }}
          tabTextStyle={{ color: '#000000', fontWeight: 'bold', fontFamily: 'IRANSansMobile' }}
          activeTabTextStyle={{ color: '#ffffff', fontFamily: 'IRANSansMobile' }}
        />

        {//table

          customStyleIndex === 0
          &&
          <View style={{ paddingBottom: wp('20%') }}>
            {this.props.isLoading ? <ActivityIndicator /> : <FlatList
              ListHeaderComponent={this._renderHeadr}
              stickyHeaderIndices={[0]}
              data={this.props.data}
              renderItem={this._renderItem}//({item})=>(this._renderItem)
              keyExtractor={(item, index) => index.toString()}
            />}
          </View>
        }
        {//Map
          customStyleIndex === 1
          &&

          <View style={{ height: hp('50%'), width: wp('100%') }}>
            <MapView
              provider={PROVIDER_GOOGLE}
              onLayout={this.onMapLayout}
              style={styles.containerMap}
              initialRegion={{
                latitude: this.props.data ? this.props.data[0].YPOINT : '',
                longitude: this.props.data ? this.props.data[0].XPOINT : '',
                latitudeDelta: 0.0922,
                longitudeDelta: 0.0421,
              }} >
              {this.state.isMapReady && 
              <Polyline
                strokeWidth={2}
                strokeColor="red"
                geodesic={true}

                icons={
                  icon = {airplin },
                  offset = '100%'
                }
                coordinates={[...this.props.data.map((value, index) => {
                  return { latitude: value.YPOINT, longitude: value.XPOINT }
                })]}
              />


              }
            </MapView>
          </View>
        }

      </View>
    )
  }
}

function mapStateToProps(state) {
  console.log(state)
  return {
    data: state.GetTraceHardware.data,
    isLoading: state.GetTraceHardware.isLoading,
    error: state.GetTraceHardware.error
  }
}
function mapDispatchToProps(dispatch) {
  return {
    getTraceOfHardware: (data) => dispatch(getTraceOfHardware(data))
  }

}
export default connect(mapStateToProps, mapDispatchToProps)(mainRoutsReport);

标签: react-nativereact-native-maps

解决方案


推荐阅读