Nov
16
2008

Tutorial: Google Maps with Java, GWT and Eclipse

The intention of this tutorial is to show how to use eclipse to develop a rich internet application with GWT that contains a Google Maps-map. The focus is less on the API provided by the Google Maps-wrapper for GWT, but how to use eclipse as a comfortable IDE. Google itself provides a very comprehensive example (source code) that demonstrates the possibilities of the wrapper.

UPDATE (01/07/09): Since there is some discussion about how to put this tutorial into action, I decided to provide a zip file containing the finished eclipse workspace of this tutorial: tutorialgwtmaps. Don’t forget to update the build path and the GWT home folder!

UPDATE 2 (01/14/09): Code Formatted.

Preliminaries
Download the required software and sign for a Google Maps API-key.

  1. Download and install the Java SE Development Kit
    You need the JDK to run Eclipse, the GWT Hosted Mode-Browser and the GWT-Compiler. On MacOS the JDK is installed by default, for other operating systems you can download the JDK from Sun.
  2. Download and unzip the Eclipse IDE for Java EE Developers
    Download Eclipse for EE Developers. You can unzip Eclipse to whereever you like, for example into the folder applications or programs.
  3. Download the Google Web Toolkit
    GWT is available at code.google.com. Download and unzip it to whereever you like.
  4. Download und install Cypal Studio for GWT
    Cypal Studio is a Eclipse plugin that integrates GWT into Eclipse the build process and the launch process. Unzip the plugin jars into <Eclipse home>/dropins/Cypal/plugins. You have to manually create the Cypal and plugins directories (installation manual).
  5. Download and unzip the Google Maps-library for GWT
    The Google Maps-library for GWT wrappes the javascript necessary to run Google Maps on your website. Download and unzip the library to whereever you like.
  6. Sign up for a Google Maps Api-Key
    This step is optional for development on your local computer (localhost). You can sign up for a key here.

Setup the eclipse workspace
Configure the eclipse workspace and project. This section contains only the configuration of eclipse, no source code that you would check in for example into svn.

  1. Eclipse Workspace
    Open Eclipse and choose a directory as workspace (project configuration and source code will/can be stored here).

    When Eclipse has started, you will see the welcome screen:

    Close the Welcome screen with the arrow on the right side and the workspace is displayed:
  2. Configuration of Cypal Studio
    Open the Preferences Dialog (Eclipse/Preferences on MacOS or Window/Preferences) and select Cypal Studio on the left side. Then Enter the folder where the Google Web Tookit is located and click OK:
  3. Create the GWT-Project
    Select File/New/Dynamic Web Project. Enter MyFirst Google Maps Application as project name and select Cypal Studio for GWT as configuration, then click Next.

    You can leave the default values on the next page and click Finish.

    You will see a new project on the left side in the project explorer:
  4. Add the Google Maps-library to the Java Build Path
    Rightclick your new project and select Properties in the popup menu, then select Java Build Path on the left side and Libraries on the top. Click Add External JARs… and add the file gwt-maps.jar located in the Google Maps for GWT-library.

