Django model field that can hold a geoposition, and corresponding widget

Overview

django-geoposition

A model field that can hold a geoposition (latitude/longitude), and corresponding admin/form widget.

https://travis-ci.org/philippbosch/django-geoposition.svg?branch=master Join the chat at https://gitter.im/philippbosch/django-geoposition

Prerequisites

Starting with version 0.3, django-geoposition requires Django 1.8 or greater. If you need to support Django versions prior to 1.8 please use django-geoposition 0.2.3. For Django versions prior to 1.4.10 please use django-geoposition 0.1.5.

Installation

  • Use your favorite Python packaging tool to install geoposition from PyPI, e.g.:

    pip install django-geoposition
    
  • Add "geoposition" to your INSTALLED_APPS setting:

    INSTALLED_APPS = (
        # …
        "geoposition",
    )
    
  • Set your Google API key in you settings file:

    GEOPOSITION_GOOGLE_MAPS_API_KEY = 'YOUR_API_KEY'
    

    API keys may be obtained here: https://developers.google.com/maps/documentation/javascript/get-api-key

  • If you are still using Django <1.3, you are advised to install django-staticfiles for static file serving.

Usage

django-geoposition comes with a model field that makes it pretty easy to add a geoposition field to one of your models. To make use of it:

  • In your myapp/models.py:

    from django.db import models
    from geoposition.fields import GeopositionField
    
    class PointOfInterest(models.Model):
        name = models.CharField(max_length=100)
        position = GeopositionField()
    
  • This enables the following simple API:

    >>> from myapp.models import PointOfInterest
    >>> poi = PointOfInterest.objects.get(id=1)
    >>> poi.position
    Geoposition(52.522906,13.41156)
    >>> poi.position.latitude
    52.522906
    >>> poi.position.longitude
    13.41156
    

Form field and widget

Admin

If you use a GeopositionField in the admin it will automatically show a Google Maps widget with a marker at the currently stored position. You can drag and drop the marker with the mouse and the corresponding latitude and longitude fields will be updated accordingly.

It looks like this:

geoposition-widget-admin

Regular Forms

Using the map widget on a regular form outside of the admin requires just a little more work. In your template make sure that

  • jQuery is included
  • the static files (JS, CSS) of the map widget are included (just use {{ form.media }})

Example:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<form method="POST" action="">{% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}
</form>

Settings

You can customize the MapOptions and MarkerOptions used to initialize the map and marker in JavaScript by defining GEOPOSITION_MAP_OPTIONS or GEOPOSITION_MARKER_OPTIONS in your settings.py.

Example:

GEOPOSITION_MAP_OPTIONS = {
    'minZoom': 3,
    'maxZoom': 15,
}

GEOPOSITION_MARKER_OPTIONS = {
    'cursor': 'move'
}

Please note that you cannot use a value like new google.maps.LatLng(52.5,13.4) for a setting like center or position because that would end up as a string in the JavaScript code and not be evaluated. Please use Lat/Lng Object Literals for that purpose, e.g. {'lat': 52.5, 'lng': 13.4}.

You can also customize the height of the displayed map widget by setting GEOPOSITION_MAP_WIDGET_HEIGHT to an integer value (default is 480).

License

MIT

