Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Country/City without geo location API React-native?

Is there a way to find a clients location on mobile device? For example, if a user opens app, how could I find out what their approximate location?

For example, if a user came from San Francisco CA it would have some type identifier to let me know the user came from San Francisco CA. I wouldn't really need their exact location just the county or general area of origin.

Well I had a reference : This SO Question .Can we somehow implement the same in React-native?

like image 640
joey rohan Avatar asked Mar 17 '17 06:03

joey rohan


1 Answers

Sure. Based on one of the answers in that thread, you can implement in React Native like this -

import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';

export default class Test extends Component {
  constructor(props) {
    super(props);
    this.state = {
      countryName: '',
      regionName: ''
    };
  }

  componentDidMount() {
    var url = 'https://freegeoip.net/json/';
    fetch(url)
      .then((response) => response.json())
      .then((responseJson) => {
        //console.log(responseJson);
        this.setState({
          countryName: responseJson.country_name,
          regionName: responseJson.region_name
        });
      })
      .catch((error) => {
       //console.error(error);
      });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text>Country: {this.state.countryName}</Text>
        <Text>Region: {this.state.regionName}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

AppRegistry.registerComponent('Test', () => Test);
like image 101
vinayr Avatar answered Oct 23 '22 06:10

vinayr