Random Sequence

An admin widget for Django which uses Google Maps + JQuery to pick a map location

Sponsored Links:

Django Admin Google Maps Location Picker with JQuery

settings.py

MAPS_API_KEY = 'XXYYZZ'

YOUR_APP/models.py

from django.db import models
from YOUR_APP.widgets import *

class Place(models.Model):
    """(Place description)"""    
    location = LocationField(blank=True, max_length=255)

YOUR_APP/widgets.py

from django import forms
from django.db import models
from django.conf import settings

class LocationPickerWidget(forms.TextInput):
    class Media:
        css = {
            'all': (
                settings.MEDIA_URL + 'css/location_picker.css',
            )
        }
        js = (
            'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
            'http://www.google.com/jsapi?key=' + settings.MAPS_API_KEY,
            settings.MEDIA_URL + 'js/jquery.location_picker.js',
        )

    def __init__(self, language=None, attrs=None):
        self.language = language or settings.LANGUAGE_CODE[:2]
        super(LocationPickerWidget, self).__init__(attrs=attrs)

    def render(self, name, value, attrs=None):
        if None == attrs:
            attrs = {}
        attrs['class'] = 'location_picker'
        return super(LocationPickerWidget, self).render(name, value, attrs)

class LocationField(models.CharField):

    def formfield(self, **kwargs):
        kwargs['widget'] = LocationPickerWidget
        return super(LocationField, self).formfield(**kwargs)

location_picker.css

.location_picker_map {
  width: 300px;
  height: 200px;
  border: 1px solid black;
  padding: 2px;
  display: inline-block;
}

jquery.location_picker.js

google.load("maps", "2");

$(document).unload(function(){
    GUnload();
});

$(document).ready(function(){
    $("input.location_picker").each(function (i) {
        var map = document.createElement('div');
        map.className = "location_picker_map";
        this.parentNode.insertBefore(map, this);
        $(this).css('display','none');

        var lat = 55.950161;
        var lng = -3.187408;
        if (this.value.split(',').length == 2) {
            values = this.value.split(',');
            lat = values[0];
            lng = values[1];
        }
        var center = new GLatLng(lat,lng);

        var map = new google.maps.Map2(map);
        map.addControl(new GSmallMapControl());
        map.setCenter(center, 13);

        this.onMapClick = function(overlay, point) {
            this.value = point.lat()+','+point.lng();
            if (this.marker == null) {
                this.marker = new GMarker(point);
                this.map.addOverlay(this.marker);
            } else {
                this.marker.setPoint(point);
            }
        }

        this.marker = new GMarker(center);
        map.addOverlay(this.marker);

        GEvent.bind(map, "click", this, this.onMapClick);
    });
});

Sponsored Links: