Location and Camera

Back

Loading concept...

📍 React Native: Device Features - Location and Camera

The Treasure Map Adventure 🗺️

Imagine you’re a pirate captain with a magical map that always knows exactly where your ship is. And you also have a special spyglass that can capture any scene and save it forever. That’s what we’re building today! Your phone becomes that magical map (Location) and spyglass (Camera).


🧭 Part 1: The Geolocation API

What is the Geolocation API?

Think of the Geolocation API like asking a wise old owl: “Hey owl, where am I right now?”

The owl looks at the stars (GPS satellites), listens to nearby towers (cell towers), and checks the wind (WiFi signals). Then it tells you EXACTLY where you are on Earth!

// The magical owl lives here
import Geolocation from
  '@react-native-community/geolocation';

// Or use expo-location
import * as Location from 'expo-location';

Why do we need it?

  • 🚗 Show directions to grandma’s house
  • 🏃 Track your morning jog
  • 📦 Find the nearest pizza shop
  • 🎮 Play location-based games

📍 Part 2: Getting Your Current Position

The “Where Am I Right Now?” Button

Imagine pressing a button and instantly knowing you’re standing at “123 Oak Street, next to the big red mailbox.”

// Ask for permission first!
const getPermission = async () => {
  const { status } = await Location
    .requestForegroundPermissionsAsync();

  if (status !== 'granted') {
    alert('We need location access!');
    return false;
  }
  return true;
};

Getting Your Position

// Get current position - ONE TIME
const findMe = async () => {
  const location = await Location
    .getCurrentPositionAsync({});

  console.log('Latitude:',
    location.coords.latitude);
  console.log('Longitude:',
    location.coords.longitude);
};

What do latitude and longitude mean?

graph TD A["🌍 Earth"] --> B["Latitude"] A --> C["Longitude"] B --> D["↕️ North/South"] C --> E["↔️ East/West"] D --> F["Like floors in a building"] E --> G["Like rooms on each floor"]

Real Example:

  • Latitude: 40.7128 (how far north)
  • Longitude: -74.0060 (how far west)
  • This is New York City! 🗽

👀 Part 3: Position Watching

The “Follow Me Everywhere” Feature

Remember that owl? Now imagine it follows you around, constantly updating where you are. Every step you take, it whispers: “Now you’re HERE!”

// Start watching position
const watchId = Location
  .watchPositionAsync(
  {
    accuracy: Location.Accuracy.High,
    distanceInterval: 10, // meters
  },
  (newLocation) => {
    console.log('You moved!');
    console.log('New position:',
      newLocation.coords);
  }
);

When to Use Watch vs Get Current

Scenario Use This
Show user on map once getCurrentPosition
Navigation app watchPosition
“Check in” at store getCurrentPosition
Fitness tracking watchPosition

Stopping the Watch

// When done tracking
watchId.remove();
// The owl goes back to sleep 🦉💤

🎯 Part 4: Location Accuracy

High, Low, or Balanced?

Imagine three owls:

  • 🦉 Sharp-Eye Owl: Super accurate but uses lots of energy (battery)
  • 🦉 Sleepy Owl: Not very accurate but saves energy
  • 🦉 Balanced Owl: Good enough accuracy, reasonable energy
// Accuracy options in Expo
const accuracyLevels = {
  Lowest: Location.Accuracy.Lowest,
  Low: Location.Accuracy.Low,
  Balanced: Location.Accuracy.Balanced,
  High: Location.Accuracy.High,
  Highest: Location.Accuracy.Highest,
  BestForNavigation:
    Location.Accuracy.BestForNavigation,
};

Choosing the Right Accuracy

graph TD A["What are you building?"] --> B{Need exact location?} B -->|Yes| C["High/BestForNavigation"] B -->|No| D{Battery important?} D -->|Yes| E["Low/Lowest"] D -->|No| F["Balanced"] C --> G["📍 Within 10 meters"] E --> H["📍 Within 3000 meters"] F --> I["📍 Within 100 meters"]

Example with accuracy:

const options = {
  accuracy: Location.Accuracy.High,
  maximumAge: 10000, // 10 seconds old OK
  timeout: 5000, // wait max 5 seconds
};

const location = await Location
  .getCurrentPositionAsync(options);

📸 Part 5: Camera Basics

Your Phone’s Magical Eye

Now let’s talk about the spyglass! Your phone’s camera is like a magical eye that can freeze any moment in time.

Setting Up Camera Access

// Using expo-camera
import { Camera } from 'expo-camera';

// Ask permission to use the eye
const getCameraPermission = async () => {
  const { status } = await Camera
    .requestCameraPermissionsAsync();

  return status === 'granted';
};

Basic Camera Component

import { Camera, CameraType } from
  'expo-camera';

function MyCamera() {
  const [type, setType] = useState(
    CameraType.back
  );

  return (
    <Camera style={{flex: 1}} type={type}>
      {/* Camera preview shows here */}
    </Camera>
  );
}

Front vs Back Camera

graph TD A["📱 Phone Cameras"] --> B["Back Camera"] A --> C["Front Camera"] B --> D["📸 Takes photos of world"] C --> E["🤳 Takes selfies"] B --> F["Usually better quality"] C --> G["CameraType.front"]

Flipping the Camera

const flipCamera = () => {
  setType(current =>
    current === CameraType.back
      ? CameraType.front
      : CameraType.back
  );
};

Taking a Photo

const cameraRef = useRef(null);

const takePhoto = async () => {
  if (cameraRef.current) {
    const photo = await cameraRef.current
      .takePictureAsync();

    console.log('Photo saved at:',
      photo.uri);
  }
};

🖼️ Part 6: Image Picker

Choosing Photos from Your Gallery

Sometimes you don’t want to take a NEW photo. You want to pick one you already have! It’s like opening a photo album and pointing: “I want THIS one!”

Setting Up Image Picker

import * as ImagePicker from
  'expo-image-picker';

// Ask permission for gallery
const getGalleryPermission = async () => {
  const { status } = await ImagePicker
    .requestMediaLibraryPermissionsAsync();

  return status === 'granted';
};

Picking an Image from Gallery

const pickImage = async () => {
  const result = await ImagePicker
    .launchImageLibraryAsync({
      mediaTypes:
        ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

  if (!result.canceled) {
    console.log('Picked:',
      result.assets[0].uri);
  }
};

Taking a Photo via Image Picker

// Opens camera through ImagePicker
const takePhoto = async () => {
  const result = await ImagePicker
    .launchCameraAsync({
      allowsEditing: true,
      aspect: [1, 1], // Square
      quality: 0.8,
    });

  if (!result.canceled) {
    setImage(result.assets[0].uri);
  }
};

Image Picker Options Explained

graph TD A["Image Picker Options"] --> B["mediaTypes"] A --> C["allowsEditing"] A --> D["aspect"] A --> E["quality"] B --> F["Images/Videos/All"] C --> G["true = crop tool"] D --> H["[4,3] or [1,1]"] E --> I["0.0 to 1.0"]

🎁 Putting It All Together

A Complete Location + Camera Example

import React, { useState } from 'react';
import { View, Button, Image, Text }
  from 'react-native';
import * as Location from 'expo-location';
import * as ImagePicker from
  'expo-image-picker';

export default function App() {
  const [location, setLocation] =
    useState(null);
  const [image, setImage] = useState(null);

  const getLocation = async () => {
    let { status } = await Location
      .requestForegroundPermissionsAsync();

    if (status !== 'granted') return;

    let loc = await Location
      .getCurrentPositionAsync({});
    setLocation(loc);
  };

  const pickImage = async () => {
    let result = await ImagePicker
      .launchImageLibraryAsync({
        mediaTypes: ImagePicker
          .MediaTypeOptions.Images,
        allowsEditing: true,
        quality: 1,
      });

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
  };

  return (
    <View style={{padding: 20}}>
      <Button
        title="📍 Get Location"
        onPress={getLocation}
      />
      <Button
        title="🖼️ Pick Image"
        onPress={pickImage}
      />

      {location && (
        <Text>
          Lat: {location.coords.latitude}
        </Text>
      )}

      {image && (
        <Image
          source={{uri: image}}
          style={{width: 200, height: 200}}
        />
      )}
    </View>
  );
}

🌟 Key Takeaways

  1. Geolocation API = Your wise owl that knows where you are
  2. getCurrentPosition = Ask once: “Where am I?”
  3. watchPosition = Keep following me everywhere
  4. Accuracy = How precise (affects battery!)
  5. Camera = Your magical eye to capture moments
  6. Image Picker = Choose from your photo album

🚀 What’s Next?

Now you can:

  • Build a “Find My Friends” app
  • Create a running tracker
  • Make a photo diary with locations
  • Build location-based games

Remember: Always ask for permissions politely, and only use location when you really need it. Users trust you with their data! 🔒


You’re now a master of device features! Go build something amazing!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.