জিও প্রশ্ন

অনেক অ্যাপ্লিকেশানের নথি রয়েছে যা প্রকৃত অবস্থান দ্বারা সূচীকৃত। উদাহরণস্বরূপ, আপনার অ্যাপ ব্যবহারকারীদের তাদের বর্তমান অবস্থানের কাছাকাছি স্টোর ব্রাউজ করার অনুমতি দিতে পারে।

ক্লাউড ফায়ারস্টোর শুধুমাত্র প্রতি যৌগ ক্যোয়ারী প্রতি একটি একক পরিসরের ধারার অনুমতি দেয়, যার অর্থ আমরা কেবল অক্ষাংশ এবং দ্রাঘিমাংশকে পৃথক ক্ষেত্র হিসাবে সংরক্ষণ করে এবং একটি বাউন্ডিং বাক্স অনুসন্ধান করে জিও কোয়েরি সম্পাদন করতে পারি না।

সমাধান: জিওহ্যাশ

জিওহ্যাশ হল একটি (latitude, longitude) জোড়াকে একটি বেস 32 স্ট্রিংয়ে এনকোড করার একটি সিস্টেম। জিওহ্যাশ সিস্টেমে বিশ্ব একটি আয়তক্ষেত্রাকার গ্রিডে বিভক্ত। জিওহ্যাশ স্ট্রিংয়ের প্রতিটি অক্ষর প্রিফিক্স হ্যাশের 32টি উপবিভাগের একটি নির্দিষ্ট করে। উদাহরণস্বরূপ, Geohash abcd হল 32টি চার-অক্ষরের হ্যাশের মধ্যে একটি যা সম্পূর্ণরূপে বৃহত্তর জিওহ্যাশ abc এর মধ্যে রয়েছে।

দুটি হ্যাশের মধ্যে ভাগ করা উপসর্গ যত বেশি, তারা একে অপরের তত কাছাকাছি। উদাহরণস্বরূপ abcdef abcdff এর চেয়ে abcdeg এর কাছাকাছি। তবে কথোপকথন সত্য নয়! খুব আলাদা জিওহ্যাশ থাকার সময় দুটি ক্ষেত্র একে অপরের খুব কাছাকাছি হতে পারে:

জিওহ্যাশ অনেক দূরে

আমরা ক্লাউড ফায়ারস্টোরে অবস্থান অনুসারে নথিগুলি সঞ্চয় করতে এবং অনুসন্ধান করতে জিওহ্যাশ ব্যবহার করতে পারি যুক্তিসঙ্গত দক্ষতার সাথে যখন শুধুমাত্র একটি একক সূচীযুক্ত ক্ষেত্রের প্রয়োজন হয়৷

সহায়ক লাইব্রেরি ইনস্টল করুন

Geohashes তৈরি করা এবং পার্স করা কিছু জটিল গণিত জড়িত, তাই আমরা Android, Apple এবং ওয়েবের সবচেয়ে কঠিন অংশগুলিকে বিমূর্ত করার জন্য সহায়ক লাইব্রেরি তৈরি করেছি:

ওয়েব মডুলার API

// Install from NPM. If you prefer to use a static .js file visit
// https://github.com/firebase/geofire-js/releases and download
// geofire-common.min.js from the latest version
npm install --save geofire-common

ওয়েব নামস্থান API

// Install from NPM. If you prefer to use a static .js file visit
// https://github.com/firebase/geofire-js/releases and download
// geofire-common.min.js from the latest version
npm install --save geofire-common

সুইফট

দ্রষ্টব্য: এই পণ্যটি watchOS এবং অ্যাপ ক্লিপ লক্ষ্যে উপলব্ধ নয়।
// এটি আপনার পডফাইল পড 'জিওফায়ার/ইউটিলস'-এ যোগ করুন

Kotlin+KTX

// Add this to your app/build.gradle
implementation 'com.firebase:geofire-android-common:3.2.0'

Java

// Add this to your app/build.gradle
implementation 'com.firebase:geofire-android-common:3.1.0'

