Skip to content

Instantly share code, notes, and snippets.

@mhulse
Created September 6, 2011 04:33
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhulse/1196589 to your computer and use it in GitHub Desktop.
Save mhulse/1196589 to your computer and use it in GitHub Desktop.
Django google maps v3 snipplet [via] admin example (tested in Django 1.4.x)
from django.contrib import admin
from myapp.models import Foo
from myapp.forms import FooForm
class FooAdmin(admin.ModelAdmin):
form = FooForm
prepopulated_fields = { 'slug': ['title'] }
admin.site.register(Foo, FooAdmin)
from django import forms
from myapp.models import Foo
from myapp.widgets import LocationWidget
class FooForm(forms.ModelForm):
latlng = forms.CharField(widget=LocationWidget()) # http://djangosnippets.org/snippets/2106/
class Meta:
model = Foo
...
latlng = models.CharField(_(u'lat/lon'), blank=True, max_length=100)
...
from django import forms
from django.db import models
from django.utils.safestring import mark_safe
DEFAULT_WIDTH = 300
DEFAULT_HEIGHT = 200
DEFAULT_LAT = 55.16
DEFAULT_LNG = 61.4
class LocationWidget(forms.TextInput):
def __init__(self, *args, **kw):
self.map_width = kw.get("map_width", DEFAULT_WIDTH)
self.map_height = kw.get("map_height", DEFAULT_HEIGHT)
super(LocationWidget, self).__init__(*args, **kw)
self.inner_widget = forms.widgets.HiddenInput()
def render(self, name, value, *args, **kwargs):
if value is None:
lat, lng = DEFAULT_LAT, DEFAULT_LNG
else:
if isinstance(value, unicode):
a, b = value.split(',')
else:
a, b = value
lat, lng = float(a), float(b)
js = '''
<script>
<!--
var map_%(name)s;
function savePosition_%(name)s(point)
{
var input = document.getElementById("id_%(name)s");
input.value = point.lat().toFixed(6) + "," + point.lng().toFixed(6);
map_%(name)s.panTo(point);
}
function load_%(name)s() {
var point = new google.maps.LatLng(%(lat)f, %(lng)f);
var options = {
zoom: 13,
center: point,
mapTypeId: google.maps.MapTypeId.ROADMAP
// mapTypeControl: true,
// navigationControl: true
};
map_%(name)s = new google.maps.Map(document.getElementById("map_%(name)s"), options);
var marker = new google.maps.Marker({
map: map_%(name)s,
position: new google.maps.LatLng(%(lat)f, %(lng)f),
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(mouseEvent) {
savePosition_%(name)s(mouseEvent.latLng);
});
google.maps.event.addListener(map_%(name)s, 'click', function(mouseEvent){
marker.setPosition(mouseEvent.latLng);
savePosition_%(name)s(mouseEvent.latLng);
});
}
$(function() {
load_%(name)s();
});
//-->
</script>
''' % dict(name=name, lat=lat, lng=lng)
html = self.inner_widget.render("%s" % name, "%f,%f" % (lat, lng), dict(id='id_%s' % name))
html += '<div id="map_%s" style="width: %dpx; height: %dpx"></div>' % (name, self.map_width, self.map_height)
return mark_safe(js + html)
class Media:
js = (
'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js',
'http://maps.google.com/maps/api/js?sensor=false',
)
@mhulse
Copy link
Author

mhulse commented Sep 6, 2011

Here's the original snippet.

@bactisme
Copy link

It could be great to add a input just on top to look for a special place.

What means "Note: This field will be filled-in automatically based on the other address bits." ? Which field is used ?

@mhulse
Copy link
Author

mhulse commented Sep 18, 2011

Hi,

Funny that you should mention the "input on top" idea... I modified this code to have a "geocode" field; I plan on posting the updated code asap. I will post back here once I have it up.

As for your second question: See this gist here. That code will take all the address fields and try to store a lat/lon value upon save.

@mhulse
Copy link
Author

mhulse commented Sep 19, 2011

FYI: Here's another example that actually uses the custom model field.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment