Return address by geolocation - react-native

I have this code to return the address:
const geo = {
getGeocode: (latitude, longitude) => {
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude +','+ longitude + __API_KEY__)
.then(response => {
console.log(response);
return response.data.results[0].formatted_address
}).catch((error) => {
console.log( error.message )
});
return 'Error geocode'
},
getGeolocation: () => {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
return geo.getGeocode(position.coords.latitude,position.coords.longitude);
},
(error) => console.log( error.message ),
{ enableHighAccuracy: true, timeout: 20000 },
);
return 'Error geolocation';
},
};
export default geo;
However every time I execute
import geolocation from './geolocation';
export default class App extends Component {
render() {
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Address: {geolocation.getGeolocation()}</Text>
</View>
);
}
}
this returns the Error geolocation
It returns on console the response with the address all right
I've tried it in many ways, and within what I know it should be returning the address correctly
[EDIT]
I tried this code too:
export const geo = {
var: address = '...',
getGeocode: (latitude, longitude) => {
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude +','+ longitude + __API_KEY__)
.then(response => {
console.log(response);
response.data.results[0].formatted_address;
}).catch((error) => {
console.log( error.message )
});
return 'Error geocode';
},
getGeolocation: () => {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
geo.getGeocode(position.coords.latitude, position.coords.longitude);
},
(error) => console.log( error.message ),
{ enableHighAccuracy: true, timeout: 20000 },
);
return address;
},
};
I return the address correctly, however I can not pass the value of response.data.results[0].formatted_address to variable address
How can I do this?

Related

I want to get currentlocation of user , I am getting current location in android and ios but not on android tablet

I am getting correct latitude and longitude in android and ios and showing the marker but this doesn't happen on tablet. I am not getting marker in tablet android , I have enable showUserLocation={true} as well.
useEffect(() => {
const requestLocationPermission = async () => {
if (Platform.OS === 'ios') {
Geolocation.requestAuthorization('always').then((resp) => {
console.log("ios response ", resp)
Geolocation.getCurrentPosition(
(position) => {
console.log("position:::", position)
const { latitude, longitude } = position.coords;
setCurrentLatitude(latitude)
setCurrentLongitude(longitude)
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 20000 }
);
}).catch((e) => console.log("ios error ::", e))
}
else {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Access Required',
message: 'This App needs to Access your location',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Geolocation.getCurrentPosition(
(position) => {
// console.log("position:::", position)
const { latitude, longitude } = position.coords;
setCurrentLatitude(latitude)
setCurrentLongitude(longitude)
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: false, timeout: 20000 }
);
} else {
setLocationStatus('Permission Denied');
}
} catch (err) {
console.warn("Location error ::", err);
}
};
}
requestLocationPermission();
}, [])
This is what I have done

Fetch virtual payment address of users in my react native app

I have integrated react-native-upi-payment in my app. The RNUpiPayment Component calls initializePayment method here which gives only vpa for a default user. How can I give vpa address for many users in my database by fecth api or any other methods? Any methods or suggestions please.
My code is here
<TouchableOpacity
style={styles.payBtn}
activeOpacity={0.5}
onPress={() => {
RNUpiPayment.initializePayment(
{
vpa: '8856452125#ybl', // or can be john#ybl or mobileNo#upi
payeeName: 'Stanlee',
amount: '20',
transactionRef: 'aasf-332-aoei-fn',
},
() => {
console.log('Success');
},
() => {
console.log('Failed');
},
);
}}>
<Text style={styles.payBtnTxt}>PAY</Text>
</TouchableOpacity>
Finally got it!
DriverPaymentFunction = () => {
const {DriverUPI} = this.state;
const {DriverName} = this.state;
fetch('http://ip/appname/payment.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
upi_id: DriverUPI,
driver: DriverName,
}),
})
.then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if (responseJson === 'Data Matched') {
RNUpiPayment.initializePayment( //Payment API
{
vpa: DriverUPI, // or can be john#ybl or mobileNo#upi
payeeName: DriverName,
amount: '0',
transactionRef: 'AppName Ride Transaction',
},
() => {
console.log('Success');
},
() => {
console.log('Failed');
},
);
} else {
Alert.alert(responseJson);
}
})
.catch((error) => {
console.error(error);
});
};

