Which Model Field to use in Django to store longitude and latitude values?

PythonDjangoGeodjango

Python Problem Overview


I want to store my users location using longitude and latitude, at the moment this comes from Google Maps, but I will be using GeoDango and some point to work out distances between to points also.

However, my first confusion is which field in Django I should be using to store the longitude and latitude values? The information I'm getting is conflicting.

The official documentation uses a FloatField https://docs.djangoproject.com/en/dev/ref/contrib/gis/tutorial/#geographic-models

lon = models.FloatField()
lat = models.FloatField()

Where almost every answer on stackoverflow shows a DecimalField

long = models.DecimalField(max_digits=8, decimal_places=3)
lat = models.DecimalField(max_digits=8, decimal_places=3)

So what should I be using?

Python Solutions


Solution 1 - Python

Float is generally an approximation, see here for some simple examples. You could get very nice results modifying your model to something like DecimalField(max_digits=9, decimal_places=6), since decimals are very important in coordinates but using more than 6 is basically meaningless.

Solution 2 - Python

Solution 3 - Python

The suggestion here to use DecimalField(max_digits=9, decimal_places=6) resulted in errors for me when trying to save locations from Google Maps.

If we assume that the most common use case is retrieving point locations from the Maps API, and a typical URL from Google Maps when right-clicking and selecting "What's Here?" yields something like:

https://www.google.com/maps/place/37°48'52.3"N+122°17'09.1"W/@37.814532,-122.2880467,17z

(random place)

So the longitude has 15 places before and after the decimal, which is why the accepted answer doesn't work. Since there's no reason to validate for "as short as possible" and db storage is cheap, I'm using:

    max_digits=22,
    decimal_places=16)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrometheusView Question on Stackoverflow
Solution 1 - PythonmcccView Answer on Stackoverflow
Solution 2 - PythonAmulya AcharyaView Answer on Stackoverflow
Solution 3 - PythonshackerView Answer on Stackoverflow