18

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?

Community
  • 1
  • 1
joey rohan
  • 3,505
  • 5
  • 33
  • 70

2 Answers2

38

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);
vinayr
  • 11,026
  • 3
  • 46
  • 42
  • Thank you so much . Would you mind explaining `.then((response) => response.json()) .then((responseJson) => { ` ? – joey rohan Mar 17 '17 at 07:30
  • 1
    `response.json()` returns JSON data of response and it is passed on to `then` promise. You can find more information here https://developer.mozilla.org/en-US/docs/Web/API/Body/json – vinayr Mar 17 '17 at 07:36
  • Hi @vinayr, I used your clever solution but it keeps me returning this error: `React-Native fetch, Network request failed` do you know why? I tried to remove the https with the http but nothing. – Univers3 Oct 26 '17 at 09:49
  • your solution found response using device ip address? – bittu Feb 27 '18 at 11:51
  • 9
    This is not recommended anymore. "This API endpoint is deprecated and will stop working on July 1st, 2018. For more information please visit: https://github.com/apilayer/freegeoip#readme" – Alon Apr 26 '18 at 11:19
5

First, get the public IP address using react-native-public-ip and then use api.ipstack.com

export const getUserCurrentCountry = () => async (dispatch) => {
  let res;
  try {
    const ACCESS_KEY = 'IPSTACK_ACCESS_KEY_HERE';
    const publicIpAddress = await publicIP();
    const url = `http://api.ipstack.com/${publicIpAddress}?access_key=${ACCESS_KEY}&format=1`;
    res = await fetch(url)
    res = await res.json();
    return res;
  } catch ({message}) {
    return null;
  }
};

The result will be in this format

{
  "ip":"",
  "type":"ipv4",
  "continent_code":"AS",
  "continent_name":"Asia",
  "country_code":"PK",
  "country_name":"Pakistan",
  "region_code":"SD",
  "region_name":"Sindh",
  "city":"Karachi",
  "zip":"74000",
  "latitude":24.882999420166016,
  "longitude":67.05799865722656,
  "location":{
    "geoname_id":1174872,
    "capital":"Islamabad",
    "languages":[
      {
        "code":"en",
        "name":"English",
        "native":"English"
      },
      {
        "code":"ur",
        "name":"Urdu",
        "native":"\u0627\u0631\u062f\u0648",
        "rtl":1
      }
    ],
    "country_flag":"http:\/\/assets.ipstack.com\/flags\/pk.svg",
    "country_flag_emoji":"\ud83c\uddf5\ud83c\uddf0",
    "country_flag_emoji_unicode":"U+1F1F5 U+1F1F0",
    "calling_code":"92",
    "is_eu":false
  }
}
Zeeshan Ansari
  • 9,657
  • 3
  • 26
  • 27