pythonfirebasegoogle-cloud-firestoregeopoints

How to read firestore GeoPoint in python script?


I am writing a Python script to read Firebase Firestore data. Somehow documentSnapshop.to_dict() was not working for me. So, I have written a class by referring to https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/firestore/cloud-client/snippets.py#L103 this resource.

In my case, there is the location of the city stored as the GeoPoint firestore field. I am not able to get it in the dictionary. How can we add GeoPoint location in the City class mentioned in the reference example mentioned above?


Solution

  • Assuming that the GeoLocation property is named location, you should just add it like:

    class City(object):
        def __init__(self, name, state, country, capital=False, population=0,
                     regions=[], location):
            self.name = name
            self.state = state
            self.country = country
            self.capital = capital
            self.population = population
            self.regions = regions
            self.location = location
    

    Then, when getting data from the DB, you could set the location property like this:

    source = db.collection(u'collection').document(u'docId').get().to_dict()
    city = City(source[u'name'], source[u'state'], source[u'country'], source[u'country'], source[u'location'])
    

    If you wanted to fetch the latitude or longitude, you could do so with the following code:

    city.location.latitude
    city.location.longitude