Get Country/City without geo location API React-native?
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
}
}
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);