Mitch Pronschinske is a Senior Content Analyst at DZone. That means he writes and searches for the finest developer content in the land so that you don't have to. He often eats peanut butter and bananas, likes to make his own ringtones, enjoys card and board games, and is married to an underwear model. Mitch is a DZone Zone Leader and has posted 2574 posts at DZone. You can read more from them at their website. View Full User Profile

Build a Grails App With Geolocation in 3 Steps

07.26.2010
| 15707 views |
  • submit to reddit
A new Grails Geolocation plugin features support for the HTML5 Geolocation spec.  In just 3 simple steps, this tutorial will show you how to use that plugin to add Geolocation into your own web app.  


These 3 steps will essentially allow you to add location-sensitive behavior to your app which enables the retrieval of a user's current position so that it may be put into the session. The 3 steps are as follows:

  1. Install the plugin - "grails install-plugin geolocation"
  2. Add the <geolocation:resources/> tag in the head section of the page that you want to be locationally-aware
  3. Add the <geolocation:locateMe/> tag in the body section of that same page

The Geoposition instance will be available in the session as soon as the user declares that they want to share their location:

From gsp inside a JavaScript function
var latlng = new google.maps.LatLng(${session.position.coords.latitude},${session.position.coords.longitude});
From a controller
def position = session['position']
The test page in the plugin can test the application's accuracy with a google map widget once the user's location is known.  Just enter:
your_app_name/geolocation/showMap

These are the domain classes:

Geoposition.groovy
package org.grails.plugins.geolocation

import org.grails.plugins.geolocation.Coordinates;

class GeoPosition {
Coordinates coords
long timestamp
static constraints = {
}
}

Coordinates.groovy
package org.grails.plugins.geolocation

import org.grails.plugins.geolocation.GeoPosition;

class Coordinates {
GeoPosition position
static constraints = {
latitude(nullable:true)
longitude(nullable:true)
altitude(nullable:true)
accuracy(nullable:true)
altitudeAccuracy(nullable:true)
heading(nullable:true)
speed(nullable:true)
}
double latitude
double longitude
double altitude
double accuracy
double altitudeAccuracy
double heading
double speed
static belongsTo = GeoPosition
}

The applications developed using this plugin have been successfully run on iPhone Safari, Safari 5.0 (slower), and Firefox 3.5+.  Some browsers like Android still haven't been tested yet.

You can download the source code from the link provided in the first paragraph, or from GitHub.