📜 ⬆️ ⬇️

Making a Twitter mash-up and Google Maps in 20 minutes on Grails

Introduction


For many Java developers, it is often synonymous with badly boring enterprise applications. It is associated with numerous XML configuration files, sample code, etc. Therefore, as a rule, instead of it, developers use dynamic languages ​​(such as Ruby, Python, PHP) to develop their projects, especially for simple utilities, mesh-ups, etc.

However, in the Java environment, much has changed in the last few years. There are a lot of frameworks that free the developer from the burden of corporate ("enterprise") applications. Grails is probably one of the best. It is based on Groovy, a dynamic language on the Java platform. Groovy is designed specifically for Java programmers and the transition to it is as painless as possible. Grails uses well-known, reliable, and efficient Java libraries (Spring, Hibernate, etc.) to do all the hard work. There is also a plugin system and plugins for almost all widely used Java libraries.

In this post I will explain how to make a mash-up from Twitter and Google Maps in just 20 minutes. The end result will look something like this:
Geo Twitter Complete
')


Preparing the development environment


First, it would be nice to make sure that the correct version of the JDK is installed. It's best to just download the latest version of the JDK here .
Install it and set the JAVA_HOME environment variable so that it points to the installation directory.

Then download the latest Grails release from here .
Unpack the archive in any place, and then set the environment variable GRAILS_HOME so that it points to the directory in which the archive was unpacked. Also make sure that the bin/ directory of the Grails installation directory is mentioned in the PATH environment variable.

After completing the above steps, it will be possible to run the Grails commands in the console. You can type grails help to check it out. A list of available commands should appear.

Basic concepts


Grails is based on the MVC design pattern . The model is presented in domain-classes, controllers by controller classes, mapping by GSP pages. In this project, only the controller classes and GSP are used, since the model is provided by the Twitter API.

It does not hurt to read the quick start guide . Additional information is available in the user manual . In particular, this post is useful information about the controllers and GSP .

Creating an application framework


One of the capabilities of Grails that frees a developer from the “enterprise” burden of Java is the ability to automatically generate the framework of the main application.
To do this just type:

grails create-app geo_twitter

This will create the geo_twitter application in the current working directory. Go to this directory for all further steps.

Getting Started with Google Maps


Google Maps integration is simple and well supported by Google. However, you first need to get an API key to access all services. Do not worry - it's easy, fast and free.

To begin with, it would be nice to clean up the main layout template (layout) - you can remove the Grails logo, etc. Open grails-app/views/layout/main.gsp and fix it to look like this:

<html>
<head>
<title><g:layoutTitle default= "Grails" /></title>
<link rel= "stylesheet" href= "${resource(dir:'css',file:'main.css')}" />
<link rel= "shortcut icon" href= "${resource(dir:'images',file:'favicon.ico')}" type= "image/x-icon" />
<g:layoutHead />
</head>
<body>
<g:layoutBody />
</body>
</html>


Then edit grails-app/views/index.gsp to integrate Google Maps like this:

<html>
<head>
<title> Welcome to GeoTwitter! </title>
<meta name= "layout" content= "main" />

<script src= "www.google.com/jsapi?key=YOUR_GOOGLE_MAPS_API_KEY" type= "text/javascript" ></script>

<script type= "text/javascript" >
google.load("maps", "2.x");
google.load("jquery", "1.3.1");

google.setOnLoadCallback(function() {
$(document).ready(function() {
var map = new GMap2(document.getElementById('map'));
var vinnitsa = new GLatLng(49.2325477, 28.4744695); // Replace this by coordinates of your own city ;)
map.setCenter(vinnitsa, 8);
map.addControl(new GLargeMapControl());
});
});
</script>
</head>
<body>
<div id= "map" style= "width:800px; height:600px" >
</div>
</body>
</html>


The end result will look something like this:

Geo Twitter Start

Twitter form and layout


Add a simple username form to the index.gsp page.

<div class= "form" >
<form action= "" id= "twitter" >
<p>
<label> twitter id: </label>
<input type= "text" id= "name" name= "name" value= "" />
</p>
<p class= "submit" >
<input type= "submit" value= "Map my friends!" >
</p>
</form>
</div>


Then replace the main styles in web-app/css/main.css with something like this:

body {
font-family : Verdana , Helvetica , sans-serif ;
margin : 1em ;
}

