【问题标题】:Problems returning address through geolocation通过地理定位返回地址的问题
【发布时间】:2017-10-23 18:56:47
【问题描述】:

我正在尝试使用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);

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

【问题讨论】:

  • 最后一条评论,你可能想从问题中编辑掉那个 API 密钥,或者只是撤销它并创建一个新的。这可能不是您想要公开的内容;) 撤销可能是更安全的选择,因为我不确定是否可以进行不会保存在 StackOverflow 历史中的编辑。
  • @MichaelCheng 看不到key的问题?它是我创建的免费公钥吗,例如,在我使用另一个的应用程序中,有什么可以做会伤害我的事情吗?
  • 我不知道您如何生成密钥的具体细节,但在一般实践中,即使您不重复使用 API 密钥,您也不希望任何人使用您的密钥。您的密钥通常存在限制,过度使用可能会导致您达到阈值。请参阅:Google Maps Geocoding API Usage Limits

标签: react-native geocode


【解决方案1】:

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() 时,您不能保证在state 中定义您的latitudelongitude。所以你可能想改变它的完成方式。一种可能的解决方法是将其放在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 }
);

【讨论】:

  • 我做了你推荐的修改,错误真的消失了,但是还没有返回地址:snack.expo.io/HyfjKaiaZ
  • 另外两件事要添加到这里:1)formatedAddress 拼写错误。应该是formattedAddress。 bennygenel 在他的日志声明中更正了它,但也要确保在 setState() 中修复它。 2) setState() 是异步的。使用您的编码方式,当调用Geocoder.geocodePosition() 时,您不能保证在state 中定义您的latitudelongitude。所以你可能想改变它的完成方式。一种可能的解决方法是将其放在 setState() 的回调中。
  • 我认为我有编辑权限,所以我将在答案中编辑一个示例。
  • 感谢大家的帮助,我做了推荐的更改,但现在我必须找出你陷入错误的原因:undefined is not an object (evaluating 'i.geocodePosition')snack.expo.io/H1h10aipZ
  • @bennygenel 我现在发现了这个问题 (github.com/devfd/react-native-geocoder/issues/25),所以我明白了react-native link 可能会解决我的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 2021-11-17
  • 2017-08-15
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
相关资源
最近更新 更多