Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 反应本机地图数据访问_Javascript_Reactjs_React Native - Fatal编程技术网

Javascript 反应本机地图数据访问

Javascript 反应本机地图数据访问,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我有一个关于react nativeMapViewDirection与世博会的问题 我从MapViewDirection中的onReady函数收到了结果 我想向用户显示距离和持续时间字段 onReady={result => { console.log(result) }}; 我想声明我正在学习并且正在使用其他人的代码进行练习。以下是完整代码: import React, { Component } from 'react'; import { Dime

我有一个关于react native
MapViewDirection
与世博会的问题

我从
MapViewDirection
中的
onReady
函数收到了结果

我想向用户显示距离和持续时间字段

 onReady={result => {

              console.log(result)
}}; 
我想声明我正在学习并且正在使用其他人的代码进行练习。以下是完整代码:

import React, { Component } from 'react';
import { Dimensions, StyleSheet } from 'react-native';
import MapView from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';

const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 40.3788;
const LONGITUDE = -105.5143;
const LATITUDE_DELTA = 0.0192;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;

const GOOGLE_MAPS_APIKEY = 'AIzaSyAkwAlX2w0S3ba6OxBqr13JGDuYIi5GRZ8';

class Example extends Component {

  constructor(props) {
    super(props);


    this.state = {
      coordinates: [
        {
          latitude:40.3788,
          longitude:-105.5143,
        },

      ],
    };

    this.mapView = null;
  }

  onMapPress = (e) => {
    this.setState({
      coordinates: [
        ...this.state.coordinates,
        e.nativeEvent.coordinate,
      ],
    });
  }

  render() {
    return (
      <MapView
        initialRegion={{
          latitude: LATITUDE,
          longitude: LONGITUDE,
          latitudeDelta: LATITUDE_DELTA,
          longitudeDelta: LONGITUDE_DELTA,
        }}
        style={StyleSheet.absoluteFill}
        ref={c => this.mapView = c}
        onPress={this.onMapPress}
      >
        {this.state.coordinates.map((coordinate, index) =>
          <MapView.Marker key={`coordinate_${index}`} coordinate={coordinate} />
        )}
        {(this.state.coordinates.length >= 2) && (
          <MapViewDirections
            origin={this.state.coordinates[0]}
            waypoints={ (this.state.coordinates.length > 2) ? this.state.coordinates.slice(1, -1): null}
            destination={this.state.coordinates[this.state.coordinates.length-1]}
            apikey={GOOGLE_MAPS_APIKEY}
            strokeWidth={3}
            strokeColor="hotpink"
            optimizeWaypoints={true}
            onStart={(params) => {
              console.log(`Started routing between "${params.origin}" and "${params.destination}"`);
            }}
            onReady={result => {

              console.log(result);

              this.mapView.fitToCoordinates(result.coordinates, {
                edgePadding: {
                  right: (width / 20),
                  bottom: (height / 20),
                  left: (width / 20),
                  top: (height / 20),
                }
              });
            }}
            onError={(errorMessage) => {
              // console.log('GOT AN ERROR');
            }}
          />
        )}
      </MapView>
    );
  }
}

export default Example; 
import React,{Component}来自'React';
从“react native”导入{Dimensions,StyleSheet};
从“react native maps”导入MapView;
从“react native maps directions”导入MapViewDirections;
const{width,height}=Dimensions.get('window');
常量纵横比=宽度/高度;
常数纬度=40.3788;
常数经度=-105.5143;
常数纬度_δ=0.0192;
常数经度_δ=纬度_δ*纵横比;
const GOOGLE_MAPS_APIKEY='AIzaSyAkwAlX2w0S3ba6OxBqr13JGDuYIi5GRZ8';
类示例扩展组件{
建造师(道具){
超级(道具);
此.state={
坐标:[
{
纬度:40.3788,
经度:-105.5143,
},
],
};
this.mapView=null;
}
onappress=(e)=>{
这是我的国家({
坐标:[
…这个州坐标,
e、 nativeEvent.coordinate,
],
});
}
render(){
返回(
this.mapView=c}
onPress={this.onMapPress}
>
{this.state.coordinates.map((坐标,索引)=>
)}
{(this.state.coordinates.length>=2)&&(
2) ?this.state.coordinates.slice(1,-1):null}
destination={this.state.coordinates[this.state.coordinates.length-1]}
apikey={GOOGLE\u MAPS\u apikey}
冲程宽度={3}
strokeColor=“热粉色”
优化路径点={true}
onStart={(参数)=>{
log(`在“${params.origin}”和“${params.destination}”之间开始路由';
}}
onReady={result=>{
控制台日志(结果);
此.mapView.fitToCoordinates(结果.coordinates{
边缘添加:{
右:(宽度/20),
底部:(高度/20),
左:(宽度/20),
顶部:(高度/20),
}
});
}}
OneError={(errorMessage)=>{
//log('GOT-ERROR');
}}
/>
)}
);
}
}
导出默认示例;


使用下面给定的代码,您可以使用纬度和经度获得两个位置之间的距离。我们在这里使用谷歌距离矩阵api来获取距离

  getDistanceOneToOne(lat1, lng1, lat2, lng2) 
  {
    const Location1Str = lat1 + "," + lng1;
    const Location2Str = lat2 + "," + lng2;
    let GOOGLE_API_KEY = "API_KEY"
    let ApiURL = "https://maps.googleapis.com/maps/api/distancematrix/json?"

    let params = `origins=${Location1Str}&destinations=${Location2Str}&key=${GOOGLE_API_KEY}`; // you need to get a key
    let finalApiURL = `${ApiURL}${encodeURI(params)}`;

    this.getDistance(finalApiURL).then((getDistance) => {
      console.log('Distance charges',getDistance);

      if (getDistance.status == "OK") 
      {

          let value = getDistance.rows[0].elements[0].distance.text; //Distance 
          let time = getDistance.rows[0].elements[0].duration.value; //time
      }    
  });
  }

    getDistance = (url) => {
        return this.getDistanceCall(url)
    }

    getDistanceCall = (url) => {

        return fetch(url, {
            method: 'GET',
        })
            .then((response) => { return response.json(); })
            .catch((error) => {
                return error;
            });
    }

亲爱的Aashish,请说出你的确切愿望是什么?我不明白你想要什么!因此,我希望能够获得从地图上所有选定的标记移动所需的距离和时间。您能在我上面的屏幕代码中进一步解释一下在哪里使用这个吗。请我无法集成。@AashishSapkota首先删除您问题中提到的api密钥。在stackoverflow上发布问题时,只需使用常量(API_键)。这样,除了您之外,没有人可以使用您的api密钥。@AashishSapkota首先获取两个位置的纬度和经度。然后用这两个纬度和经度调用上面提到的getDistanceOnetoOne函数。您将获得这两个位置之间的距离和时间估计。