Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NextJS
  • Material UI
  • React Bootstrap
  • React Suite
  • Ant Design
  • Reactstrap
  • BlueprintJS
  • React Desktop
  • React Native
  • React Rebass
  • React Spring
  • React Evergreen
  • ReactJS
  • ReactJS
  • JS Formatter
  • Web Technology
Open In App
Next Article:
Create a Chatbot App using React-Native
Next article icon

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:

  • Node.js and npm installed
  • React Native development environment set up
  • Knowledge of React Native basics

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
Create a Chatbot App using React-Native

F

falgunbofs
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • Geeks Premier League
  • React-Native
  • Geeks Premier League 2023

Similar Reads

  • Create a Camera App using React-Native
    A camera app using react native is a mobile application that is designed to capture photos or videos using the built-in camera functionality of a mobile device. In this article, you will learn how you can create a camera app with simple steps. Output Preview: Let us have a look at how the final appl
    3 min read
  • Create a Blog App using React-Native
    This article shows how to create a basic blog app using react native. This app contains functionalities such as adding a blog and a delete button to remove the blogs using react native. The user can enter content with a title and then click on 'Add New Post' to create a new blog post Preview of fina
    4 min read
  • Create ClassRoom App using React-Native
    ClassRoom App using React Native is a simple application designed to facilitate online learning and classroom management. These apps are commonly used in educational institutions, schools, colleges, and universities to enhance the teaching and learning experience. Preview of final output: Let us hav
    7 min read
  • Create a Chatbot App using React-Native
    Creating a chatbot app using React Native will be an exciting project. In this article, we are going to implement a Chatbot App using React Native. Chatbot App is a mobile application that answers the user's questions on the basis of their previous learning or content provided by developers. It help
    4 min read
  • Create a Calling App using React-Native
    Building a Calling App using React-Native allows you to create a cross-platform application that supports voice calling. This tutorial will guide you through the process of integrating voice calling functionality into a React-Native app, enabling users to make and receive calls seamlessly. Preview o
    5 min read
  • Create an E-commerce App using React-Native
    An E-commerce app using react native is an application designed to facilitate online buying and selling of goods and services. These apps aim to provide a digital platform for businesses to showcase their products or services and for consumers to browse, compare, and purchase items without the need
    5 min read
  • Create Job Board App using React-Native
    In this article, we are going to Create a Job Board App using React Native. The Job Board App is a simple application that is a collection of job openings in any field. It helps the students and the people who are searching for jobs in the market. It helps to find jobs and provides in-depth informat
    6 min read
  • Create a Voting App using React-Native
    Voting involves assessing multiple entities based on specific criteria. This article guides the creation of a basic voting app, where users can compare and evaluate options. The application allows users to make choices, making it a valuable tool for decision-making and gathering opinions. We will cr
    3 min read
  • Create a Coin Flipping App using React-Native
    In this article we'll create a coin flipping app using React-Native. It allows users to simulate the flip of a coin and displays the result as either "Heads" or "Tails" with a corresponding image. The user can see the count of head and tails and can even reset the score. Preview of final output : Le
    3 min read
  • Create a Portfolio App using React-Native
    In this article, we are going to Create a portfolio app using React Native. The portfolio app is a simple application that is a collection of a person's qualifications, achievements, work samples, and other relevant materials. It is used to demonstrate one's abilities and suitability for a particula
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences