Monday, June 18, 2012

How to use gmaps.js on web2py

It's easy to handle Google Maps on your website and of course it will be much easier if you use web2py!

1. Create new app called gmap


2. Download gmaps.js
Go to http://hpneo.github.com/gmaps/ and download gmaps.js. Place it under the app folder static/js/gmaps.js

3. controllers/default.py
Replace the def index() with the following.

def index():
    from gluon.tools import geocode
    latitude = longtitude = ''
    form=SQLFORM.factory(Field('search'), _class='form-search')
    form.custom.widget.search['_class'] = 'input-long search-query'
    form.custom.submit['_value'] = 'Search'
    form.custom.submit['_class'] = 'btn'
    if form.accepts(request):
        address=form.vars.search
        (latitude, longitude) = geocode(address)
    else:
        (latitude, longitude) = ('','')
    return dict(form=form, latitude=latitude, longitude=longitude)
Note:  There was an issue #855 and just fixed with the Version 2.0.0 (2012-06-17 23:36:32) dev. If you are using the web2py version older than this, make sure to replace the latitude and longitude as follows.
 (longitude, latitude) = geocode(address)
4. views/default/index.html
Replace it with the following.

{{extend 'layout.html'}}
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="{{=URL('static','js/gmaps.js')}}"></script>
<div>
{{=form.custom.begin}}
{{=form.custom.widget.search}}{{=form.custom.submit}}
{{=form.custom.end}}
</div>
{{if longitude or latitude:}}
<p>latitude, longtitude: {{=latitude}},{{=longitude}}</p>
<div id="map" style="height:400px;width:800px"></div>
<script>
$(document).ready(function(){
  map = new GMaps({
    div: '#map',
    lat: {{=latitude}},
    lng: {{=longitude}}
  });
   map.addMarker({
    lat: {{=latitude}},
    lng: {{=longitude}},
    title: 'Here!',
    infoWindow: {
        content: '<p>{{=request.vars.search}}</p>'
    }
  });
});
</script>
{{pass}}
5. Result
Type "243 S Wabash Ave, Chicago, IL, USA" and see the result.




5 comments:

  1. Great Post.
    I am new to Web2py and this helped a lot.
    How would i make it display and map with the users current location (obtained from browser) on load?
    Thanks

    ReplyDelete
    Replies
    1. I never tried but this post might help you.
      http://www.paulund.co.uk/create-google-maps-with-gmaps-js

      Delete
  2. Great work, just tried it does return the correct (latitude, longtitude: 41.8784403,-87.6256217) But the map is not displayed.
    Thanks in advance

    ReplyDelete
    Replies
    1. if your server uses https trey : https://maps.google.co....

      Delete
    2. laurent, no me aparece el mapa. Y no puedo ver su mensaje, como lo podria solucionar?

      Delete