Your first Google Maps-application
This section handles the source code and configuration files. It adjusts the GWT-template to create a Google Maps-map.

  1. Create a GWT Module
    Select File/New/Other…, then Cypal Studio/GWT Module and click Next:

    Enter a package (e.g.: com.claudiushauptmann.gwt.maps.samples) and a name for the module (e.g.: MyFirstMapsModule) and click Finish.

    Your workspace will look like this with 3 new files. A Java class with the module, a wrapper-html-file and a xml-file that defines the GWT-Module:
  2. Configure your project for Google Maps
    Add <inherits name=”com.google.gwt.maps.GoogleMaps”/> and<script src=”http://maps.google.com/maps?gwt=1&amp;file=api&amp;v=2″ /> to your Module XML-file (e.g.: MyFirstMapsModule.gwt.xml). You can enter your API-Key here (optional for localhost).

    <module>
    
    	<!-- Inherit the core Web Toolkit stuff.                  -->
    	<inherits name='com.google.gwt.user.User'/>
    
    	<inherits name="com.google.gwt.maps.GoogleMaps"/>
    	<script src="http://maps.google.com/maps?gwt=1&amp;amp;file=api&amp;amp;v=2" />
    
    	<!-- Specify the app entry point class.                   -->
    	<entry-point class='com.claudiushauptmann.gwt.maps.samples.client.MyFirstMapsModule'/>
    
      	<inherits name="com.google.gwt.user.theme.standard.Standard"/>
      	<!-- <inherits name="com.google.gwt.user.theme.chrome.Chrome"/> -->
      	<!-- <inherits name="com.google.gwt.user.theme.dark.Dark"/> -->
    
    </module>
    
  3. Add some code that inserts a MapWidget into the web page:
    package com.claudiushauptmann.gwt.maps.samples.client;
    
    import com.google.gwt.core.client.EntryPoint;
    import com.google.gwt.maps.client.MapWidget;
    import com.google.gwt.maps.client.control.MapTypeControl;
    import com.google.gwt.maps.client.control.SmallMapControl;
    import com.google.gwt.maps.client.event.MapClickHandler;
    import com.google.gwt.maps.client.geom.LatLng;
    import com.google.gwt.maps.client.overlay.Marker;
    import com.google.gwt.maps.client.overlay.Overlay;
    import com.google.gwt.user.client.ui.RootPanel;
    
    public class MyFirstMapsModule implements EntryPoint {
    
    	public void onModuleLoad() {
    		MapWidget mapWiget = new MapWidget(LatLng.newInstance(48.136559, 11.576318), 13);
    		mapWiget.setSize("500px", "300px");
    
    	    mapWiget.addControl(new SmallMapControl());
    	    mapWiget.addControl(new MapTypeControl());
    
    	    mapWiget.addMapClickHandler(new MapClickHandler() {
    	      public void onClick(MapClickEvent e) {
    	        MapWidget sender = e.getSender();
    	        Overlay overlay = e.getOverlay();
    	        LatLng point = e.getLatLng();
    
    	        if (overlay != null &amp;&amp; overlay instanceof Marker) {
    	          sender.removeOverlay(overlay);
    	        } else {
    	          sender.addOverlay(new Marker(point));
    	        }
    	      }
    	    });
    
    	    RootPanel.get().add(mapWiget);
    	}
    }
    

The launch configuration
Now we want to run and debug our application. First we debug it in the Hosted Mode-Browser, the we compile it to javascript and open it with a standard internet browser.

  1. Create a launch configuration and start debugging
    Select Run/Debug Configurations… and create a new launch configuration with the button on the top left. Enter a name for the launch configuration and selct your project and your module, then click Apply.
  2. Debugging
    Click Debug and the Hosted Mode-browser starts:
  3. Compile and run in your Browser
    Click Compile/Browse, wait some seconds and your standard browser will open and show your application:

It would give me a great pleasure, if you wrote a short comment, whether this tutorial was helpful!

