Approach and Logic

  • The application will have single page.
  • It will have a title, two text for displaying the Latitude and Longitude.
  • It will also have a Update location button and a Share button.
  • Imports and Dependencies: The code imports necessary modules like expo-status-bar, Location, and Share for location services and sharing functionality in a React-Native app.
  • Fetching User Location: It requests user location permissions, retrieves the latitude and longitude, and updates the state when the component mounts. An alert notifies when location is updated.
  • Sharing User Location: The shareLocation function creates a Google Maps link with the user’s location and shares it. It handles success, cancellation, and errors, showing alerts when needed.
  • User Interface: The app’s UI displays a welcome message, the user’s latitude and longitude (if available), buttons to open Google Maps and share location, and a loading message during location retrieval.
  • Styling and Layout: Styles are defined using StyleSheet.create for a centered and visually appealing layout. Various text styles, buttons, and positioning are configured to create an attractive user interface.

Example: In this example we are following the above-explained approach.

App.js

Javascript




import { StatusBar } from "expo-status-bar";
import {
    Button,
    StyleSheet,
    Text,
    View,
    Share,
    Alert,
    Linking,
} from "react-native";
import * as Location from "expo-location";
import { useEffect, useState } from "react";
  
export default function App() {
  
    // State variable to store the user's location
    const [location, setLocation] = useState(null);
  
    // Function to fetch the user's location
    const fetchLocation = async () => {
        await Location.requestForegroundPermissionsAsync();
  
        const {
            coords: { latitude, longitude },
        } = await Location.getCurrentPositionAsync();
        setLocation({ latitude, longitude });
  
        // Show an alert when the location is updated
        Alert.alert("w3wiki", "Location Updated", [
            {
                text: "Close",
                onPress: () => console.log("Close Pressed"),
                style: "destructive",
            },
        ]);
    };
  
    // Function to share the user's location
    const shareLocation = async () => {
        try {
            const result = await Share.share({
                // Create a Google Maps link using the user's location
                message:
`https://www.google.com/maps/search/?api=1&query=${location?.latitude},${location?.longitude}`,
            });
  
            if (result.action === Share.sharedAction) {
                if (result.activityType) {
                    console.log("shared with activity type of ",
                        result.activityType);
                } else {
                    console.log("shared");
                }
            } else if (result.action === Share.dismissedAction) {
                console.log("dismissed");
            }
        } catch (error) {
          
            // Show an alert if there's an error while sharing location
            Alert.alert(
                "w3wiki",
                "Something went wrong while sharing location",
                [
                    {
                        text: "Close",
                        onPress: () => console.log("Close Pressed"),
                        style: "destructive",
                    },
                ]
            );
        }
    };
  
    // Fetch the user's location when the component mounts
    useEffect(() => {
        fetchLocation();
    }, []);
  
    return (
        <View style={styles.container}>
            <Text style={styles.heading}>
                Welcome to w3wiki
            </Text>
            <Text style={styles.heading2}>
                Location Sharing App
            </Text>
            {location ? (
                <View>
                    <Text style={styles.text1}>
                        Latitude: {location?.latitude}
                    </Text>
                    <Text style={styles.text1}>
                        Longitude: {location?.longitude}
                    </Text>
                    <Button
                        onPress={() => {
                          
                            // Open Google Maps with the user's location
                            Linking.openURL(
`https://www.google.com/maps/search/?api=1&query=${location?.latitude},${location?.longitude}`
                            );
                        }}
                        title="Open in Google Maps"
                    />
                </View>
            ) : (
                <Text style={styles.text1}>
                    Loading...
                </Text>
            )}
            <Button title="Update Location"
                onPress={fetchLocation} />
            <Button title="Share Location"
                onPress={shareLocation} />
  
            <StatusBar style="auto" />
        </View>
    );
}
  
const styles = StyleSheet.create({
    container: {
        display: "flex",
        alignContent: "center",
        alignItems: "center",
        justifyContent: "space-evenly",
        backgroundColor: "#fff",
        height: "100%",
    },
    heading: {
        fontSize: 28,
        fontWeight: "bold",
        marginBottom: 10,
        color: "green",
        textAlign: "center",
    },
    heading2: {
        fontSize: 22,
        fontWeight: "bold",
        marginBottom: 10,
        color: "black",
        textAlign: "center",
    },
    text1: {
        fontSize: 16,
        marginBottom: 10,
        color: "black",
        fontWeight: "bold",
    },
});


package.json

Javascript




{
    "name": "location-sharing-app",
    "version": "1.0.0",
    "main": "node_modules/expo/AppEntry.js",
    "scripts": {
        "start": "expo start",
        "android": "expo start --android",
        "ios": "expo start --ios",
        "web": "expo start --web"
    },
    "dependencies": {
        "expo": "~49.0.10",
        "expo-location": "~16.1.0",
        "expo-sharing": "~11.5.0",
        "expo-status-bar": "~1.6.0",
        "react": "18.2.0",
        "react-native": "0.72.4"
    },
    "devDependencies": {
        "@babel/core": "^7.20.0"
    },
    "private": true
}


Step 4: Navigate to the terminal or command prompt and type the required command there to run the React native application.

npx expo start

To run on Android:

npx react-native run-android

To run on Ios:

npx react-native run-ios

Step optional: To run on Web, you need to install the following packages

npx expo install react-dom react-native-web @expo/webpack-config

Step 5: To run on web, press w on Terminal will application is running. For Android/IOS, install the Expo app and scan the QR code or enter the link of Metro in the Terminal.

Output:



Create a Location Sharing App using React-Native

In this article, we are going to build a step-by-step Location Sharing App using React-Native. A Location Sharing App developed with React-Native allows users to share their real-time location with others. It leverages React-Native’s cross-platform capabilities to create a mobile application that facilitates location sharing and tracking among users. Using this application, the user will be able to fetch his/her current location and also allow the user to share it.

Here is the demo of the application.

Similar Reads

Prerequisites and Technolgies Used

Introduction to React Native Introduction React Native Components React Native State React Native Props Expo CLI Node.js and npm (Node Package Manager)...

Project Setup

Step 1: Create the project:...

Project Structure

...

Approach and Logic

The application will have single page. It will have a title, two text for displaying the Latitude and Longitude. It will also have a Update location button and a Share button. Imports and Dependencies: The code imports necessary modules like expo-status-bar, Location, and Share for location services and sharing functionality in a React-Native app. Fetching User Location: It requests user location permissions, retrieves the latitude and longitude, and updates the state when the component mounts. An alert notifies when location is updated. Sharing User Location: The shareLocation function creates a Google Maps link with the user’s location and shares it. It handles success, cancellation, and errors, showing alerts when needed. User Interface: The app’s UI displays a welcome message, the user’s latitude and longitude (if available), buttons to open Google Maps and share location, and a loading message during location retrieval. Styling and Layout: Styles are defined using StyleSheet.create for a centered and visually appealing layout. Various text styles, buttons, and positioning are configured to create an attractive user interface....