#map {
position : absolute ;
width : 800px ;
height : 600px ;
left : 19em ;
top : 1em ;
}

.form {
border : 1px dashed gray ;
width : 15em ;
padding : 0.5em ;
}

.form label {
width : 7em ;
display : block ;
float : left ;
}

.form input {
width : 10em ;
}

.form .submit {
padding-left : 7em ;
}


You will get something like this:
Geo Twitter Login Form


Some special Grails magic of server logic


To make something really work, you need to add server logic. First install the Grails plugin to work with Twitter .

grails install-plugin twitter

Now we need to create a controller that will give out a list of friends from Twitter with information about their location, etc.

grails create-controller Twitter

The command above will generate the grails-app/controllers/TwitterController.groovy file with the controller skeleton. It should be replaced with a controller implementation that will display information about friends in JSON format. He will also contact the geocoding service to get coordinates on the map by the name of the area.

import grails.converters.*

class TwitterController {
// Google Maps API key
static def API_KEY = "Insert your Google Maps API key here"

// TwitterService instance will be injected into this variable by Spring
def twitterService

def friendsJson = {
// Get friends of given user
def friends = getFriends ( params . name )
// Render friends list as JSON
render ( friends as JSON )
}

private def getFriends ( String userName ) {
def friends = twitterService . getFriends ( params . name )

// Return only the needed fields for each user and retrieve coordinates for location
friends . collect { it ->
[
screenName: it . screenName ,
name: it . name ,
pictureUrl: it . profileImageUrl as String ,
bio: it . description ,
status: it . status ?. text ,
coords: getCoordsFromLocation ( it . location )
]
}
}

/**
* This method gets coordinates on map for given location string.
*/

private def getCoordsFromLocation ( String location ) {
if ( location ) {
if ( location . contains ( "iPhone:" )) {
// There can be coords specified in location
// like iPhone: 39.035248,-77.138687
location = location . replace ( "iPhone: " , "" )
def parts = location . split ( "," )
return [ latitude: parts [0], longitude: parts [1]]
} else {
// Encode location as URL
def encodedLocation = URLEncoder . encode ( location )
// Call web service by retrieving URL content
def response =
"maps.google.com/maps/geo?q=${encodedLocation}&output=xml&key=${API_KEY}" . toURL (). getText ()
// Parse response XML
def root = new XmlSlurper (). parseText ( response )
if ( root . Response . Placemark . size () == 1) {
def coords = root . Response . Placemark . Point . coordinates . text ()
def parts = coords . split ( "," )
if ( parts . size () > 1) {
return [ latitude: parts [1] as Double , longitude: parts [0] as Double ]
}
}
}
}

// No coordinates are determined
return null
}
}


Using AJAX to get data from the server


After we wrote the controller logic, we need to write the JS code that will receive data from the server and display it on the map. This code can be placed in the form submission handler, but first you need to set the correct action for the form:
action="${createLink(controller: 'twitter', action: 'friendsJson'}"

Then add the handler to index.gsp , like:

google.load( "maps" , "2.x" );
google.load( "jquery" , "1.3.1" );

google.setOnLoadCallback( function () {
$( document ).ready( function () {
// Create and configure Google Map control
var map = new GMap2( document .getElementById( "map" ));
var vinnitsa = new GLatLng( 49.2325477 , 28.4744695 );
map.setCenter(vinnitsa, 4 );
map.addControl( new GLargeMapControl());
// Add form submit handler
var form = $( "#twitter" );
form.submit( function () {
$.getJSON(form.attr( "action" ) + "?" + form.serialize(), function (data) {
// Clear all markers
map.clearOverlays();
// Loop through friends list and add markers to map
$.each(data, function (i, item) {
if (item.coords) {
var marker = new GMarker( new GLatLng(item.coords.latitude, item.coords.longitude));
map.addOverlay(marker);
var popup = '<img style="width: 48px; height:48px;" src="' + item.pictureUrl + '">' +
item.name + ' (' + item.screenName + ') <br>' +
item.bio + '<br>' + item.status;
GEvent.addListener(marker, "click" , function () {
marker.openInfoWindowHtml(popup);
});
}
});
});
// Indicate that form should not actually be submitted
return false ;
});
});
});


Now, when you enter a name and click on the button "Map my friends!" Get the following picture:

Geo Twitter Complete

Demo and source




It is useful to read more


Source: https://habr.com/ru/post/75774/


All Articles