Open In App

Create a Compass App using React-Native

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this project, we'll create a Compass App using React Native. The app will display real-time compass heading information, along with additional details such as cardinal direction. The user interface will include a rotating compass image to provide a visual representation of the device's orientation.

Preview of final output: Let us have a look at how the final output will look like.

Screenshot-2024-01-19-104002

Prerequisites:

Approach to create Compass App using React Native:

  • Display Real-time Compass Heading: Utilize the react-native-compass-heading package to access the device's compass sensor and receive real-time updates for the current heading.
  • Show a Rotating Compass Image: Implement the Animated API from React Native to create a visually appealing rotation effect on a compass image, reflecting changes in the device's orientation.
  • Determine and Display Cardinal Direction: Calculate the cardinal direction (North, East, South, West) based on the current heading, providing users with an intuitive sense of their device's orientation in relation to the cardinal points.

Steps to Create the Project:

Step 1: Initialize a new React Native project:

npx react-native init CompassApp
cd CompassApp

Step 2: Install dependencies:

npm install @react-native-community/compass-react-native react-navigation react-navigation-stack

Project Structure:

Screenshot-2024-01-19-112637

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "18.2.0",
"react-native": "0.73.2",
"react-native-compass-heading": "^1.5.0",
"react-navigation": "^4.4.4",
"react-navigation-stack": "^2.10.4"
},
"devDependencies": {
"@babel/core": "^7.20.0",
"@babel/preset-env": "^7.20.0",
"@babel/runtime": "^7.20.0",
"@react-native/babel-preset": "0.73.19",
"@react-native/eslint-config": "0.73.2",
"@react-native/metro-config": "0.73.3",
"@react-native/typescript-config": "0.73.1",
"@types/react": "^18.2.6",
"@types/react-test-renderer": "^18.0.0",
"babel-jest": "^29.6.3",
"eslint": "^8.19.0",
"jest": "^29.6.3",
"prettier": "2.8.8",
"react-test-renderer": "18.2.0",
"typescript": "5.0.4"
}

Step 3: Create the Compass component (Compass.js) and add the following code for adding compass functionalities and styles:

JavaScript
//Compass.js

import React, { useEffect, useState } from "react";
import CompassHeading from "react-native-compass-heading";
import { View, Text, StyleSheet, Image, Animated } from "react-native";

const Compass = () => {
	const [heading, setHeading] = useState(0);
	const rotateValue = new Animated.Value(0);

	useEffect(() => {
		const degreeUpdateRate = 3;

		CompassHeading.start(degreeUpdateRate, ({ heading, accuracy }) => {
			console.log("CompassHeading: ", heading, accuracy);
			setHeading(heading);

			// Rotate the compass image
			Animated.timing(rotateValue, {
				toValue: heading,
				duration: 100,
				useNativeDriver: false,
			}).start();
		});

		return () => {
			CompassHeading.stop();
		};
	}, []);

	const rotateStyle = {
		transform: [{ rotate: `${-heading}deg` }],
	};

	const getCardinalDirection = () => {
		const directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
		const index = Math.round(heading / 45) % 8;
		return directions[index];
	};

	return (
		<View style={styles.container}>
			<Text style={styles.appName}>Beautiful Compass App</Text>
			<View style={styles.compassContainer}>
				<Animated.Image
					source={
					require("
https://media.geeksforgeeks.org/wp-content/uploads/20240122153821/compass.png"
					)}
					style={[styles.compassImage, rotateStyle]}
				/>
			</View>
			<Text style={styles.headingValue}>{`Heading: ${heading.toFixed(
				2
			)}°`}</Text>
			<Text
				style={styles.cardinalDirection}
			>{`Direction: ${getCardinalDirection()}`}</Text>
		</View>
	);
};

const styles = StyleSheet.create({
	container: {
		flex: 1,
		justifyContent: "center",
		alignItems: "center",
		backgroundColor: "#f5f5f5",
	},
	appName: {
		fontSize: 24,
		fontWeight: "bold",
		marginBottom: 10,
		color: "#333",
	},
	compassContainer: {
		width: 250,
		height: 250,
		justifyContent: "center",
		alignItems: "center",
		backgroundColor: "#fff",
		borderRadius: 125,
		shadowColor: "#000",
		shadowOffset: { width: 0, height: 2 },
		shadowOpacity: 0.3,
		shadowRadius: 3,
		elevation: 5,
	},
	compassImage: {
		width: 200,
		height: 200,
	},
	headingValue: {
		fontSize: 18,
		marginTop: 10,
		color: "#555",
	},
	cardinalDirection: {
		fontSize: 18,
		marginTop: 10,
		color: "#555",
	},
});

export default Compass;

Step 4: To run the application:

  • Navigate to the project folder
cd CompassApp
  • Run the application (Android):
npx react-native run-android
  • Run the application (Android): (iOS)
npx react-native run-ios

Output:


Next Article

Similar Reads