Coder Social home page Coder Social logo

django-google-maps's Introduction

django-google-maps is a simple application that provides the basic hooks into google maps V3 api for use in Django models from Django version 1.11+.

Starting with django-google-maps version (0.7.0), Django 1.11+ is required because Django changed their widget template rendering system. Version 0.8.0 supports Django 2.0+, and as such removes support for Python 2.7

I’m using this to allow someone from the admin panels to type a freeform address, have the address geocoded on change and plotted on the map. If the location is not 100% correct, the user can drag the marker to the correct spot and the geo coordinates will update.

Status

Build Status

USAGE:

  • include the django_google_maps app in your settings.py

  • Add your Google Maps API Key in your settings.py as GOOGLE_MAPS_API_KEY

  • create a model that has both an address field and geolocation field

    from django.db import models
    from django_google_maps import fields as map_fields
    
    class Rental(models.Model):
        address = map_fields.AddressField(max_length=200)
        geolocation = map_fields.GeoLocationField(max_length=100)
  • in the admin.py include the following as a formfield_override

    from django.contrib import admin
    from django_google_maps import widgets as map_widgets
    from django_google_maps import fields as map_fields
    
    class RentalAdmin(admin.ModelAdmin):
        formfield_overrides = {
            map_fields.AddressField: {'widget': map_widgets.GoogleMapsAddressWidget},
        }
  • To change the map type (hybrid by default), you can add an html attribute on the AddressField widget. The list of allowed values is: hybrid, roadmap, satellite, terrain

    from django.contrib import admin
    from django_google_maps import widgets as map_widgets
    from django_google_maps import fields as map_fields
    
    class RentalAdmin(admin.ModelAdmin):
        formfield_overrides = {
            map_fields.AddressField: {
              'widget': map_widgets.GoogleMapsAddressWidget(attrs={'data-map-type': 'roadmap'})},
        }
  • To change the autocomplete options, you can add an html attribute on the AddressField widget. See https://developers.google.com/maps/documentation/javascript/places-autocomplete#add_autocomplete for a list of available options

    import json from django.contrib import admin
    from django_google_maps import widgets as map_widgets
    from django_google_maps import fields as map_fields
    
    class RentalAdmin(admin.ModelAdmin): formfield_overrides = {
        map_fields.AddressField: { ‘widget’:
        map_widgets.GoogleMapsAddressWidget(attrs={
          ‘data-autocomplete-options’: json.dumps({ ‘types’: [‘geocode’,
          ‘establishment’], ‘componentRestrictions’: {
                      'country': 'us'
                  }
              })
          })
        },
    }

That should be all you need to get started.

I also like to make the geolocation field readonly in the admin so a user (myself) doesn't accidentally change it to a nonsensical value. There is validation on the field so you can't enter an incorrect value, but you could enter something that is not even close to the address you intended.

When you're displaying the address back to the user, just request the map using the geocoordinates that were saved in your model. Maybe sometime when I get around to it I'll see if I can create a method that will build that into the model.

django-google-maps's People

Contributors

bashu avatar dcreekp avatar devharam avatar dfejgelis avatar dlenskyi avatar duologic avatar goldhand avatar kernelpan1k avatar khornberg avatar madisona avatar mattfanto avatar matthewelwell avatar mattjmorrison avatar pulsedemon avatar stianjensen avatar thomashkim avatar tsredanovic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-google-maps's Issues

Map not Loading on the template

Map doesn't load on the form as expected. I have tried this with the sample map in the app but it is working fine. Could there be any special requirement needed when using form wizard? I am trying to load the map on a form wizard, but I am not sure if that is the problem. Console gives me this as an error:

Uncaught TypeError: Cannot read property 'value' of null at Object.getExistingLocation (google-maps-admin.js:92) at Object.initialize (google-maps-admin.js:41) at HTMLDocument.<anonymous> (google-maps-admin.js:165) at j (jquery.min.js:2) at k (jquery.min.js:2)

I also noticed that another jquery.js is loaded, which is of lower version 3.1.0 as compared to the jquery loaded that is used in the project which is v3.2.1

Is there an example (or step to step tutorial) on how to use it?

Hi,

Forgive my unenlightenment, i'm quite new to Django and web development in general, but i searched thoroughly through the official docs (https://pypi.org/project/django-google-maps/) , stackoverflow and other sources, cloned this repo and i'm beating my head trying to figure out on how this works, there's a sample folder inside this repo should i execute virtual environment inside of it?
I ran a local instance of the project using virtual environment, what i did was go to the main project folder and executed the following through bash (Obviously i added my API key to settings.py).
I'm also in doubt if i should reproduce all the steps contained in README file. Because this repo already have for example the models.py files, etc.

virtualenv -p python3 venv
source venv/bin/activate
cd requirements
pip install -r requirements.txt
pip install -r test.txt
python manage.py migrate
cd $HOME/django-google-maps/django-google-maps-master && source ./venv/bin/activate && python manage.py runserver 0.0.0.0:8800

Currently i'm trying to figure out what is wrong because it actually renders the map for quite a few milliseconds then it disappears sugesting me to look at the JavaScript Console
gonewrong

Thanks for your time!

On mouse click set marker with lat long

Hi,

I would like to implement a python application that allows me to display a google (satellite) map and also create new markers on mouse click with the lat long of the marker. I am new to django so I would like to know if this is possible with this library before I start studying.

This javascript program below does exactly what I want. Also I have seen in one of the issues that someone said you can't zoom? Google map allows you to zoom with the mouse wheel etc or did they mean something else? Thanks for the help.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>My Google Map</title>
  <style>
    #map{
      height:400px;
      width:100%;
    }
  </style>
