反应本地获取国家和城市

时间:2021-07-02 13:00:32

标签: react-native geolocation

我需要为我的应用获取用户所在的国家和城市。

我可以使用此代码获取纬度并登录。

如何让城市和国家反应原生

import GetLocation from 'react-native-get-location';


getUserLocation() {
    GetLocation.getCurrentPosition({
      enableHighAccuracy: true,
      timeout: 15000,
    })
      .then(location => {
        console.log('location');
        console.log(location);
      })
      .catch(error => {
        const {code, message} = error;
        console.warn(code, message);
      });
  }

它回来了

accuracy: 20
altitude: x0.47877258310501
bearing: 0
latitude: x0.7637253
longitude: x9.9530597
provider: "fused"
speed: 0
time: xx25230494592

也试过了

import Geolocation from 'react-native-geolocation-service';
    Geolocation.getCurrentPosition(
      position => {
        console.log('position');
        console.log(position);
      },
      error => {
        // See error code charts below.
        console.log(error.code, error.message);
      },
      {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
    );

它返回几乎相同。纬度经度,

coords:
accuracy: 20
altitude: x0.52203785539176
altitudeAccuracy: 3
heading: x70
latitude: x0.7637262
longitude: x9.9530588
speed: 0.0013554140459746122
__proto__: Object
mocked: false
provider: "fused"
timestamp: 1625231106853

1 个答案:

答案 0 :(得分:0)

尝试使用 npm 包从纬度和经度值中获取地址。 React Native Geocoding

为此,您可能需要从 Google Cloud

生成地理编码 API 密钥

代码示例

import Geocoder from 'react-native-geocoding';

// Initialize the module (needs to be done only once)
Geocoder.init("xxxxxxxxxxxxxxxxxxxxxxxxx"); // use a valid API key

// Search by geo-location (reverse geo-code)
Geocoder.from(41.89, 12.49)
        .then(json => {
                var addressComponent = json.results[0].address_components[0];
            console.log(addressComponent);
        })
        .catch(error => console.warn(error));