Use Geocoder to return the device address

Asked

Viewed 428 times

1

I want to put in my application a button that when pressed returns the current address of the cell phone.

The latitude and longitude I am managing to return correctly, and to convert this data into an address I reached the library React-Native-geocoder.

My current code is like this:

import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
import Geocoder from 'react-native-geocoder';
 // 0.4.8

class GeolocationExample extends Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      error: null,
    };
  }
  
  refresh = () => {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    );
  };

  render() {
    Geocoder.geocodePosition(this.state.latitude,this.state.longitude)
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
         <Button
          style={{ marginTop: 30 }}
          onPress={() => { this.refresh(); }}
          title="Refresh"
        />
      </View>
    );
  }
}

export default GeolocationExample;

From what I understand in Geocoder.geocodePosition(this.state.latitude,this.state.longitude) would be returning the address, but did not understand how to get this data from there.

The Code in the Snack: https://snack.expo.io/rJhYwaG2Z

1 answer

1


The Geocoder.geocodePosition returns a Promise, so you should capture the address with .then. Ex:

Geocoder.geocodePosition(coords) .then(res => { this.setState({address: res[0].formatedAddress} ); console.log(res[0].formattedAddress)} )

  • But then what? Then he finishes capturing but I still can’t return these

  • You can give a setState of the result because the call to the geocode is asynchronous. Then you can use the state to show the result. formattedAdress is one of the properties of the result. You can query the geocode documentation and capture the desired property.

  • I tried to do following what you said but the address is not returned, if you can give a help I opened a question about the code I wrote: https://answall.com/questions/248717/problemas-ao-retorr-o-endere%C3%A7o-atrav%C3%A9s-da-geolocaliza%C3%A7%C3%A3o

Browser other questions tagged

You are not signed in. Login or sign up in order to post.