জিওহ্যাশ স্টোর করুন

প্রতিটি নথির জন্য আপনি অবস্থান অনুসারে সূচী করতে চান, আপনাকে একটি জিওহ্যাশ ক্ষেত্র সংরক্ষণ করতে হবে:

ওয়েব মডুলার API

import { doc, updateDoc } from 'firebase/firestore';

// Compute the GeoHash for a lat/lng point
const lat = 51.5074;
const lng = 0.1278;
const hash = geofire.geohashForLocation([lat, lng]);

// Add the hash and the lat/lng to the document. We will use the hash
// for queries and the lat/lng for distance comparisons.
const londonRef = doc(db, 'cities', 'LON');
await updateDoc(londonRef, {
  geohash: hash,
  lat: lat,
  lng: lng
});

ওয়েব নামস্থান API

// Compute the GeoHash for a lat/lng point
const lat = 51.5074;
const lng = 0.1278;
const hash = geofire.geohashForLocation([lat, lng]);

// Add the hash and the lat/lng to the document. We will use the hash
// for queries and the lat/lng for distance comparisons.
const londonRef = db.collection('cities').doc('LON');
londonRef.update({
  geohash: hash,
  lat: lat,
  lng: lng
}).then(() => {
  // ...
});

সুইফট

দ্রষ্টব্য: এই পণ্যটি watchOS এবং অ্যাপ ক্লিপ লক্ষ্যে উপলব্ধ নয়।
// Compute the GeoHash for a lat/lng point
let latitude = 51.5074
let longitude = 0.12780
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

let hash = GFUtils.geoHash(forLocation: location)

// Add the hash and the lat/lng to the document. We will use the hash
// for queries and the lat/lng for distance comparisons.
let documentData: [String: Any] = [
  "geohash": hash,
  "lat": latitude,
  "lng": longitude
]

let londonRef = db.collection("cities").document("LON")
londonRef.updateData(documentData) { error in
  // ...
}

Kotlin+KTX

// Compute the GeoHash for a lat/lng point
val lat = 51.5074
val lng = 0.1278
val hash = GeoFireUtils.getGeoHashForLocation(GeoLocation(lat, lng))

// Add the hash and the lat/lng to the document. We will use the hash
// for queries and the lat/lng for distance comparisons.
val updates: MutableMap<String, Any> = mutableMapOf(
    "geohash" to hash,
    "lat" to lat,
    "lng" to lng,
)
val londonRef = db.collection("cities").document("LON")
londonRef.update(updates)
    .addOnCompleteListener {
        // ...
    }

Java

// Compute the GeoHash for a lat/lng point
double lat = 51.5074;
double lng = 0.1278;
String hash = GeoFireUtils.getGeoHashForLocation(new GeoLocation(lat, lng));

// Add the hash and the lat/lng to the document. We will use the hash
// for queries and the lat/lng for distance comparisons.
Map<String, Object> updates = new HashMap<>();
updates.put("geohash", hash);
updates.put("lat", lat);
updates.put("lng", lng);

DocumentReference londonRef = db.collection("cities").document("LON");
londonRef.update(updates)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                // ...
            }
        });

জিওহ্যাশেস জিজ্ঞাসা করুন

জিওহ্যাশগুলি জিওহ্যাশ ক্ষেত্রের প্রশ্নের একটি সেটে যোগদান করে এবং তারপর কিছু মিথ্যা ইতিবাচক ফিল্টার করে আনুমানিক এলাকা কোয়েরি করার অনুমতি দেয়:

ওয়েব মডুলার API

import { collection, query, orderBy, startAt, endAt, getDocs } from 'firebase/firestore';

// Find cities within 50km of London
const center = [51.5074, 0.1278];
const radiusInM = 50 * 1000;

// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
const bounds = geofire.geohashQueryBounds(center, radiusInM);
const promises = [];
for (const b of bounds) {
  const q = query(
    collection(db, 'cities'), 
    orderBy('geohash'), 
    startAt(b[0]), 
    endAt(b[1]));

  promises.push(getDocs(q));
}