Comments
  • inline admin GeoPosition not rendering the map unless you resize the browser window

    inline admin GeoPosition not rendering the map unless you resize the browser window

    screen shot 2016-07-23 at 2 37 19 pm

    When I use a geoposition as an inline admin the map does not render until you resize the browser. It just is grey but you can see the red location marker. It works normally as a stand alone admin component.

    Any idea whats causing this?

    opened by imran31415 14
  • Request support on Django2

    Request support on Django2

    Hi Your package is great! In order to fasten your upgrade process I will post my problem when first contact with Django2

    Traceback (most recent call last):
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
        response = get_response(request)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/Users/sarit/.pyenv/versions/3.6.4/lib/python3.6/contextlib.py", line 52, in inner
        return func(*args, **kwds)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
        return view_func(*args, **kwargs)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view
        return self.dispatch(request, *args, **kwargs)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch
        response = self.handle_exception(exc)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception
        self.raise_uncaught_exception(exc)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch
        response = handler(request, *args, **kwargs)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/mixins.py", line 22, in create
        headers = self.get_success_headers(serializer.data)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 537, in data
        ret = super(Serializer, self).data
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
        self._data = self.to_representation(self.instance)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 504, in to_representation
        ret[field.field_name] = field.to_representation(attribute)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/fields.py", line 1858, in to_representation
        return self.model_field.value_to_string(obj)
      File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/src/django-geoposition/geoposition/fields.py", line 50, in value_to_string
        value = self._get_val_from_obj(obj)
    AttributeError: 'GeopositionField' object has no attribute '_get_val_from_obj'
    
    opened by elcolie 8
  • Add Google API Key

    Add Google API Key

    Google has shut down keyless use of the Maps API on June 22nd. This breaks the app. The key should be set in the django settings file(s) and then read by the app.

    opened by rgeber 5
  • GeopositionField returns string instead of Geoposition() after loaddata with python 3.4

    GeopositionField returns string instead of Geoposition() after loaddata with python 3.4

    Hi,

    I dumped my models with python 2.7 and loaded them on a different django install with python 3.4. after loaddata geoposition returns a string instead of a Geoposition object:

    on python 2.7:

    >>> model.position
    Geoposition(45.4855921,9.2202867)
    >>> model.position.latitude
    Decimal('45.4855921')
    >>> model.position.longitude
    Decimal('9.2202867')
    

    on python 3.4:

    >>> model.position
    '45.4906771,9.16936499999997'
    >>> model.position.latitude
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
    AttributeError: 'str' object has no attribute 'latitude'
    >>> model.position.longitude
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
    AttributeError: 'str' object has no attribute 'longitude'
    

    This obviously breaks code elsewhere in my app relying on Geoposition to be returned.

    opened by lucacorti 5
  • Possibility to use django-geoposition with geodjango

    Possibility to use django-geoposition with geodjango

    It would be really nice if geoposition worked with django's build-in PointField() model field type, instead of requiring you to use its own GeopositionField().

    opened by hakanw 4
  • Improve the search widget in admin

    Improve the search widget in admin

    I made the search widget show the autosuggestion a short delay after typing ends, and also moved it up above the map to the top left because I found that some admin users missed it under the map.

    skarmavbild 2013-11-29 kl 14 10 17

    opened by hakanw 3
  • Map is not loaded correctly in a regular form

    Map is not loaded correctly in a regular form

    I'm using a Geoposition field on a model, and when the form is displayed, the gmap loads, but is not fully displayed, the zoom is bad rendered, also the mark.

    map

    opened by marcosalcazar 3
  • admin inlines empty 'extra' form creates an object

    admin inlines empty 'extra' form creates an object

    When using in admin inlines, 'extra' form creates an object (with 0,0 coordinates) even if it's fields nor the map were touched. Setting field's default='0,0' does not help. Also, it would be great to make the field/widget respect the default value.

    opened by mikek 3
  • Only works in Admin due to jQuery.noConflict(true)

    Only works in Admin due to jQuery.noConflict(true)

    django-geolocation assumes jQuery to be in the namespace django which is true for admin only. Most of the sites use jQuery as is in the frontend thus the map widget is not displayed.

    opened by owais 3
  • django.utils.six no longer included (django 3)

    django.utils.six no longer included (django 3)

    Just installed according to the instructions on django version 3, and since django.utils.six is no longer included, I got this exception when running from geoposition.fields import GeopositionField:

    Exception in thread django-main-thread:
    Traceback (most recent call last):
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner
        self.run()
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run
        self._target(*self._args, **self._kwargs)
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
        fn(*args, **kwargs)
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
        autoreload.raise_last_exception()
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception
        raise _exception[1]
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute
        autoreload.check_errors(django.setup)()
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
        fn(*args, **kwargs)
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
        apps.populate(settings.INSTALLED_APPS)
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate
        app_config.import_models()
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models
        self.models_module = import_module(models_module_name)
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
      File "<frozen importlib._bootstrap>", line 991, in _find_and_load
      File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 783, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "/Users/kallewesterling/Google Drive/Dropbox (snapshot)/dev/dev-dissertation/dissertation-website/eimadataset/models.py", line 2, in <module>
        from geoposition.fields import GeopositionField
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/geoposition/fields.py", line 4, in <module>
        from django.utils.six import with_metaclass
    ModuleNotFoundError: No module named 'django.utils.six'
    
    
    opened by kallewesterling 2
  • Does this ONLY work with Google Maps?

    Does this ONLY work with Google Maps?

    My client doesn't want to have to pay for every map generated. Can you update the tutorial for a different service, or if that's impossible with this codebase, any suggestions would be appreciated.

    opened by ursomniac 2
  • Django-geoposition still does not support Python 3

    Django-geoposition still does not support Python 3

    I continue to get the ModuleNotFoundError when I import the Geoposition class. Error details are below:

    from geoposition.fields import GeopositionField
      File "C:\Users\MKEDONKOR\.virtualenvs\DjangoTracker-ItodlCVG\lib\site-packages\geoposition\fields.py", line 4, in <module>
        from django.utils.six import with_metaclass
    ModuleNotFoundError: No module named 'django.utils.six'
    

    I understand @xangcastle and @waseem-omar have made some pull requests and requested to merge, but nothing has been done about it. At least can you implement support for Django 3.2 and Python 3.9?

    opened by enoch-prince 0
  • 'GeopositionField' object has no attribute '_get_val_from_obj

    'GeopositionField' object has no attribute '_get_val_from_obj

    https://github.com/philippbosch/django-geoposition/blob/b68382b408deb1f9bf62b65050a19fd3cedba775/geoposition/fields.py#L50

    When trying to execute dumpdata command CommandError: Unable to serialize database: 'GeopositionField' object has no attribute '_get_val_from_obj'

    opened by iforvard 0
  • Is this project alive?

    Is this project alive?

    Hello!

    I am using your project and trying to upgrade the main version of Django (3.0.x). But your project does not support it. Do you have plans to make any changes to support the new version? Maybe I should prepare a PR?

    Thanks!

    opened by mcproger 5
A GUI widget for Linux to show current time in different timezones.

A GUI widget to show current time in different timezones (under development). To use this widget: Run scripts/startup.py Select a country. A list of t

B.Jothin kumar 11 Nov 10, 2022
A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Django Countries A Django application that provides country choices for use with forms, flag icons static files, and a country field for models. Insta

Chris Beaven 1.2k Jan 3, 2023
Using Global fishing watch's data to build a machine learning model that can identify illegal fishing and poaching activities through satellite and geo-location data.

Using Global fishing watch's data to build a machine learning model that can identify illegal fishing and poaching activities through satellite and geo-location data.

Ayush Mishra 3 May 6, 2022
Hapi is a Python library for building Conceptual Distributed Model using HBV96 lumped model & Muskingum routing method

Current build status All platforms: Current release info Name Downloads Version Platforms Hapi - Hydrological library for Python Hapi is an open-sourc

Mostafa Farrag 15 Dec 26, 2022
This app displays interesting statistical weather records and trends which can be used in climate related research including study of global warming.

This app displays interesting statistical weather records and trends which can be used in climate related research including study of global warming.

null 0 Dec 27, 2021
OSMnx: Python for street networks. Retrieve, model, analyze, and visualize street networks and other spatial data from OpenStreetMap.

OSMnx OSMnx is a Python package that lets you download geospatial data from OpenStreetMap and model, project, visualize, and analyze real-world street

Geoff Boeing 4k Jan 8, 2023
A short term landscape evolution using a path sampling method to solve water and sediment flow continuity equations and model mass flows over complex topographies.

r.sim.terrain A short-term landscape evolution model that simulates topographic change for both steady state and dynamic flow regimes across a range o

Brendan Harmon 7 Oct 21, 2022
Python script that can be used to generate latitude/longitude coordinates for GOES-16 full-disk extent.

goes-latlon Python script that can be used to generate latitude/longitude coordinates for GOES-16 full-disk extent. ?? ??️ The grid files can be acces

Douglas Uba 3 Apr 6, 2022
Geodata extensions for Django REST Framework

Django-Spillway Django and Django REST Framework integration of raster and feature based geodata. Spillway builds on the immensely marvelous Django RE

Brian Galey 62 Jan 4, 2023
Geographic add-ons for Django REST Framework. Maintained by the OpenWISP Project.

django-rest-framework-gis Geographic add-ons for Django Rest Framework - Mailing List. Install last stable version from pypi pip install djangorestfra

OpenWISP 981 Jan 3, 2023
Geographic add-ons for Django REST Framework. Maintained by the OpenWISP Project.

Geographic add-ons for Django REST Framework. Maintained by the OpenWISP Project.

OpenWISP 982 Jan 6, 2023
Yet Another Time Series Model

Yet Another Timeseries Model (YATSM) master v0.6.x-maintenance Build Coverage Docs DOI | About Yet Another Timeseries Model (YATSM) is a Python packag

Chris Holden 60 Sep 13, 2022
glTF to 3d Tiles Converter. Convert glTF model to Glb, b3dm or 3d tiles format.

gltf-to-3d-tiles glTF to 3d Tiles Converter. Convert glTF model to Glb, b3dm or 3d tiles format. Usage λ python main.py --help Usage: main.py [OPTION

null 58 Dec 27, 2022
ESMAC diags - Earth System Model Aerosol-Cloud Diagnostics Package

Earth System Model Aerosol-Cloud Diagnostics Package This Earth System Model (ES

Pacific Northwest National Laboratory 1 Jan 4, 2022
Read and write rasters in parallel using Rasterio and Dask

dask-rasterio dask-rasterio provides some methods for reading and writing rasters in parallel using Rasterio and Dask arrays. Usage Read a multiband r

Dymaxion Labs 85 Aug 30, 2022
Deal with Bing Maps Tiles and Pixels / WGS 84 coordinates conversions, and generate grid Shapefiles

PyBingTiles This is a small toolkit in order to deal with Bing Tiles, used i.e. by Facebook for their Data for Good datasets. Install Clone this repos

Shoichi 1 Dec 8, 2021
This repository contains the scripts to derivate the ENU and ECEF coordinates from the longitude, latitude, and altitude values encoded in the NAD83 coordinates.

This repository contains the scripts to derivate the ENU and ECEF coordinates from the longitude, latitude, and altitude values encoded in the NAD83 coordinates.

Luigi Cruz 1 Feb 7, 2022
Python bindings and utilities for GeoJSON

geojson This Python library contains: Functions for encoding and decoding GeoJSON formatted data Classes for all GeoJSON Objects An implementation of

Jazzband 765 Jan 6, 2023
Manipulation and analysis of geometric objects

Shapely Manipulation and analysis of geometric objects in the Cartesian plane. Shapely is a BSD-licensed Python package for manipulation and analysis

null 3.1k Jan 3, 2023