Header Ads Widget

Responsive Advertisement

Want to build a smart location-based app that works even without internet? In this blog, we’ll show you how to combine ObjectBox, a lightning-fast local NoSQL database, with Flutter and device location data to create a fully offline “Find Nearby Places” feature.

You’ll learn how to:

  • Store places with latitude and longitude
  • Get the user’s current location(Mock for now)
  • Calculate distances with the Haversine formula
  • Filter and sort results based on proximity
  • Build a local-first experience that feels instant and reliable
Thumbnail

Perfect for apps like travel guides, delivery services, or city explorers — this guide helps you give users what they need, right where they are, even without a connection. 🌍📱

🧠 What is a Vector Database (and Why Should You Care)?

If traditional databases are like libraries with exact book titles, vector databases are more like brainy librarians who understand what you mean, not just what you type.

Let’s break it down:

📚 Traditional DB:

  • You search "vegan pasta" → returns results with exact word match.

🤖 Vector DB:

  • You search "healthy Italian food" → also suggests "vegan pasta", "zucchini noodles", or "Mediterranean salad" — because it understands semantic similarity.


🧬 Under the Hood: How Vector Databases Work

Objectbox vector database

Here’s the secret sauce:

1. Embeddings = Meaning in Numbers

Every text/image/sound is converted into a vector — a list of numbers that captures its meaning.
For example:

TextVector (simplified)
1. "cat"[0.23, 0.64, -0.12]
2. "dog"[0.21, 0.61, -0.14]
3. "airplane"[-0.88, 0.02, 1.19]

Vectors that are closer together = more similar in meaning.

Let’s say you're building a:

  • 🛵 Delivery app?
  • 🧭 Travel guide?
  • 🍔 Restaurant finder?

You’ll eventually need one thing:

“Find places near me” – FAST and OFFLINE.

Let’s build that with ObjectBox, a lightning-fast local NoSQL DB — and yes, it works like a charm with Flutter!

vector database mobile local database applications

🧠 Goal: Store Location (Lat, Lng) and Query Nearby Places

🔧 Step 1: Set up ObjectBox in Flutter

Add these to pubspec.yaml:

dependencies:
  objectbox: ^4.1.0
  path_provider: ^2.0.15 #to create db in local application directory
  geolocator: ^11.1.0 # (Optional) for getting current location

Then run:

flutter pub get

Get Latest version From :

  1. https://pub.dev/packages/geolocator/install
  2. https://pub.dev/packages/objectbox/install


🏗 Step 2: Create Your Entity (Place with Latitude/Longitude)

import 'package:objectbox/objectbox.dart';

@Entity()
class Place {
  int id = 0;

  String name;

  // Float values for coordinates
  double latitude;
  double longitude;

  Place(this.name, this.latitude, this.longitude);
}

Boom 💥 You now have a Place object that can be stored locally.

Then add below dev dependencies,

dev_dependencies:
  build_runner: ^2.0.0
  objectbox_generator: ^4.1.0

Then run : (It will generate objectbox model files for our ENTITY)

flutter pub run build_runner build

📍 Step 3: Add Sample Places

    final docsDir = await getApplicationDocumentsDirectory();
    final Store store = openStore(directory: "${docsDir.path}/nearby_places_example/");
    final placeBox = store.box<Place>();

    final places = [
      Place("Coffee Club", 11.015, 76.963),
      Place("Park Central", 11.012, 76.961),
      Place("Green Garden", 11.018, 76.960),
      Place("Eiffel Tower", 48.858, 2.294),
      Place("Tokyo Tower", 35.689, 139.767),
      Place("Great Wall of China", 40.443, 116.576),
      Place("Acropolis of Athens", 37.979, 23.725),
      Place("Burj Khalifa", 25.197, 55.274),
    ];

    placeBox.putMany(places);
    store.close();

📡 Step 4: Get User’s Current Location or Mock for now.

import 'package:geolocator/geolocator.dart';

Position fakePositions() {
    double latitude = 11.0 + (0.01 * (0.5 - Random().nextDouble())); // Random latitude
    double longitude = 76.9 + (0.01 * (0.5 - Random().nextDouble())); // Random longitude

    return Position(
      latitude: latitude,
      longitude: longitude,
      timestamp: DateTime.now(),
      accuracy: 100, // Example accuracy in meters
      altitude: 0, // Example altitude
      heading: 0, // Example heading
      speed: 0, // Example speed
      speedAccuracy: 0,
      altitudeAccuracy: 80,
      headingAccuracy: 100, // Example speed accuracy
    );
  }

// Get current position
Position position = fakePositions();

Don't forget to give Location permission


📏 Step 5: Find Nearby Places (Simple Radius Filter)

Here’s how you do a rough search using Haversine formula:

double calculateDistance(lat1, lon1, lat2, lon2) {
  const p = 0.0174533; // Pi/180
  final a = 0.5 - 
    cos((lat2 - lat1) * p)/2 +
    cos(lat1 * p) * cos(lat2 * p) *
    (1 - cos((lon2 - lon1) * p))/2;

  return 12742 * asin(sqrt(a)); // Distance in km
}

Future<List<Place>> findNearbyPlaces(double radiusInKm) async {
  final position = fakePositions();
  final docsDir = await getApplicationDocumentsDirectory();
      final Store store = openStore(directory: "${docsDir.path}/nearby_places_example/");
      final placeBox = store.box<Place>();
      // This would involve using ObjectBox to query places near the current location
      final allPlaces = placeBox.getAll();

      const radiusInKm = 10;
      final placesList = allPlaces.where((place) {
        final distance = calculateDistance(
          position.latitude,
          position.longitude,
          place.latitude,
          place.longitude,
        );
        return distance <= radiusInKm;
      }).toList();
      store.close();
      return placesList;
}

⚡ Bonus Tip: Sort by Distance

List<Place> sortByNearest(Position current, List<Place> places) {
  places.sort((a, b) {
    final d1 = calculateDistance(current.latitude, current.longitude, a.latitude, a.longitude);
    final d2 = calculateDistance(current.latitude, current.longitude, b.latitude, b.longitude);
    return d1.compareTo(d2);
  });
  return places;
}

📲 Real App Use Case

Imagine the user opens your app and wants to find nearby:

  • 🍽 Restaurants within 2 km
  • 🏞 Parks within 5 km
  • 🧴 ATMs within 1 km

With this setup, your app:

✅ Works offline
✅ Loads data instantly
✅ Doesn’t hit a server every time
✅ Is easy to build on


🧪 Try This Challenge

Modify the Place entity to store a category (like "food", "park", "atm"), and let users filter by type and distance! 🚀


🚀 Final Thoughts

You don't always need Firebase or remote APIs for location search. With ObjectBox, you can build smart, fast, offline-first apps right inside Flutter.

💡 Coming Up Next:
In our upcoming blog, we’ll dive into the powerful built-in vector search capabilities of ObjectBox — and show you exactly how to use its blazing-fast nearestNeighbor feature to find similar items and recommendations in your Flutter app. 🔍⚡

Project source code github link - https://github.com/wh173d3v11/nearby_places_offline_flutter.git

Got questions? Just drop a comment! 👇
Happy building! 💙

Post a Comment

Link copied to clipboard!