React native 使用静止的经度和纬度获取方向

React native 使用静止的经度和纬度获取方向,react-native,use-state,directions,React Native,Use State,Directions,我想从两点(起点和终点)得到方向 我编写了一个简单的函数来获取经度和纬度 看起来像这样 const GetLongitudeFromAddress = (address) =>{ var logLatApi = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false&key=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE';

我想从两点(起点和终点)得到方向 我编写了一个简单的函数来获取经度和纬度

看起来像这样

const GetLongitudeFromAddress = (address) =>{
    var logLatApi = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false&key=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE';
    var header = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };
    fetch(
        logLatApi,{
            method : 'GET',
            headers : header
        }
    ).then((response) => response.json())
    .then((responseJson)=>{
        if(responseJson.status ==='OK')
        {
            this.setState({longitude: responseJson.results[0].geometry.location.lng});
            this.setState({latitude: responseJson.results[0].geometry.location.lat});
        }
    })
}
现在我想把它用在像这样的输入文本中

            <TextInput 
            style={styles.input}
            placeholder="Origin"
            onChangeText={text => GetLongitudeFromAddress(text)}
            />
GetLongitudeFromAddress(文本)}
/>
它似乎不起作用,我得到了这个错误,这是可能的,如下图所示

我如何将其与useState一起使用?我的代码如下所示:

import React , {useState, useEffect} from 'react';
import {StyleSheet, View, Dimensions, TextInput} from 'react-native';
import MapView , { Marker , Polyline } from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

const ShowMap =() =>{

    const GetLongitudeFromAddress = (address) =>{
        var logLatApi = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false&key=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE';
        var header = {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        };
        fetch(
            logLatApi,{
                method : 'GET',
                headers : header
            }
        ).then((response) => response.json())
        .then((responseJson)=>{
            if(responseJson.status ==='OK')
            {
                this.setState({longitude: responseJson.results[0].geometry.location.lng});
                this.setState({latitude: responseJson.results[0].geometry.location.lat});
            }
        })
    }

    const [coordinates] = useState([
        {
          latitude: 6.450430,
          longitude: 3.390460,
        },
        {
          latitude: 6.430980,
          longitude: 3.435880,
        },
      ]);

    return(
        
        <View style={styles.container}>
        <MapView
          style={styles.maps}
          initialRegion={{
            latitude: coordinates[0].latitude,
            longitude: coordinates[0].longitude,
            latitudeDelta: 0.0622,
            longitudeDelta: 0.0121,
          }}>
          <MapViewDirections
            origin={coordinates[0]}
            destination={coordinates[1]}
            apikey="AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE"
            strokeWidth={4}
            strokeColor="#FD0631"
          />
          <Marker coordinate={coordinates[0]} />
          <Marker coordinate={coordinates[1]} />
        </MapView>
        <View style={styles.inputView}>
                <TextInput 
                style={styles.input}
                placeholder="Origin"
                onChangeText={text => GetLongitudeFromAddress(text)}
                />
                <TextInput 
                style={styles.input}
                placeholder="Destination"
                onChangeText={text => GetLongitudeFromAddress(text)}
                />
            </View>
      </View>
    );
}


const styles = StyleSheet.create({
    container: {
      flex: 1,
    },
    maps: {
      width: Dimensions.get('screen').width,
      height: Dimensions.get('screen').height,
    },
    inputView:{
        backgroundColor: 'rgba(0,0,0,0)',
        position: 'absolute', 
        top: 0,
        left: 5,
        right: 5
    },
    input: {
        height: 50,
        padding: 10,
        marginTop: 20,
        marginLeft: 10,
        marginRight: 10,
        fontSize: 18,
        borderWidth: 1,
        borderRadius: 35,
        borderColor: '#EEEEEE',
        backgroundColor: 'white',
    }
  });



