Search code examples
react-nativegoogle-mapsgeolocationfetch

How to Fetch longitude and Latitude from google API


I am trying to get Longitude and Latitude from google Maps Api so when i put it on browser, together with the API Key like this

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

i get this

44.png

This is good, Now i want to get the same in React native. I have created this Method Which looks like this

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=YOUR_API_KEY';

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

It does not get the Correct Longitude, sometimes, it returns null, i try to put it onTextChange() Please how do i get it to imprint the correct longitude and Latitude. ?


Solution

  • Correct your state setting line to this

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

    Your fetch should look like this

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