It’s a common requirement in Apps to fetch nearest Places using Google Places API. In this article, I will explain how to fetch the nearest places in React Native using google places API. You can use this method to fetch places for both Android & IOS Apps.
Method to Fetch Nearest Places in React Native
fetchNearestPlacesFromGoogle = () => {
const latitude = 25.0756; // you can update it with user's latitude & Longitude
const longitude = 55.1454;
let radMetter = 2 * 1000; // Search withing 2 KM radius
const url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + latitude + ',' + longitude + '&radius=' + radMetter + '&key=' + YOUR_API_KEY
fetch(url)
.then(res => {
return res.json()
})
.then(res => {
var places = [] // This Array WIll contain locations received from google
for(let googlePlace of res.results) {
var place = {}
var lat = googlePlace.geometry.location.lat;
var lng = googlePlace.geometry.location.lng;
var coordinate = {
latitude: lat,
longitude: lng,
}
var gallery = []
if (googlePlace.photos) {
for(let photo of googlePlace.photos) {
var photoUrl = Urls.GooglePicBaseUrl + photo.photo_reference;
gallery.push(photoUrl);
}
}
place['placeTypes'] = googlePlace.types
place['coordinate'] = coordinate
place['placeId'] = googlePlace.place_id
place['placeName'] = googlePlace.name
place['gallery'] = gallery
places.push(place);
}
// Do your work here with places Array
})
.catch(error => {
console.log(error);
});
}
In this method, Google places Nearby Search API is used. But you can also use other request types as per your requirement. Don’t forget to change your API key in the method. In the end you will get Google places in places
array.
Enjoy 🙂
You can also find many other React Native Coding Articles.