Send data to webService in react-native

Hi I'm working on a app in react-native which is using the latitude and longitude of the user phone position. I'm also using a webService that let me retrieve some data about the user. I want now to send the latitude and longitude to the webservice how can I do that ?
getData(){
const url = "https://somewebsite.com/webservice/app/ws.php"
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
dataSource: res
});
})
.catch(error => {
console.log("get data error:" + error);
});
}
displayPosition = () => {
Geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: JSON.stringify(position.coords.latitude),
longitude: JSON.stringify(position.coords.longitude),
error: null,
});
console.log(this.state.latitude)
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
}
Will it work if I do : `https://somewebsite.com/webservice/app/ws.php?lo=${this.state.longitude}&la=${this.state.latitude} `
You need to use POST method to send data to your backend. You can use axios. Here is a very basic example:
axios.post('https://somewebsite.com/webservice/app/ws.php', {
latitude: position.coords.latitude,
longitude: position.coords.longitude
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

React-redux action is returning before async action is complete

I have a React Native app using redux and I'd like my action to set the GPS coordinates so I have them available in the store. You can see my console logs in the code, and 'action returning' is logged before 'has coordinates', which is the problem.
Component:
<TouchableOpacity style={{flex:1}} onPress={() => {
this.props.setLocation();
}}>
Action.js
export function setLocation(){
let coords = {
latitude:0,
longitude:0,
navigatorError:''
};
navigator.geolocation.getCurrentPosition(
(position) => {
console.log('has coordinates');
coords['latitude'] = position.coords.latitude
coords['longitude'] = position.coords.longitude
coords['navigatorError'] = null
},
(error) => coords['navigatorError'] = error.message,
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
console.log('action returning');
return {
type: 'set_location',
payload: coords
};
};
Reducer.js
export default (state = null, action) => {
switch(action.type){
case 'set_location':
return action.payload;
default:
return state;
}
}
Note: I'm not actually using redux-thunk in this project, I'm not sure if it's appropriate for what I need here.
You can use async and await to accomplish this. Basically, you need to await the coords to be returned from your asynchronous call.
Something like this:
export async function setLocation(){
let coords = {
latitude:0,
longitude:0,
navigatorError:''
};
await navigator.geolocation.getCurrentPosition(
(position) => {
console.log('has coordinates');
coords['latitude'] = position.coords.latitude
coords['longitude'] = position.coords.longitude
coords['navigatorError'] = null
},
(error) => coords['navigatorError'] = error.message,
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
console.log('action returning');
return {
type: 'set_location',
payload: coords
};
};
Documentation on async/await can be found here.

Extract formatted_address from JSON return from Google Maps API

I'm using the google maps API to do the reverse geocoding but I'm not able to extract the formatted_address
componentWillMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000 },
);
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ this.state.latitude +','+ this.state.longitude +'&key=__API_KEY__')
.then(results => {
this.setState({
place: results[0].formated_address
})
.catch((error) => {
this.setState({ error: error.message })
});
});
}
How do I do that?
first you need to call the api after getCurrentPosition is finished
be sure your api key is correct and has access to the geocode api
access the first place address from response.data.results[0].formatted_address note that i changed results to response since it is more descriptive name also note that formatted_address with double t
finally catch is called after then not after setState
full working example
componentWillMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
}, () => this.getGeocode()); // call the api after getCurrentPosition is finished
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000 },
);
}
getGeocode() {
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ this.state.latitude +','+ this.state.longitude +'&key=__API_KEY__') // be sure your api key is correct and has access to the geocode api
.then(response => {
console.log(response);
this.setState({
place: response.data.results[0].formatted_address // access from response.data.results[0].formatted_address
})
}).catch((error) => { // catch is called after then
this.setState({ error: error.message })
});
}