Over a million developers have joined DZone.

Build a Grails App With Geolocation in 3 Steps

· Web Dev Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

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.

The Web Dev Zone is brought to you by Stormpath—offering a complete, pre-built User Management API for building web and mobile applications, and APIs. Download our new whitepaper: "Build Versus Buy: Customer Identity Management for Web and Mobile Applications".

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}