// Collect all the query results together into a single list
const snapshots = await Promise.all(promises);

const matchingDocs = [];
for (const snap of snapshots) {
  for (const doc of snap.docs) {
    const lat = doc.get('lat');
    const lng = doc.get('lng');

    // We have to filter out a few false positives due to GeoHash
    // accuracy, but most will match
    const distanceInKm = geofire.distanceBetween([lat, lng], center);
    const distanceInM = distanceInKm * 1000;
    if (distanceInM <= radiusInM) {
      matchingDocs.push(doc);
    }
  }
}

ওয়েব নামস্থান API

// Find cities within 50km of London
const center = [51.5074, 0.1278];
const radiusInM = 50 * 1000;

// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
const bounds = geofire.geohashQueryBounds(center, radiusInM);
const promises = [];
for (const b of bounds) {
  const q = db.collection('cities')
    .orderBy('geohash')
    .startAt(b[0])
    .endAt(b[1]);

  promises.push(q.get());
}

// Collect all the query results together into a single list
Promise.all(promises).then((snapshots) => {
  const matchingDocs = [];

  for (const snap of snapshots) {
    for (const doc of snap.docs) {
      const lat = doc.get('lat');
      const lng = doc.get('lng');

      // We have to filter out a few false positives due to GeoHash
      // accuracy, but most will match
      const distanceInKm = geofire.distanceBetween([lat, lng], center);
      const distanceInM = distanceInKm * 1000;
      if (distanceInM <= radiusInM) {
        matchingDocs.push(doc);
      }
    }
  }

  return matchingDocs;
}).then((matchingDocs) => {
  // Process the matching documents
  // ...
});

সুইফট

দ্রষ্টব্য: এই পণ্যটি watchOS এবং অ্যাপ ক্লিপ লক্ষ্যে উপলব্ধ নয়।
// Find cities within 50km of London
let center = CLLocationCoordinate2D(latitude: 51.5074, longitude: 0.1278)
let radiusInM: Double = 50 * 1000

// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
let queryBounds = GFUtils.queryBounds(forLocation: center,
                                      withRadius: radiusInM)
let queries = queryBounds.map { bound -> Query in
  return db.collection("cities")
    .order(by: "geohash")
    .start(at: [bound.startValue])
    .end(at: [bound.endValue])
}

@Sendable func fetchMatchingDocs(from query: Query,
                       center: CLLocationCoordinate2D,
                       radiusInMeters: Double) async throws -> [QueryDocumentSnapshot] {
  let snapshot = try await query.getDocuments()
  // Collect all the query results together into a single list
  return snapshot.documents.filter { document in
    let lat = document.data()["lat"] as? Double ?? 0
    let lng = document.data()["lng"] as? Double ?? 0
    let coordinates = CLLocation(latitude: lat, longitude: lng)
    let centerPoint = CLLocation(latitude: center.latitude, longitude: center.longitude)

    // We have to filter out a few false positives due to GeoHash accuracy, but
    // most will match
    let distance = GFUtils.distance(from: centerPoint, to: coordinates)
    return distance <= radiusInM
  }
}

// After all callbacks have executed, matchingDocs contains the result. Note that this code
// executes all queries serially, which may not be optimal for performance.
do {
  let matchingDocs = try await withThrowingTaskGroup(of: [QueryDocumentSnapshot].self) { group -> [QueryDocumentSnapshot] in
    for query in queries {
      group.addTask {
        try await fetchMatchingDocs(from: query, center: center, radiusInMeters: radiusInM)
      }
    }
    var matchingDocs = [QueryDocumentSnapshot]()
    for try await documents in group {
      matchingDocs.append(contentsOf: documents)
    }
    return matchingDocs
  }

  print("Docs matching geoquery: \(matchingDocs)")
} catch {
  print("Unable to fetch snapshot data. \(error)")
}

Kotlin+KTX

// Find cities within 50km of London
val center = GeoLocation(51.5074, 0.1278)
val radiusInM = 50.0 * 1000.0

// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
val bounds = GeoFireUtils.getGeoHashQueryBounds(center, radiusInM)
val tasks: MutableList<Task<QuerySnapshot>> = ArrayList()
for (b in bounds) {
    val q = db.collection("cities")
        .orderBy("geohash")
        .startAt(b.startHash)
        .endAt(b.endHash)
    tasks.add(q.get())
}

// Collect all the query results together into a single list
Tasks.whenAllComplete(tasks)
    .addOnCompleteListener {
        val matchingDocs: MutableList<DocumentSnapshot> = ArrayList()
        for (task in tasks) {
            val snap = task.result
            for (doc in snap!!.documents) {
                val lat = doc.getDouble("lat")!!
                val lng = doc.getDouble("lng")!!

                // We have to filter out a few false positives due to GeoHash
                // accuracy, but most will match
                val docLocation = GeoLocation(lat, lng)
                val distanceInM = GeoFireUtils.getDistanceBetween(docLocation, center)
                if (distanceInM <= radiusInM) {
                    matchingDocs.add(doc)
                }
            }
        }

        // matchingDocs contains the results
        // ...
    }

Java

// Find cities within 50km of London
final GeoLocation center = new GeoLocation(51.5074, 0.1278);
final double radiusInM = 50 * 1000;

// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
List<GeoQueryBounds> bounds = GeoFireUtils.getGeoHashQueryBounds(center, radiusInM);
final List<Task<QuerySnapshot>> tasks = new ArrayList<>();
for (GeoQueryBounds b : bounds) {
    Query q = db.collection("cities")
            .orderBy("geohash")
            .startAt(b.startHash)
            .endAt(b.endHash);

    tasks.add(q.get());
}

// Collect all the query results together into a single list
Tasks.whenAllComplete(tasks)
        .addOnCompleteListener(new OnCompleteListener<List<Task<?>>>() {
            @Override
            public void onComplete(@NonNull Task<List<Task<?>>> t) {
                List<DocumentSnapshot> matchingDocs = new ArrayList<>();

                for (Task<QuerySnapshot> task : tasks) {
                    QuerySnapshot snap = task.getResult();
                    for (DocumentSnapshot doc : snap.getDocuments()) {
                        double lat = doc.getDouble("lat");
                        double lng = doc.getDouble("lng");

                        // We have to filter out a few false positives due to GeoHash
                        // accuracy, but most will match
                        GeoLocation docLocation = new GeoLocation(lat, lng);
                        double distanceInM = GeoFireUtils.getDistanceBetween(docLocation, center);
                        if (distanceInM <= radiusInM) {
                            matchingDocs.add(doc);
                        }
                    }
                }

                // matchingDocs contains the results
                // ...
            }
        });

সীমাবদ্ধতা

অবস্থান অনুসন্ধানের জন্য জিওহ্যাশ ব্যবহার করা আমাদের নতুন ক্ষমতা দেয়, তবে এর নিজস্ব সীমাবদ্ধতার সাথে আসে:

  • মিথ্যা ইতিবাচক - জিওহ্যাশ দ্বারা অনুসন্ধান করা সঠিক নয়, এবং আপনাকে ক্লায়েন্টের দিকে মিথ্যা-ইতিবাচক ফলাফলগুলি ফিল্টার করতে হবে। এই অতিরিক্ত পাঠগুলি আপনার অ্যাপে খরচ এবং বিলম্বিত করে।
  • এজ কেস - এই ক্যোয়ারী পদ্ধতি দ্রাঘিমাংশ/অক্ষাংশের লাইনের মধ্যে দূরত্ব অনুমান করার উপর নির্ভর করে। এই অনুমানটির যথার্থতা হ্রাস পায় কারণ বিন্দু উত্তর বা দক্ষিণ মেরুর কাছাকাছি আসে যার অর্থ জিওহ্যাশ কোয়েরির চরম অক্ষাংশে বেশি মিথ্যা ইতিবাচক থাকে।