36 Comments »

  • [...] Tutorial: Google Maps with Java, GWT and Eclipse A step-by-step tutorial showing how to use Cypal Studio and the Google Maps APIs. [...]

    Pingback | November 19, 2008
  • Tyler Tallman

    This was helpful to me As would any other tutorial of small projects with cypal studios.

    Thanks

    Comment | November 19, 2008
  • Tembargo

    Very good tutorial !
    Thank you!
    (A french guy)

    Comment | November 20, 2008
  • getulio

    Very nice tutorial.
    Thank you.

    Comment | November 28, 2008
  • kasper

    hi, thanks a bunch.

    i found it really helpful !
    :-)

    Comment | December 3, 2008
  • Raid

    Very good tutorial and well explained.
    Thank you for your work.
    (A Spanish guy)

    Comment | December 9, 2008
  • Excellent, thanks a bunch.

    I struggled a little with “Configure your project for Google Maps” but that’s me being a C++ coder not JEE (culture shock!).

    My work is on my employer’s internal server right now but I’ll be putting some work on my own site later.

    Comment | December 9, 2008
  • Mark

    This was very well written thank you so much. Screen shots were nicely done. Got me started and setup very quickly.

    Comment | December 18, 2008
  • Kedzior

    Hi,
    I have got sth error:

    [ERROR] Unable to load module entry point class com.claudiushauptmann.gwt.maps.samples.client.MyFirstMapsModule (see associated exception for details)
    java.lang.RuntimeException: The Maps API has not been loaded.
    Is a tag missing from your host HTML or module file? Is the Maps key missing or invalid?
    at com.google.gwt.maps.client.Maps.assertLoaded(Maps.java:29)
    at com.google.gwt.maps.client.geom.LatLng$.newInstance(Native Method)
    at com.claudiushauptmann.gwt.maps.samples.client.MyFirstMapsModule.onModuleLoad(MyFirstMapsModule.java:16)

    Could anyone help me ?

    Comment | December 21, 2008
  • Claudius Hauptmann

    Did you add <inherits name=”com.google.gwt.maps.GoogleMaps”/> and <script src=”http://maps.google.com/maps?gwt=1&file=api&v=2″ /> to your Module XML-file (e.g.: MyFirstMapsModule.gwt.xml)?

    Comment | December 21, 2008
  • [...] you are looking for help how to use this library with your own google maps-mashup, my tutorial might be useful. Don’t forget to additionally add both jar-files of GXT and gwt-maps-gxt to [...]

    Pingback | December 21, 2008
  • Kedzior

    Claudius Hauptmann – I’ve done everything like you wrote ;/ If I don’t using Google Maps API but only GWT everything is OK, code(another) is working, but if i try to plece there some code using GMAPS i have error – for ex:
    ———Hello.java———

    package hellogwt.hello.client;
    import com.google.gwt.core.client.EntryPoint;
    import com.google.gwt.maps.client.MapWidget;
    import com.google.gwt.maps.client.geom.LatLng;
    import com.google.gwt.user.client.ui.RootPanel;

    public class Hello implements EntryPoint {
    public void onModuleLoad() {
    MapWidget mapWiget = new MapWidget(LatLng.newInstance(48.136559,11.576318), 5);
    mapWiget.setSize(”500px”, “300px”);
    RootPanel.get().add(mapWiget);
    }
    }

    ——-Hello.gwt.xml——–

    Hello.html is stay like that generated by Cypal Module.

    Any sugestion ? if no – may be someone who got working examle can send me eclipse project or sth like this

    Comment | December 21, 2008
  • Kedzior

    I see xml file code is invisible ;/

    Comment | December 21, 2008
  • Claudius Hauptmann

    The problem is, that eather the Google Maps-API is not referenced or could not be loaded, since the computer is offline for example.

    Comment | December 22, 2008
  • Kedzior

    Hi, everytime i tried run it my computer was online.
    Now i run everything outside eclipse (by projectCreator etc) and it run with API key only (at localhost). Anyway thanks for help – and good tutorial – it help me very much.

    Comment | December 23, 2008
  • Alper

    There is an error while compiling ? please help
    -style should be followed by one of
    OBF, PRETTY, or DETAILED
    Google Web Toolkit 1.5.3
    GWTShell [-port port-number | "auto"] [-noserver] [-whitelist whitelist-string] [-blacklist blacklist-string] [-logLevel level] [-gen dir] [-out dir] [-style style] [-ea] [url]

    where
    -port Runs an embedded Tomcat instance on the specified port (defaults to 8888)
    -noserver Prevents the embedded Tomcat server from running, even if a port is specified
    -whitelist Allows the user to browse URLs that match the specified regexes (comma or space separated)
    -blacklist Prevents the user browsing URLs that match the specified regexes (comma or space separated)
    -logLevel The level of logging detail: ERROR, WARN, INFO, TRACE, DEBUG, SPAM, or ALL
    -gen The directory into which generated files will be written for review
    -out The directory to write output files into (defaults to current)
    -style Script output style: OBF[USCATED], PRETTY, or DETAILED (defaults to OBF)
    -ea Debugging: causes the compiled output to check assert statements.
    and
    url Automatically launches the specified URL

    Comment | December 25, 2008
  • Dimitris

    i try to edit the xml file adding hte code you proposed ( i also copied and pasted your xml-section with the appropriate modifications) but i get an error from eclipse:

    Description Resource Path Location Type
    The reference to entity “file” must end with the ‘;’ delimiter.

    the referred line

    Comment | December 25, 2008
  • Kedzior

    Dimitris – I must add “;” like this:

    You need change & to &amp;

    I hope it will help you

    Comment | December 30, 2008
  • Claudius Hauptmann

    Thats right. Thank you, Kedzior! My Blog does not display the xml file correctly, please change “&” to “&amp;” in the script tag.

    Comment | January 2, 2009
  • Cohen

    to Kedzior :
    I have the same error.I found the reason is the “Hello.html” must hava the tag <meta http-equiv=”content-type” content=”text/html; charset=UTF-8″> between tag,then it’s ok.

    Comment | January 3, 2009
  • cristian

    muy buen tutorial EXCELENTE!!!!!

    Comment | January 13, 2009
  • Yes, it was helpful, thanks!

    Comment | January 15, 2009
  • Thamak

    Very helpful but how can I do if I want to set the map on Paris at the beginning ?

    Comment | January 21, 2009
  • ahmdalitaha

    that is a great tutorial and i did like it very much
    but i wanted to know how to make that on another server i mean not on localhost

    Comment | February 10, 2009
  • Claudius Hauptmann

    Hi ahmdalitaha,
    when you want to deploy your web application that uses gwt-maps to your server, you just have to add an API key to the script tag, that matches your domain name. Google explains this very well on the official Google Maps site.
    http://code.google.com/apis/maps/signup.html

    Comment | February 10, 2009
  • clay

    Thanks for the tutorial!

    Comment | February 16, 2009
  • Romeryto Lira

    Hi!!! How to change the marker color?

    Comment | March 13, 2009
  • I want to thank you for this tutorial, but I have a problem: why did google decided to limit the detail on countries like Romania ? I have to do a project on GPS Traking Device and it seems that google is not helping me as I was expected … ?

    Comment | March 15, 2009
  • [...] tutorial (http://claudiushauptmann.com/tutorial-google-maps-with-java-gwt-and-eclipse.html) recommends using the Cypal plugin: http://www.cypal.in/studio page_revision: 2, last_edited: [...]

    Pingback | March 25, 2009
  • Kushal

    The map is not being displayed on the browser running on the local host. it is displaying all other contents except for the map. Pl help us.

    Comment | March 31, 2009
  • MG

    Hello Claudius, This tutorial is really good and useful. However i am getting following error in MyFirstMapsModule.java class
    : amp cannot be resolve
    : Syntax error on token “;”,. expected

    Online number 28

    I am using exactly the same code as you mentioned above in the tutorial. Please help!!!!

    Comment | April 2, 2009
  • Claudius Hauptmann

    @MG: I think this is a problem of my weblog, which html-encoded the xml code. Please try to download the zipped eclipse workspace und copy the xml code from there. And please write, if it will be working then.

    @Romeryto Lira: The marker is a small PNG-image. You cannot change the color, but you can use your own icon with another color. The sample application of the Google Maps wrapper for GWT should have such an example.

    @Kushal: Could you please explain the problem a little bit more in detail? Are some other widgets visible? Perhaps the whole GWT code does not work and only the html code out of the host page is visible?

    @Florin: Google does not create the map data itselve, but buyes it. When you look at the border between two countries you will see a big difference in detail in most map types.

    @Thamak: Why do you want to choose Paris at the beginning? Munich is great! You have to use the “LatLng” of Paris: 51.151786,10.415039

    @ahmdalitaha: This is a GWT topic and explained within the documentation of the official GWT site: http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=FAQ_PackageAppInWARFile

    Comment | April 3, 2009
  • monthofcrow

    Simple. Effective. Thanks!

    Stay clear of the Cypal 2.0…..

    Comment | April 25, 2009
  • Pankaj

    Was gr8.. my first to learn with maps…

    Comment | May 7, 2009
  • [...] som används för att programmera till de flesta kartor som till exepel google maps, med java. Claudius Hauptmann är en annan bra resurs som skrivit ett par artiklar om programmering till google maps. [...]

    Pingback | May 10, 2009
  • feras

    hallo leute ,

    kann mich jemand helfen ? . ich benötige informationen darüber, wie ich mit Java (GWT) im googleMaps API einen Route mit farbige Markierung (keine luft-linie sondern detaliertere Route-Zeichnung) zwischen zwei Latlng (orten) kodieren kann. ???

    danke

    Comment | June 17, 2009

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress. Theme: TheBuckmaker