Location field and widget for Django. It supports Google Maps, OpenStreetMap and Mapbox

Overview

logo

django-location-field

Let users pick locations using a map widget and store its latitude and longitude.

Stable version: django-location-field==2.1.0
Documentation: https://django-location-field.readthedocs.io/en/latest/
License: MIT

Status

Build Status Documentation Status Say Thanks!

Tests are performed with Python 2 and 3, Django 1.11 and 2, and SpatiaLite.

Features

  • Support for multiple map engines, like Google Maps, OpenStreetMap and Mapbox.
  • Support for multiple search engines, like Google, Nominatim, Yandex and Addok.
  • Works with both Spatial and non-Spatial databases.

Compatibility

  • Django >= 1.11
  • Python 2.7, 3.6, 3.7

Spatial Databases

  • PostGIS
  • SpatiaLite

Installation

  1. Install through pip (or manually place it on your PYTHONPATH).

    pip install django-location-field

  2. Add location_field.apps.DefaultConfig to INSTALLED_APPS your settings.py file

For example, PostGIS:

https://docs.djangoproject.com/en/dev/ref/contrib/gis/install/postgis/

Basic usage (using Spatial Database)

from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from location_field.models.spatial import LocationField

class Place(models.Model):
    city = models.CharField(max_length=255)
    location = LocationField(based_fields=['city'], zoom=7, default=Point(1.0, 1.0))

Basic usage (without Spatial Database)

from django.db import models
from location_field.models.plain import PlainLocationField

class Place(models.Model):
    city = models.CharField(max_length=255)
    location = PlainLocationField(based_fields=['city'], zoom=7)

Screenshot

Screenshot


Nick Frost has credit over the image used as logo for this project. CC BY

