Wednesday, November 16, 2011

Django - Google maps on your page and display address in map entered in form




1) get gmapi , Django application for google map , from here http://code.google.com/p/django-gmapi/

2) copy gmapi folder to your project directory 

3) add gmapi to INSTALLED_APP and in urls.py add following two lines.
url(r'', include('gmapi.urls.media')), # Use for debugging only.
url(r'^$', 'main.views.index'),

4) in your main/views.py
def index(request):
    "intialize gmap with initial center location"
    gmap = maps.Map(opts = {
        'center': maps.LatLng(18, 72.5),
        'mapTypeId': maps.MapTypeId.ROADMAP,
        'zoom': 3,
        'mapTypeControlOptions': {
            'style': maps.MapTypeControlStyle.DROPDOWN_MENU
        },
    })
    """ This is my location  """
    xyam = 23   # longitude
    yyam = 72.5 # latitude
    """  for display marker on my location """
    marker = maps.Marker(opts = {
        'map': gmap,
        'position': maps.LatLng(xyam, yyam),
    })
    maps.event.addListener(marker, 'mouseover', 'myobj.markerOver')
    maps.event.addListener(marker, 'mouseout', 'myobj.markerOut')
    info = maps.InfoWindow({
        'content': "Priyank's location",
        'disableAutoPan': True
    })
    info.open(gmap, marker)
    
    """ to get address and display result on maps """
    if request.method == 'POST':
         from gmapi.maps import Geocoder
         geocoder = Geocoder()
         address = request.POST.get('address')
         results, status_code = geocoder.geocode({'address': address })
         if results:
             for r in results:
                 result = r
                 #print "location====",result['geometry']['location']
                 lat, lng = result['geometry']['location']['arg']
                 xyam = lat
                 yyam = lng

                 """ This markers are for search results """
                 marker1 = maps.Marker(opts = {
                 'map': gmap,
                 'position': maps.LatLng(xyam, yyam),
                 })
                 maps.event.addListener(marker1, 'mouseover', 'myobj.markerOver')
                 maps.event.addListener(marker1, 'mouseout', 'myobj.markerOut')
                 info = maps.InfoWindow({
                     'content': "Searched result",
                     'disableAutoPan': True
                 })
                 info.open(gmap, marker1)

    extra_context = {}
    extra_context['form'] = MapForm(initial={'map': gmap})
    return render_to_response('index.html', extra_context, context_instance=RequestContext(request))
5) in your index.html  put this line....
{{ form.map }}
{{ form.media.js }}

 < script type="text/javascript" >
    window.myobj = {
         markerOver: function() { this.openInfoWindow(); },
         markerOut: function() { this.closeInfoWindow(); }
    };
</script>

<form action='' method='post'>
         {% csrf_token %}
         Address:<input type='text' name='address'/>
         <input type='submit' value='Get location'/>
</form>
6) here is live example.......http://coderpriyu.alwaysdata.net

7) thats it . stay tune with blog , i w'll post shortly about how to display your live location in your page with google latitude api..

8) question ??.............comment it ...

2 comments:

  1. What modules i have to import to work with this example?

    ReplyDelete
  2. Hey Mr Patel,

    I am writing to ask for your advice and help about django and maps in general. I've found tutorials and examples with google maps and other open source solutions, like the open street maps. I would like to be able to create points in a map and show a info window for each point.

    I am new to Django (using the version 1.6.1). It seems that gmapi was developed for an old version of Django. Is that correct? Do you have a newer version?

    I would appretiate very much if you send me some tutorials or other info to help me get where I need.

    Shucriá.
    Thank you very much.

    ReplyDelete