import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, Platform } from 'react-native';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import Geolocation from 'react-native-geolocation-service';
const GooglePlacesInput = () => {
const [location, setLocation] = useState(null); // Store user's location
const [locationPermissionGranted, setLocationPermissionGranted] = useState(false); // Track permission status
const GOOGLE_PLACES_API_KEY = 'YOUR_GOOGLE_PLACES_API_KEY'; // Replace with your API key (use env vars or secure storage)
useEffect(() => {
// Request location permissions when the component mounts
requestLocationPermission();
}, []);
// Function to request location permissions
const requestLocationPermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await Geolocation.requestAuthorization('always');
if (granted === 'granted') {
setLocationPermissionGranted(true);
getCurrentLocation(); // Fetch user's location after permission is granted
}
} catch (err) {
console.error('Android permission error:', err);
}
} else if (Platform.OS === 'ios') {
// Request authorization for iOS
Geolocation.requestAuthorization();
getCurrentLocation(); // Attempt to get location, which will prompt for permissions
}
};
// Function to fetch the user's current location
const getCurrentLocation = () => {
Geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
setLocation({ lat: latitude, lng: longitude }); // Update state with user's location
},
(error) => {
console.error('Location error:', error);
},
{
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 10000,
}
);
};
return (
<View>
<GooglePlacesAutocomplete
placeholder="Search"
minLength={2} // Minimum input length to trigger suggestions
autoFocus={true}
returnKeyType={'search'}
placeholderTextColor={'#333'}
onPress={(data, details = null) => {
console.log(data, details);
}}
query={{
key: GOOGLE_PLACES_API_KEY, // Use API key from secure source
language: 'en',
types: '(cities)', // Optional: Filter by cities
location: location ? `${location.lat},${location.lng}` : '', // Pass user's location for nearby results
radius: location ? '20000' : '', // Search radius in meters around the user's location
}}
styles={{
textInputContainer: {
backgroundColor: 'rgba(0,0,0,0)',
borderTopWidth: 0,
borderBottomWidth: 0,
},
textInput: {
marginLeft: 0,
marginRight: 0,
height: 38,
color: '#5d5d5d',
fontSize: 16,
},
predefinedPlacesDescription: {
color: '#1faadb',
},
}}
currentLocation={true} // Show "Current location" option
currentLocationLabel="Current location"
/>
{/* Display a button to request permissions if they are not granted */}
{!locationPermissionGranted && (
<TouchableOpacity onPress={requestLocationPermission}>
<Text>Grant Location Permission</Text>
</TouchableOpacity>
)}
</View>
);
};
export default GooglePlacesInput;