Comments
  • the map does not appear

    the map does not appear

    Hi, since 3 days ago the map does not appear, and it does not throw me any errors in the google chrome console, any idea or where find error?

    Django version 2.1.1, using settings 'mywebsite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [19/Nov/2018 21:39:41] "GET /static/admin/css/dashboard.css HTTP/1.1" 200 412 [19/Nov/2018 21:39:41] "GET /static/admin/img/icon-changelink.svg HTTP/1.1" 200 380 [19/Nov/2018 21:39:41] "GET /static/admin/img/icon-addlink.svg HTTP/1.1" 200 331 Not Found: /robots.txt [2018-11-19 21:39:42,142] log: WARNING - Not Found: /robots.txt [19/Nov/2018 21:39:42] "GET /robots.txt HTTP/1.1" 404 4172 [19/Nov/2018 21:39:42] "GET /admin/ HTTP/1.1" 200 16892 [19/Nov/2018 21:39:46] "GET /admin/dlf_app/place/add/ HTTP/1.1" 200 10300 [19/Nov/2018 21:39:46] "GET /static/admin/js/inlines.js HTTP/1.1" 200 13813 [19/Nov/2018 21:39:46] "GET /static/location_field/js/form.js HTTP/1.1" 200 19650 [19/Nov/2018 21:39:46] "GET /admin/jsi18n/ HTTP/1.1" 200 7047 [19/Nov/2018 21:40:16] "GET /static/admin/img/inline-delete.svg HTTP/1.1" 200 560

    captura de pantalla 2018-11-19 a la s 21 45 11
    opened by CARocha 15
  • Browser autocomplete creates incorrect point

    Browser autocomplete creates incorrect point

    Hi Team, thanks for creating a cool app.

    I have found an issue recently where if browser autocomplete is used then the location field point is incorrect.

    screenshot - good point created on typing typing in - address works

    screenshot - bad point created on autocomplete (Note: the fields in yellow were the browser autocomplete fields) autocomplete - address does not work

    I have <form ... autocomplete="off">... but a lot of browsers ignore this anyway.

    Thanks for your assistance in advance.

    opened by lukeaus 12
  • Issue when upgrade to 2.0.1

    Issue when upgrade to 2.0.1

    I just upgraded the library from 1.6 and got this error:

    'Settings' object has no attribute 'LOCATION_FIELD'

    Seems is not taking the default value since I don't have any LOCATION_FIELD setting.

    opened by camilonova 7
  • Missing leaflet static files causing errors with ManifestStaticFilesStorage

    Missing leaflet static files causing errors with ManifestStaticFilesStorage

    When you're using the ManifestStaticFilesStorage, collectstatic fails because it can't find two files. Namely:

    • location_field/images/layers.png
    • location_field/images/layers-2x.png

    The solution would be either to remove those lines from leaflet.css or include the images with the package.

    Here's a relevant issue: https://github.com/evansd/whitenoise/issues/96

    opened by mixxorz 7
  • install_requires shouldn't reference Django itself

    install_requires shouldn't reference Django itself

    Currently pip installing django-location-field downgrades Django itself:

    $ pip install django-location-field
    Installing collected packages: Django, django-location-field
      Found existing installation: Django 1.9.2
        Uninstalling Django-1.9.2:
          Successfully uninstalled Django-1.9.2
    Successfully installed Django-1.8.9 django-location-field-1.6.1
    

    Even if django-location-field really doesn't work on Django 1.9 this is still surprising behaviour. See similar discussions:

    https://github.com/charettes/django-admin-enhancer/issues/23

    https://github.com/carljm/django-model-utils/issues/183

    (yeah - it's me each time ;-) )

    opened by andybak 7
  • How to load static files?

    How to load static files?

    I'm sure I'm missing the obvious here. My form displays a blank space where the map should go, essentially because the static files do not get loaded (or referenced for that matter) in my template. How should I link them? How should I configure the static files?

    opened by JoseTomasTocino 6
  • max_length error

    max_length error

    Django 1.9.1

    from location_field.models.plain import PlainLocationField
    ...
    city = models.ForeignKey(City, blank=True, null=True)
    region = models.ForeignKey(Region, blank=True, null=True)
    location = PlainLocationField('place',
                                 based_fields=['city'],
                                 zoom=7
                                 )
    

    When I try to makemigrations I'm got:

    ERRORS:
    trips.TripExpence.location: (fields.E121) 'max_length' must be a positive integer.
    

    Second question: Name of city defined in another model and linked through ForeignKey. Is this will work?

    And third: Can I set the place for location field using both entites: city and region?

    opened by Guest007 6
  • location field map not working with bootstrap 4 modal

    location field map not working with bootstrap 4 modal

    HI all,

    I am using the forms inside a bootstrap 4 modal. The Map is not render in the modal.

    Example code:

    <html>
        <head>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
            <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
            {{form.media}}
        </head>
        <body>
         <div class="modal fade" id="modal1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                                {% for f in  form %}
                                    <label for="{{ f.auto_id }}" class="bmd-label-static">{{ f.label }}</label>
                                    {{ f }}
                                {% endfor %}
                </div></div></div>
        </body>
    <script>
            $(document).ready(function (){
                $('#modal1').modal()
            })
        </script>
    </html>
    

    this code work:

    <html>
        <head>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
            <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
            {{form.media}}
        </head>
        <body>
             {% for f in  form %}
                  <label for="{{ f.auto_id }}" class="bmd-label-static">{{ f.label }}</label>
                  {{ f }}
             {% endfor %}
        </body>
    </html>
    

    I appreciate if you can help me solve this.

    opened by Esteban108 5
  • Map is not rendering

    Map is not rendering

    When opening change form in admin map is blank. image After changing city it's refreshed and renders correctly, after saving model it works correctly, problem exists only when opening model that wasn't edited through admin (it was imported). Dragging map or changing location field don't help.

    I'm using postgis, and from location_field.models.spatial import LocationField Tested in django 2.2 and 1.10, with django-location-field==2.1.0

    opened by Alexander3 5
  • Not compatible with Django 2.1

    Not compatible with Django 2.1

    I did a basic install and added a PlainLocationField to my model, and now the admin crashes with:

    TypeError: render() got an unexpected keyword argument 'renderer'
    

    It seems on the Django side it is calling:

    widget.render(
                name=self.html_initial_name if only_initial else self.html_name,
                value=self.value(),
                attrs=attrs,
                renderer=self.form.renderer,
            )
    

    But the LocationWidget doesn't accept renderer as a keyword argument.

    opened by carlmjohnson 5
  • Allow blank value for LocationField

    Allow blank value for LocationField

    Environment details

    Python version: 2.7.3 Django version: 1.5.1 Django Location Field version: 84718c64e039c4ca2974b62e220b60b6db74cf12 (latest master checkout)

    Problem

    Currently the form explodes (both on validation and on rendering of the the field value) if you set field blank attribute to True, leave the value empty and save the model.

    return func(*args, **kwargs)
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 989, in add_view
        if form.is_valid():
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 126, in is_valid
        return self.is_bound and not bool(self.errors)
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 117, in _get_errors
        self.full_clean()
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 272, in full_clean
        self._clean_fields()
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 287, in _clean_fields
        value = field.clean(value)
      File "/home/vagrant/.virtualenvs/foo/src/location-field/location_field/forms.py", line 32, in clean
        lat, lng = value.split(',')
    ValueError: need more than 1 value to unpack
    
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/template/base.py", line 830, in render
        bit = self.render_node(node, context)
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/template/debug.py", line 74, in render_node
        return node.render(context)
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/template/debug.py", line 87, in render
        output = force_text(output)
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/utils/encoding.py", line 99, in force_text
        s = s.__unicode__()
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 411, in __str__
        return self.as_widget()
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 458, in as_widget
        return widget.render(name, self.value(), attrs=attrs)
      File "/home/vagrant/.virtualenvs/foo/src/location-field/location_field/widgets.py", line 14, in render
        lat, lng = value.split(',')
    ValueError: need more than 1 value to unpack
    

    This pull request fixes this and allows a blank value.

    bug 
    opened by Kami 5
  • Mapbox doesn't work as map provider

    Mapbox doesn't work as map provider

    Mapbox doesn't work as map provider since they deprecated classic styles: https://blog.mapbox.com/deprecating-studio-classic-styles-d8892ac38cb4 When I try to load map at the django admin panel, the map doesn't render correctly. Response to the request is: {"message":"Classic styles are no longer supported; see https://blog.mapbox.com/deprecating-studio-classic-styles-d8892ac38cb4 for more information"}

    opened by parkhomchukp 0
  • How to update map marker with current location on the map

    How to update map marker with current location on the map

    Good day,

    We are using the library with this configuration

    LOCATION_FIELD = {
        "map.provider": "openstreetmap",
        "search.provider": "nominatim",
    }
    

    The model is using a PlainLocationField.

    We need to allow the users to use their current location in the map. For this, we implemented this little script

      function getLocation() {
        if ("geolocation" in navigator) {
          navigator.geolocation.getCurrentPosition(showPosition, error);
        } else {
          $("#location-message").show()
        }
      }
      function showPosition(position) {
        $("#id_location").val(position.coords.latitude + "," + position.coords.longitude)
      }
      function error(err) {
        $("#location-message").show()
      }
    

    it is working fine, the latitude and longitude is automatically updated; however, the marker is not. How may we force the marker to move to the new coordinates?

    We tried editing the coordinates directly and it is not working either; it seems that the marker updates the coordinates field but it does not work in the other way.

    Thank you,

    opened by jlariza 0
  • LocationField throws AttributeError because value is always None

    LocationField throws AttributeError because value is always None

    Hello there. I have a strange behaviour with the LocationField in my forms.py. I guess i do something wrong, but have no idea what it is (maybe the problem is that i use crispy-forms?)

    I have a Spatial LocationField in my model and added it also to my Create-Form.

    forms.py

    from location_field.forms.spatial import LocationField
    
    class SomeCreateForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['location'].initial = "2.0,2.0"
    
            self.helper = FormHelper()
            self.helper.form_tag = False
            self.helper.layout = Layout(
               ...
                LocationField("location"),
                ...
                Submit("create", "Create", css_class="some_class"),
            )
    
        class Meta:
            model = Place
            fields = (..., 'location', ...)
    

    Problem:

    When LocationField.clean() is called, the value is always None, which leads to a AttributeError. The initial-value gets propagated to self.initial in my case.

    class LocationField(PlainLocationField):
        def clean(self, value):
            try:
                lat, lng = value.split(',')
                return Point(float(lng), float(lat))
            except ValueError:
                return None
    

    So as a workaround i created a costum MyLocationField() where i add the initial value directly into the .clean() function. I am looking forward to any kind of help or advice here. Thank you!

    opened by daMichaelB 0
Owner
Caio Ariede
Caio Ariede
A bot that tweets info and location map for new bicycle parking added to OpenStreetMap within a GeoJSON boundary.

Bike parking tweepy bot app A twitter bot app that searches for bicycle parking added to OpenStreetMap. Relies on AWS Lambda/S3, Python3, Tweepy, Flas

Angelo Trivisonno 1 Dec 19, 2021
prettymaps - A minimal Python library to draw customized maps from OpenStreetMap data.

A small set of Python functions to draw pretty maps from OpenStreetMap data. Based on osmnx, matplotlib and shapely libraries.

Marcelo de Oliveira Rosa Prates 9k Jan 8, 2023
Use Mapbox GL JS to visualize data in a Python Jupyter notebook

Location Data Visualization library for Jupyter Notebooks Library documentation at https://mapbox-mapboxgl-jupyter.readthedocs-hosted.com/en/latest/.

Mapbox 620 Dec 15, 2022
Calculate the area inside of any GeoJSON geometry. This is a port of Mapbox's geojson-area for Python

geojson-area Calculate the area inside of any GeoJSON geometry. This is a port of Mapbox's geojson-area for Python. Installation $ pip install area U

Alireza 87 Dec 14, 2022
Example of animated maps in matplotlib + geopandas using entire time series of congressional district maps from UCLA archive. rendered, interactive version below

Example of animated maps in matplotlib + geopandas using entire time series of congressional district maps from UCLA archive. rendered, interactive version below

Apoorva Lal 5 May 18, 2022
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
Tools for the extraction of OpenStreetMap street network data

OSMnet Tools for the extraction of OpenStreetMap (OSM) street network data. Intended to be used in tandem with Pandana and UrbanAccess libraries to ex

Urban Data Science Toolkit 47 Sep 21, 2022
A library to access OpenStreetMap related services

OSMPythonTools The python package OSMPythonTools provides easy access to OpenStreetMap (OSM) related services, among them an Overpass endpoint, Nomina

Franz-Benjamin Mocnik 342 Dec 31, 2022
Python renderer for OpenStreetMap with custom icons intended to display as many map features as possible

Map Machine project consists of Python OpenStreetMap renderer: SVG map generation, SVG and PNG tile generation, Röntgen icon set: unique CC-BY 4.0 map

Sergey Vartanov 0 Dec 18, 2022
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
Google maps for Jupyter notebooks

gmaps gmaps is a plugin for including interactive Google maps in the IPython Notebook. Let's plot a heatmap of taxi pickups in San Francisco: import g

Pascal Bugnion 747 Dec 19, 2022
Google Maps keeps old satellite imagery around for a while – this tool collects what's available for a user-specified region in the form of a GIF.

google-maps-at-88-mph The folks maintaining Google Maps regularly update the satellite imagery it serves its users, but outdated versions of the image

Noah Doersing 111 Sep 27, 2022
Implemented a Google Maps prototype that provides the shortest route in terms of distance

Implemented a Google Maps prototype that provides the shortest route in terms of distance, the fastest route, the route with the fewest turns, and a scenic route that avoids roads when provided a source and destination. The algorithms used were DFS, BFS, A*, and Iterative Depth First Search.

null 1 Dec 26, 2021
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
A simple python script that, given a location and a date, uses the Nasa Earth API to show a photo taken by the Landsat 8 satellite. The script must be executed on the command-line.

What does it do? Given a location and a date, it uses the Nasa Earth API to show a photo taken by the Landsat 8 satellite. The script must be executed

Caio 42 Nov 26, 2022
This is a simple python code to get IP address and its location using python

IP address & Location finder @DEV/ED : Pavan Ananth Sharma Dependencies: ip2geotools Note: use pip install ip2geotools to install this in your termin

Pavan Ananth Sharma 2 Jul 5, 2022
A service to auto provision devices in Aruba Central based on the Geo-IP location

Location Based Provisioning Service for Aruba Central A service to auto provision devices in Aruba Central based on the Geo-IP location Geo-IP auto pr

Will Smith 3 Mar 22, 2022
LicenseLocation - License Location With Python

LicenseLocation Hi,everyone! ❤ ?? ?? ?? ?? ?? This is my first project! ✔ Actual

The Bin 1 Jan 25, 2022