有没有办法在移动设备上找到客户位置?例如,如果用户打开应用,我怎么能找出他们的大概位置?
例如,如果用户来自旧金山的CA,则会有一些类型标识符让我知道该用户来自旧金山CA.我真的不需要他们的确切位置只是县或一般的原产地。
我有一个参考:This SO Question 。我们能以某种方式在React-native中实现相同的功能吗?
答案 0 :(得分:32)
不确定。基于该线程中的一个答案,您可以像这样在React Native中实现 -
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);
答案 1 :(得分:0)
首先,使用react-native-public-ip获取公共IP地址,然后使用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;
}
};
结果将采用这种格式
{
"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
}
}