Login

Google map on admin address field

Author:
coulix
Posted:
August 18, 2010
Language:
JavaScript
Version:
Not specified
Score:
2 (after 2 ratings)

Who never wished to have valid address data by showing a little google map with a marker near the address input text ? Using js only it gets quite easy.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
 
  
$(document).ready(function() {

    $('#id_address').parent().append("<div id='map_canvas' style='width:380px; height:200px; margin: 20px; margin-left: 105px;' ></div>");

    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    
    var map = new google.maps.Map(document.getElementById("map_canvas"),  myOptions);
 

    $('#id_address').change(function() {
      updateMapPosition(map);
    });

    // on load update map if address is not empty 
    if ($('#id_address').val()) {
      updateMapPosition(map);
    }
    
});


 
function updateMapPosition(map) {
  var geocoder = new google.maps.Geocoder();
  var position = geocoder.geocode({'address': $('#id_address').val()} ,
    function(results,status) { 
      if (status == google.maps.GeocoderStatus.OK) {
        if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({map:map, position:results[0].geometry.location});
        }
      }
      else {
        alert("Adresse inconnue par google map, rajoutez le code postal et le pays.");
      }
    }
  );
}

===========
Python
class FooAdmin(admin.ModelAdmin):

    class Media:
        js = [
            'http://code.jquery.com/jquery-1.4.2.min.js', 
            'http://maps.google.com/maps/api/js?sensor=false', 
            settings.MEDIA_URL +'/admin/long-lat-render.js'
        ]
            



  

More like this

  1. Django Collapsed Stacked Inlines by applecat 1 year, 10 months ago
  2. Django Collapsed Stacked Inlines by mkarajohn 3 years, 11 months ago
  3. Dynamically adding forms to a formset. OOP version. by halfnibble 9 years, 7 months ago
  4. Convert multiple select for m2m to multiple checkboxes in django admin form by abidibo 11 years, 8 months ago
  5. Django admin inline ordering - javascript only implementation by ojhilt 12 years ago

Comments

magopian (on August 18, 2010):

Awesome, thanks!

#

quinode (on April 22, 2011):

Yoohooo !!!

#

Please login first before commenting.