Magas
Magas

Reputation: 514

Problems returning address through geolocation

I'm trying to use the react-native-geocoder library to return the address through the latitude and longitude of the device.

Through response to another question and some more research, I came up with this code:

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

Geocoder.apiKey = '__API__KEY__';

export default class testeGeocoder extends Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      place: 'Localizando endereço...',
      error: null,
    };
  }

  componentDidMount() {
    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 },
    );

    Geocoder.geocodePosition(this.state.latitude,this.state.longitude)
      .then(res => {
          this.setState({
              place: res[0].formatedAddress
          });
          console.log(res[0].formattedAddress)
      });
  }

  render() {
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        <Text>{this.state.place.toString()}</Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
    );
  }
}

AppRegistry.registerComponent('testeGeocoder', () => testeGeocoder);

But this returns me to the correct latitude and longitude, but stays locating address ... and never returns.

Edit:

With the help of bennygenel and Michael Cheng I managed to eliminate the warning and got to this code:

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

Geocoder.apiKey = '__API__KEY__';

export default class teste47 extends Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      place: 'Localizando endereço...',
      error: null,
    };
  }

  componentDidMount() {
   navigator.geolocation.getCurrentPosition(
    position => {
      this.setState(
        {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        },
        () => {
          Geocoder.geocodePosition({
            lat: position.coords.latitude,
            lng: position.coords.longitude
          }).then(res => {
            this.setState({
              place: res[0].formattedAddress,
            });
          });
        }
      );
    },
    error => this.setState({ error: error.message }),
    { 
      enableHighAccuracy: true, timeout: 20000 
    });
  }

  render() {
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        <Text>{this.state.place.toString()}</Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
    );
  }
}

AppRegistry.registerComponent('teste47', () => teste47);

But when I execute this it is returning the error:

enter image description here

enter image description here

Upvotes: 1

Views: 1193

Answers (1)

bennygenel
bennygenel

Reputation: 24660

Geocoder.geocodePosition takes an object contains lat and long. You are trying to send 2 separate parameters.

If you change

Geocoder.geocodePosition(this.state.latitude, this.state.longitude)
  .then(res = > {
    this.setState({
      place: res[0].formattedAddress
    });
    console.log(res[0].formattedAddress)
  });

to this

Geocoder.geocodePosition({ lat: this.state.latitude, long: this.state.longitude})
  .then(res = > {
    this.setState({
      place: res[0].formattedAddress
    });
    console.log(res[0].formattedAddress)
  });

error will be solved.

Side Note 1: When using Promise it is a really good practice to handle error with catch.

Geocoder.geocodePosition({ lat: this.state.latitude, long: this.state.longitude})
  .then(res = > {
    // do something with response
  })
  .catch((error) => {
    // do something with error
  });

Side Note 2: You also have formatedAddress misspelled. It should be corrected to formattedAddress.

Side Note 3: setState() is asynchronous. With the way you coded it, when Geocoder.geocodePosition() is called, you are not guaranteed to have your latitude and longitude defined in state yet. So you may want to change how that's done. One possible fix for this is to place it in the callback of setState() like so:

navigator.geolocation.getCurrentPosition(
  position => {
    this.setState(
      {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        error: null,
      },
      () => {
        Geocoder.geocodePosition({
          lat: this.state.latitude,
          lng: this.state.longitude,
        }).then(res => {
          this.setState({
            place: res[0].formattedAddress,
          });
        });
      }
    );
  },
  error => this.setState({ error: error.message }),
  { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);

Upvotes: 2

Related Questions