export default ShowMap;
import React,{useState,useffect}来自“React”;
从“react native”导入{样式表、视图、维度、文本输入};
从“react native maps”导入MapView,{Marker,Polyline};
从“react native maps directions”导入MapViewDirections;
从“react native google places autocomplete”导入{GooglePlacesSautoComplete};
常量ShowMap=()=>{
常量GetLongitudeFromAddress=(地址)=>{
变量logLatApi=https://maps.googleapis.com/maps/api/geocode/json?address=“+地址+”&传感器=false&密钥=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9 YNE”;
变量头={
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”
};
取回(
洛格拉塔皮{
方法:“GET”,
标题:标题
}
).then((response)=>response.json())
.然后((responseJson)=>{
如果(responseJson.status==='OK')
{
this.setState({经度:responseJson.results[0].geometry.location.lng});
this.setState({纬度:responseJson.results[0].geometry.location.lat});
}
})
}
常数[坐标]=使用状态([
{
纬度:6.450430,
经度:3.390460,
},
{
纬度:6.430980,
经度:3.435880,
},
]);
返回(
GetLongitudeFromAddress(文本)}
/>
GetLongitudeFromAddress(文本)}
/>
);
}
const styles=StyleSheet.create({
容器:{
弹性:1,
},
地图:{
宽度:尺寸。获取('screen')。宽度,
高度:尺寸。获取(“屏幕”)。高度,
},
输入视图:{
背景颜色:“rgba(0,0,0,0)”,
位置:'绝对',
排名:0,
左:5,,
右:5
},
输入:{
身高:50,
填充:10,
玛金托普:20,
边缘左:10,
marginRight:10,
尺码:18,
边框宽度:1,
边界半径:35,
边框颜色:“#EEEEEE”,
背景颜色:“白色”,
}
});
导出默认的ShowMap;

我该怎么办?如何使用此
GetLongitudeFromAddress
从两个字段获取经度和纬度。请协助

您需要一个按钮,当按下该按钮时,该按钮将调用函数
GetLongitudeFromAddress
。每次更改输入文本值都要调用此函数,因为每次调用该函数时,它都会调用地理编码请求。 我成功地修改了您的代码,从输入文本中获取地址,然后使用函数将其转换,然后使用转换后的坐标作为MapViewDirections的输入。下面是一段代码和一段代码片段,其中包含内联注释:

import React, { useState, useEffect } from 'react';
import { StyleSheet, View, Dimensions, TextInput, Button } from 'react-native';
import MapView, { Marker, Polyline } from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
const { width, height } = Dimensions.get('window');
const ShowMap = () => {

//initial maps coordinate
  const [initialCenter] = useState({
    latitude: 6.45043,
    longitude: 3.39046,
  });

//state variables for the value of the textbox
  const [originInput, setOInput] = useState(null);
  const [destInput, setDInput] = useState(null);

//state variables to handle the coordinates after getting it from GetLongitudeFromAddress function
  const [originReq, setOReq] = useState(null);
  const [destReq, setDReq] = useState(null);

//state variable that will be one of the condition to trigger MapViewDirections once button is pressed
  const [isBtnPressed, setBtn] = useState(null);

  //state variable that will be a condition to show the origin and destination marker once the route was started
  const [routeStarted, setRouteStarted] = useState(null);

//function that will convert the address from your inpput textbox to a coordinate(geocoding)
//coord variable will be the variable that will determine if you are converting the origin or the destination coordinates
  const GetLongitudeFromAddress = (address, coord) => {
    var logLatApi =
      'https://maps.googleapis.com/maps/api/geocode/json?address=' +
      address +
      '&sensor=false&key=YOUR_KEY';
    var header = {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    };
    fetch(logLatApi, {
      method: 'GET',
      headers: header,
    })
      .then((response) => response.json())
      .then((responseJson) => {
        if (responseJson.status === 'OK') {
          //check if coord value is 'origin' or destination'
          if (coord == 'origin' || coord == 'destination') {
            if (coord == 'origin') {
              //if origin, it will change the originReq state value to the result
              setOReq({
                latitude: responseJson.results[0].geometry.location.lat,
                longitude: responseJson.results[0].geometry.location.lng,
              });
            } else {
              //if destination, it will change the destReq state value to the result
              setDReq({
                latitude: responseJson.results[0].geometry.location.lat,
                longitude: responseJson.results[0].geometry.location.lng,
              });
            }
          }
        }
      });
 
  };

//function called when the button is pressed
  const processAddress = () => {
 //it will pass the current value of your input state and hardcoding origin or destination to mark if the address being converted to coordinates is either one of them
    GetLongitudeFromAddress(originInput, 'origin');
    GetLongitudeFromAddress(destInput, 'destination');
    //change isBtnPressed state variable value
    setBtn('Y');
  };

//function called when the route is ready, it will also fit the polyline to the current view
  const routeReady = (result) => {
    console.log(`Distance: ${result.distance} km`);
    console.log(`Duration: ${result.duration} min.`);
    console.log(isBtnPressed);
    this.mapView.fitToCoordinates(result.coordinates, {
      edgePadding: {
        right: width / 20,
        bottom: height / 20,
        left: width / 20,
        top: height / 20,
      },
    });
  };



  return (
    <View style={styles.container}>
      <MapView
        style={styles.maps}
        ref={(c) => (this.mapView = c)}
        initialRegion={{
          latitude: initialCenter.latitude,
          longitude: initialCenter.longitude,
          latitudeDelta: 0.0622,
          longitudeDelta: 0.0121,
        }}>
        {isBtnPressed !== null && originReq !== null && destReq !== null && (
          <MapViewDirections
            origin={originReq}
            destination={destReq}
            apikey="YOUR_KEY"
            strokeWidth={4}
            strokeColor="#FD0631"
            onStart={() => {
              setRouteStarted('Y');
            }}
            onReady={(result) => {
              routeReady(result);
            }}
            onError={() => {
              setRouteStarted(null);
            }}
          />
        )}
        {routeStarted !== null && originReq != null && (
          <Marker coordinate={originReq} />
        )}
        {routeStarted !== null && destReq != null && (
          <Marker coordinate={destReq} />
        )}
      </MapView>
      <View style={styles.inputView}>
        <TextInput
          style={styles.input}
          placeholder="Origin"
          onChangeText={(text) => setOInput(text)}
        />
        <TextInput
          style={styles.input}
          placeholder="Destination"
          onChangeText={(text) => setDInput(text)}
        />
        <Button title="Press me" color="#f194ff" onPress={processAddress} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  maps: {
    width: Dimensions.get('screen').width,
    height: Dimensions.get('screen').height,
  },
  inputView: {
    backgroundColor: 'rgba(0,0,0,0)',
    position: 'absolute',
    top: 0,
    left: 5,
    right: 5,
  },
  input: {
    height: 50,
    padding: 10,
    marginTop: 20,
    marginLeft: 10,
    marginRight: 10,
    fontSize: 18,
    borderWidth: 1,
    borderRadius: 35,
    borderColor: '#EEEEEE',
    backgroundColor: 'white',
  },
});

