【问题标题】:How to Fetch longitude and Latitude from google API如何从谷歌 API 获取经度和纬度
【发布时间】:2021-05-05 08:34:11
【问题描述】:

我正在尝试从 google Maps Api 获取经度和纬度,所以当我把它放在浏览器上时,连同这样的 API 密钥

https://maps.googleapis.com/maps/api/geocode/json?address=%2727,%20Bello%20Street%20Orile%20Iganmu,%20Lagos%20Nigeria%27&sensor=false&key=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE

我明白了

这很好,现在我想在 React Native 中获得相同的效果。我创建了这个看起来像这样的方法

GetLongitudeFromAddress = (txtaddress) =>{

    let address = txtaddress;
    let lng = this.state.Alongitude;
    let lat = this.state.Alatitude;

    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 =='OK')
        {
            this.setState({longitude:responseJson[0].Alongitude});
            this.setState({latitude:responseJson[0].Alatitude});
        }
    })
}

它没有得到正确的经度,有时,它返回 null,我尝试将它放在 onTextChange() 请我如何让它印上正确的经度和纬度。 ?

【问题讨论】:

    标签: react-native google-maps geolocation fetch


    【解决方案1】:

    将您的状态设置行更正

    this.setState({ longitude : responseJson.results[0].geometry.location.lng });
    this.setState({ latitude : responseJson.results[0].geometry.location.lat });
    

    您的fetch 应该是这样的

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

    【讨论】:

      猜你喜欢
      • 2013-03-03
      • 2011-04-15
      • 1970-01-01
      • 2012-06-28
      • 2016-01-29
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多