matiru

Blockchain-Based Supply Chain Transparency for Agricultural Produce

frontend/components/LocationPicker.js (1849B)


 1import { useState, useEffect } from "react";
 2import { View, TextInput, Button, Text, Alert } from "react-native";
 3import * as Location from "expo-location";
 4import styles, { colors } from "../styles";
 5
 6export default function LocationPicker({ value, onChange }) {
 7  const [coords, setCoords] = useState(null);
 8
 9  useEffect(() => {
10    if (!value) setCoords(null);
11  }, [value]);
12
13  const pickLocation = async () => {
14    try {
15      const { status } = await Location.requestForegroundPermissionsAsync();
16      if (status !== "granted") {
17        Alert.alert("Permission denied", "Enable location services");
18        return;
19      }
20
21      const loc = await Location.getCurrentPositionAsync({});
22      setCoords(
23        `Lat ${loc.coords.latitude.toFixed(4)}, Lng ${loc.coords.longitude.toFixed(4)}`
24      );
25
26      const [address] = await Location.reverseGeocodeAsync({
27        latitude: loc.coords.latitude,
28        longitude: loc.coords.longitude,
29      });
30
31      const placeName = address
32        ? `${address.name || ""} ${address.street || ""}, ${address.city || ""}, ${address.region || ""}, ${address.country || ""}`.trim()
33        : "";
34
35      onChange(
36        placeName ||
37          `${loc.coords.latitude.toFixed(4)}, ${loc.coords.longitude.toFixed(4)}`
38      );
39    } catch (err) {
40      Alert.alert("Error", err.message);
41    }
42  };
43
44  return (
45    <View style={{ marginVertical: 8 }}>
46      <Button
47        title="Use Current Location"
48        color={colors.darkGreen}
49        onPress={pickLocation}
50      />
51      <TextInput
52        style={[styles.input, { marginTop: 10 }]}
53        placeholder="Enter Location Name"
54        value={value}
55        onChangeText={onChange}
56      />
57      {coords && (
58        <Text style={{ marginTop: 6, color: colors.darkGreen }}>
59          📍 {coords}
60        </Text>
61      )}
62    </View>
63  );
64}