export default ShowMap;

import React,{useState,useffect}来自“React”;
从“react native”导入{样式表、视图、维度、文本输入、按钮};
从“react native maps”导入MapView,{Marker,Polyline};
从“react native maps directions”导入MapViewDirections;
从“react native google places autocomplete”导入{GooglePlacesSautoComplete};
const{width,height}=Dimensions.get('window');
常量ShowMap=()=>{
//初始地图坐标
常量[initialCenter]=useState({
纬度:6.45043,
经度:3.39046,
});
//文本框值的状态变量
const[originInput,setOInput]=useState(null);
const[destInput,setDInput]=useState(null);
//从GetLongitudeFromAddress函数获取坐标后处理坐标的状态变量
const[originReq,setOReq]=useState(null);
const[destReq,setDReq]=useState(null);
//状态变量,该变量是按下按钮后触发MapViewDirections的条件之一
const[isbtnppressed,setBtn]=useState(null);
//状态变量,该变量将作为在路线启动后显示起点和终点标记的条件
常量[routeStarted,setRouteStarted]=useState(null);
//将输入文本框中的地址转换为坐标的函数(地理编码)
//coord变量将是确定是转换原点坐标还是目标坐标的变量
常量GetLongitudeFromAddress=(地址,坐标)=>{
变量logLatApi=
'https://maps.googleapis.com/maps/api/geocode/json?address=' +
地址+
“&sensor=false&key=YOUR_key”;
变量头={
接受:'application/json',
“内容类型”:“应用程序/json”,
};
获取(logLatApi{
方法:“GET”,
标题:标题,
})
.then((response)=>response.json())
.然后((responseJson)=>{
如果(responseJson.status=='OK'){
//检查坐标值是否为“起点”或“终点”
如果(坐标='origin'| |坐标=='destination'){
如果(坐标==“原点”){
//如果是origin,它会将originReq状态值更改为结果
塞托雷克({
纬度:responseJson.results[0].geometry.location.lat,
经度:responseJson.results[0].geometry.location.lng,
});
}否则{
//如果选择destination,则会将destReq状态值更改为结果
塞德雷克({
纬度:responseJson.results[0].geometry.location.lat,