</head>
<body>
  <h1>My Google Map</h1>
  <div id="map"></div>
  <script>
    function initMap(){
      // Map options
      var options = {
        zoom:8,
        center:{lat:42.3601,lng:-71.0589}
      }

      // New map
      var map = new google.maps.Map(document.getElementById('map'), options);

      // Listen for click on map
      google.maps.event.addListener(map, 'click', function(event){
        // Add marker
        addMarker({coords:event.latLng});
      });

      /*
      // Add marker
      var marker = new google.maps.Marker({
        position:{lat:42.4668,lng:-70.9495},
        map:map,
        icon:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
      });

      var infoWindow = new google.maps.InfoWindow({
        content:'<h1>Lynn MA</h1>'
      });

      marker.addListener('click', function(){
        infoWindow.open(map, marker);
      });
      */

      // Array of markers
      var markers = [
        {
          coords:{lat:42.4668,lng:-70.9495},
          iconImage:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
          content:'<h1>Lynn MA</h1>'
        },
        {
          coords:{lat:42.8584,lng:-70.9300},
          content:'<h1>Amesbury MA</h1>'
        },
        {
          coords:{lat:42.7762,lng:-71.0773}
        }
      ];

      // Loop through markers
      for(var i = 0;i < markers.length;i++){
        // Add marker
        addMarker(markers[i]);
      }

      // Add Marker Function
      function addMarker(props){
        var marker = new google.maps.Marker({
          position:props.coords,
          map:map,
          //icon:props.iconImage
        });

        // Check for customicon
        if(props.iconImage){
          // Set icon image
          marker.setIcon(props.iconImage);
        }

        // Check content
        if(props.content){
          var infoWindow = new google.maps.InfoWindow({
            content:props.content
          });

          marker.addListener('click', function(){
            infoWindow.open(map, marker);
          });
        }
      }

  </script>
  <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=SOMEAPIKEY&callback=initMap">
    </script>
</body>
</html>

Django 4.0 force_text

django==4.0.2
django-google-maps==0.12.4

ImportError: cannot import name 'force_text' from 'django.utils.encoding'

Django 1.10 Compatibility

fields.py has a reference to the removed models.SubfieldBase, I'll submit a pull request to change it to use Field.from_db_value

Django 3.2 support

Hi there,

I've noticed that you've pinned your django dependency to <3.2 - is there a reason for this? Can it be removed?

Thanks,
Matt

Issue with the documentation

The documentation avilable in the website pyp.org has some flaws when copy-pasting directlly from the website,

E.g: ‘widget’------> 'widget'

Code Sample On Documentation :
map_fields.AddressField: { ‘widget’:
map_widgets.GoogleMapsAddressWidget(attrs={
‘data-autocomplete-options’: json.dumps({ ‘types’: [‘geocode’,
‘establishment’], ‘componentRestrictions’: {
'country': 'us'

Migrate to django 1.11

Django 1.11 admin throws an error for GoogleMapsAddressWidget.
Code:

    formfield_overrides = {
        map_fields.AddressField: {'widget': map_widgets.GoogleMapsAddressWidget},
    }

Error:

build_attrs() got an unexpected keyword argument 'type'

Django 1.10 admin works well

DjangoREST

Does it support Django REST?
I don't see anything on this

Any way to set zoom level?

Thank you for this awesome widget. Now need some help on how to set zoom level & how to always have the pointer static like we have in mobile.

Error in Django 2.2.16

Update Django from 2.0.1 to 2.2.16. Got an error in admin page:

render() got an unexpected keyword argument 'renderer'

Error when installing on Docker

Hello,
I have spotted that django-google-maps have a problem to properly install under Docker container.

I am using python:3.6-alpine official image and installing requirements from pip finish with a traceback:

Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "/tmp/pip-build-etjs66mk/django-google-maps/setup.py", line 38, in <module>
      zip_safe=False,
    File "/usr/local/lib/python3.6/site-packages/setuptools/__init__.py", line 129, in setup
      return distutils.core.setup(**attrs)
    File "/usr/local/lib/python3.6/distutils/core.py", line 148, in setup
      dist.run_commands()
    File "/usr/local/lib/python3.6/distutils/dist.py", line 955, in run_commands
      self.run_command(cmd)
    File "/usr/local/lib/python3.6/distutils/dist.py", line 974, in run_command
      cmd_obj.run()
    File "/usr/local/lib/python3.6/site-packages/wheel/bdist_wheel.py", line 257, in run
      self.distinfo_dir)
    File "/usr/local/lib/python3.6/site-packages/wheel/bdist_wheel.py", line 427, in egg2dist
      distribution=self.distribution)
    File "/usr/local/lib/python3.6/site-packages/wheel/metadata.py", line 177, in pkginfo_to_dict
      new_requirements = sorted(convert_requirements(requirements))
    File "/usr/local/lib/python3.6/site-packages/wheel/metadata.py", line 234, in convert_requirements
      parsed_requirement = pkg_resources.Requirement.parse(req)
    File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3047, in parse
      req, = parse_requirements(s)
  ValueError: not enough values to unpack (expected 1, got 0)

I have checked version 0.6.0 and 0.10.0. I did update of setuptools, pip, wheel but with no luck.
Probably related tightly to Alpine Linux distribution. Any advice how to fix it?

EDIT: After some debugging I have found out that the package is correctly installed tho and exists in site-packages

pip freeze | grep 'google'
django-google-maps==0.10.0

I am super confused now. But seems that this error during installation is not affecting the process.

Multiple widgets in same model

How to add multiple widgets in the same model?

If the only accepted/hardcoded names are "address" and "geolocation" i see no way to do that.

Incompatibility with `django-storages` using s3

The extension is incredibly useful. One note: I had to extend the GoogleMapsAddressWidget class so that I could get the file paths correct for my setup using s3 for static assets. I essentially added the django-storages setting into the path.

settings.AWS_S3_CUSTOM_DOMAIN + settings.STATIC_URL + 'django_google_maps/js/google-maps-admin.js',

But I wonder if there's not a way that would handle this automatically, since the other static admin files (for example the ones included with Django) seem to write the path properly.

Making geolocation read only returns world map

djangoGoogleMaps
Hello,

I followed your suggestion and put geolocation into read only.

from locations.models import Container
from django.contrib import admin
from django_google_maps import widgets as map_widgets
from django_google_maps import fields as map_fields

class ContainerAdmin(admin.ModelAdmin):
    formfield_overrides = {
        map_fields.AddressField: {'widget': map_widgets.GoogleMapsAddressWidget},
    }
    readonly_fields=('geolocation',)

admin.site.register(Container, ContainerAdmin)

However, now I only see the world map in the admin but no longer the exact address as given by AddressField.

How can I fix that?

Regards

Robert

Widget template renders improperly inside a div

I'm wondering what the repercussions would be to omit class="map_canvas_wrapper" from the HTML of django_google_maps/templates/django_google_maps/widgets/map_widget.html.

That div has some padding built into it such that it overflows parent divs. It looks real bad on desktop. However... looks perfect on mobile (iOS, Safari).

I'm willing to do further research, but I cannot find the map_widget.html code to change it once it's pip-installed. I don't know if it gets compiled into some other template.

image

By the way, you're the best for writing this app. Blessed of the Lord.

Using Maps for frontend users in templates

Hi,
I've seen your previous post related to this issue but still not able to make it work for templates.

Following are the details what I am trying to do:

 `from django.db import models
  from django_google_maps import fields as map_fields

class Address(models.Model):
    address = map_fields.AddressField(max_length=200)
    geolocation = map_fields.GeoLocationField(max_length=200)

    def __unicode__(self):
        return `self.address````

My Forms.py:

`from django_google_maps import widgets as map_widgets
 from django_google_maps import fields as map_fields

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address
        fields = ['address', 'geolocation']
        formfield_overrides = {
            map_fields.AddressField: {'widget': map_widgets.GoogleMapsAddressWidget},
        }`

My Views.py:
from .forms import AddressForm
from django.views.generic.edit import FormView

class MapView(FormView):
    form_class = AddressForm
    template_name = 'address.html'
    # success_url = '/thanks/'

    def form_valid(self, form):

        return super(MapView, self).form_valid(form)
I am working with Python 2.7, Django 1.11.

Finally Template:
`{% extends 'base.html' %}
{{form.media}}


{% block content %}
<div class="container">
    <div class="row">
        <div class="col-4 offset-3">
        <form action="" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Send message" />
        </form>
        </div>
    </div>
</div>
{% endblock content %}

`
I've tried {{ form.media }} in my head in base.html and in template itself directly by removing it from base to avoid any duplication but still map is not showing up in frontend template. I got the both fields displaying fine and there is also no error in chrome inspect elements. My GoogleAPI key is listed in settings.py as per your instructions.

I've collected static and in my urls.py I am serving static locally.

`from customer.views import (
    MapView
 )

from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
     url(r'^$', views.home, name='home'),
     url(r'^map/', MapView.as_view(), name='map'),
     url(r'^admin/', admin.site.urls),
 ]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

`
Your advise will be much appreciated if you can clearly help to identify the problem.

Is Compatible with Django 2.1 or Higher Version?

When I tried to upgrade Django's version using pip install Django==2.1, the console returned the following message.

Collecting Django==2.1
  Using cached https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl
Requirement already satisfied: pytz in ./venv/lib/python3.7/site-packages (from Django==2.1) (2018.5)
django-google-maps 0.10.1 has requirement Django<2.1,>=1.11.0, but you'll have django 2.1 which is incompatible.
Installing collected packages: Django
  Found existing installation: Django 2.0.13
    Uninstalling Django-2.0.13:
      Successfully uninstalled Django-2.0.13
Successfully installed Django-2.1

I see the new version can be installed, however, is there anything incompatible existed? Thanks.

Next Release?

It is long time by now
Do you have plan to release soon?
I am looking forward to see it in action with Django2

How do I access map in the template?

I've done everything by the tutorial and it works, I have the map in admin interface. How do I access this map In my templates? I need It in my details view.

contact email

Hi, I'm trying to make an application involving django + google maps and would like to ask questions about using your boirleplate in a presentation

South introspection rules for AddressField

Hey, first off, nice plugin. Saved me a lot of time!

I was getting a

! Cannot freeze field 'project.project.address'
! (this field has class django_google_maps.fields.AddressField)

error when trying to migrate an app that was using your AddressField.

This might be down to my setup: I had an existing CharField for the address, then I installed your app and changed the CharField to an AddressField and added the Geo..Field too. Eitherway, specifically adding an introspection rule for the AddressField fixed it:

try:
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules([], ["^django_google_maps\.fields\.GeoLocationField"])
    add_introspection_rules([], ["^django_google_maps\.fields\.AddressField"])
except ImportError:
    pass

Django admin AddressField not responsive

On smaller screen sizes address field can go out of proportions and map disappears in django admin.
My code:

class CargoStatusAdmin(admin.ModelAdmin):
    model = CargoStatus

    list_display = ('id', 'cargo', 'address', 'date',)
    list_display_links = ('id',)
    search_fields = ('cargo__tracking_number', 'address', 'date')
    ordering = ('-cargo__created_at', '-date')
    autocomplete_fields = ('cargo', )

    formfield_overrides = {
        map_fields.AddressField: {'widget': map_widgets.GoogleMapsAddressWidget},
    }

Here is a screenshot for a small screen issue:
small_screen

Here is a screenshot for a mobile screen issue:
mobile_screen

dynamically put an address in the address field and trigger it to search

Hi and thanks for sharing this :)

Is there a way to dynamically put an address in the address field and trigger it to search like if i was doing manually
i tried this, but doesnt work:

$('#id_address').val('byens pizza klarup')
var e = $.Event( "keypress", { which: 13 } );
$('#id_address').trigger(e);

Why? Its my intention that I show a really simple signup form with email, company name and city, and as soon as these fields are valid, i will take the company name and city and perform a search and show the rest of the form fields, map, address postal code etc with pre filled information. I always try to make it really easy to sign up.

thanks :)

Typo in readme file

In readme file there's a typing error. Nothing major, but It causes error when you test the app the first time and just copy model and admin.

class Rental(models.Model):
address = map_fields.AddressField(max_lenght=200) # length
geolocation = map_fields.GeoLocationField(max_length=100)

ValueError while trying to migrate app

Hey! i'm new to the django framework and python too.
I've succesfully installed django and made a virtual environment in which i'm trying to run the app.
But i'm getting a ValueError while trying to migrate the app which states :

lat, lon = self._split_geo_point(lat)
ValueError: not enough values to unpack (expected 2, got 1)

I'm using python3.8 and Django3.0.8 & the django_google_maps version is 0.12.1
I'm stuggling with this and any help would be really apprecited.
Regards

How could the CSS styles be modified?

Hello, first of all, thank you very much for the application, as the title says, how can I modify the CSS style, mostly the size, I do not have much idea of styles, excuse me.

Google Maps widget hard-codes jquery 3.1.0, conflicts with other imports of jquery

I just tracked down an issue with datepicker-plus not working that turned out to be caused by this line in widgets.py:

        'https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js',

This was importing a second (older) copy of jquery, which was conflicting with an earlier import. I've worked around it for now by making a copy of GoogleMapsAddressWidget with that line removed.

HTTPs not working

https:// requests cannot include http:// files.

Includes should be schemaless.
What's needed is to delete "http" in widgets.py (line 14, 15).

I've forked and fixed it: dfejgelis@22ec8dd
No idea how to submit a patch :S

Feedback

commit : 7912b859fad705633794deb37e91ce01aa630b64

Django==2.0.1
django-google-maps==0.8.0
pytz==2017.3

image

  • How to pin point the location. I don't see any pin widget on it. And yellow man is not a pin. It is a Google Street View

Please support

Having only the 'address' field in the form.py breaks the search in a template

I am trying to display the address autofill in the template, using the example code in the sample app.

But I need only the 'address' field and not the 'geolocation' field in my template, as I want the user to enter just the location in a search box.

Simply put, just an input box for the address, no map and no geolocation box.

So, when I remove the 'geolocation' from the fields in the forms.py, it breaks the address box as well. If I add 'geolocation' back, it works fine again.

forms.py code:

`from django.forms import ModelForm
from .models import Rental
from django_google_maps.widgets import GoogleMapsAddressWidget
import json

class mapForm(ModelForm):
class Meta:
model = Rental
fields = ['address']
widgets = {
"address": GoogleMapsAddressWidget(attrs={
'data-autocomplete-options': json.dumps({ 'types': ['geocode',
'establishment'], 'componentRestrictions': {
'country': 'ind'
}
})
}),
}`

model.py code:

`from django.db import models

from django_google_maps import fields as map_fields

class Rental(models.Model):
address = map_fields.AddressField(max_length=200)
geolocation = map_fields.GeoLocationField(max_length=100)
`

index.html:

`

{{form.media}}

{{form.as_p}}

`

Error I see in the console:

jquery.min.js:2 Uncaught TypeError: Cannot read property 'value' of null
at Object.getExistingLocation (google-maps-admin.js:105)
at Object.initialize (google-maps-admin.js:41)
at HTMLDocument. (google-maps-admin.js:178)
at j (jquery.min.js:2)
at k (jquery.min.js:2)

Can someone please help me out here?
Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.