Search code examples
pythondjangopostgisgeodjango

OSMWidget Django form location coodinates are incorrect


I have the following form field

point = gis_forms.PointField(widget=gis_forms.OSMWidget(
                            attrs={'map_width': 800,
                                   'map_srid': 4326,
                                   'map_height': 500,
                                   'default_lat': 49.246292,
                                   'default_lon'-123.116226,
                                   'default_zoom': 7,}))

The form is rendered in django as

<form method="post">
  {% csrf_token %}
  {{ form|crispy }}
  <button type="submit">Submit for Review</button>
</form>

But when the data comes in POST the locations are incorrect.

def register_storage(request):
    if request.method == 'POST':
        form = MyGeoForm(request.POST)
        if form.is_valid():
            data=form.cleaned_data
            print(data.get('point'))
            print(data.get('point').srid)

The SRID is showing up as 3857 and weird default coordinates -13645232.541356523 6283123.725041488

I thought it was my django version, but it is updated to 3.1.3 due to some functionality with GDAL. But no luck.

Very lost here.


Solution

  • You must explictly define the SRID in the form's field. I'm not sure why this is the case (you'd think it would default to 4326 like the rest of Django/GeoDjango), but that's the way it seems to be. Your code should read:

    point = gis_forms.PointField(
        srid=4326,
        widget=gis_forms.OSMWidget(
            attrs={
                "map_width": 800,
                "map_srid": 4326,
                "map_height": 500,
                "default_lat": 49.246292,
                "default_lon": -123.116226,
                "default_zoom": 7,
            }
        ),
    )