通过地理定位返回地址的问题

时间:2017-10-23 18:56:48

标签: react-native geocode

我尝试使用react-native-geocoder库通过设备的纬度和经度返回地址。

通过回答另一个问题和更多研究,我想出了这个代码:

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

但这会让我回到正确的纬度和经度,但保持定位地址......并且永远不会返回。

修改

在bennygenel和Michael Cheng的帮助下,我设法消除了警告并得到了这段代码:

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

但是当我执行它时它返回错误:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

Geocoder.geocodePosition包含一个包含latlong的对象。您正尝试发送2个单独的参数。

如果你改变了

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

到这个

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

错误将被解决。

旁注1:使用Promise时,使用catch处理错误是一种非常好的做法。

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

旁注2:您的formatedAddress拼写错误。应将其更正为formattedAddress

旁注3: setState()是异步的。根据您对其进行编码的方式,在调用Geocoder.geocodePosition()时,您无法保证在latitude中定义longitudestate。所以你可能想要改变它的完成方式。一个可能的解决方法是将其置于setState()的回调中,如下所示:

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