Over a million developers have joined DZone.
Platinum Partner

Build a Grails App With Geolocation in 3 Steps

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

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:

These are the domain classes:

package org.grails.plugins.geolocation

import org.grails.plugins.geolocation.Coordinates;

class GeoPosition {
Coordinates coords
long timestamp
static constraints = {

package org.grails.plugins.geolocation

import org.grails.plugins.geolocation.GeoPosition;

class Coordinates {
GeoPosition position
static constraints = {
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.

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}