DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Keep Your Application Secrets Secret
  • How To Build a Google Photos Clone - Part 1
  • Google Cloud Pub/Sub: Messaging With Spring Boot 2.5
  • 10 Ways To Keep Your Java Application Safe and Secure

Trending

  • The State of Data Streaming for Digital Natives (Born in the Cloud)
  • Monetizing APIs: Accelerate Growth and Relieve Strain on Your Engineers
  • Understanding Europe's Cyber Resilience Act and What It Means for You
  • A Continuous Testing Approach to Performance
  1. DZone
  2. Coding
  3. Java
  4. Google Maps in Java Swing Application

Google Maps in Java Swing Application

If you need to embed and display Google Maps in your Java Desktop Swing application, then JxBrowser Java library is what you need.

Vladimir Ikryanov user avatar by
Vladimir Ikryanov
·
Mar. 22, 14 · Tutorial
Like (6)
Save
Tweet
Share
150.55K Views

Join the DZone community and get the full member experience.

Join For Free

If you need to embed and display Google Maps in your Java Desktop Swing application, then JxBrowser Java library is what you need.

JxBrowser is a cross-platform Java library that allows embedding Google Chromium-based web browser component into Java Swing applications to display web pages built with HTML5, CSS3, JavaScript, AJAX etc. The Browser component that displays web pages is totally lightweight, so you can forget about well known “Mixing heavyweight and lightweight components in Java Swing” issue.

In order to embed and display Google Maps in your Java Desktop application you just need to create Browser instance, embed it into JFrame or any other Swing container and load the http://maps.google.com web page. The following simple example demonstrates how to do this:

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import javax.swing.*;
import java.awt.*;

public class GoogleMapsSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame("JxBrowser Google Maps");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("http://maps.google.com");
    }
}

In this example we create Browser instance, embed it into JFrame and load http://maps.google.com into it to display Google Maps.

Once you compile and run this GoogleMapsSample in your favorite Java IDE you should see the following output:

You can find the instruction about how to use JxBrowser in your Java application in JxBrowser Programmer’s Guide.

What if we need to communicate with the loaded map from Java code? For example, provide user with ability to zoom in/out of the map from Java Swing application. In this case we need to communicate with Google Maps API via JavaScript. JxBrowser API allows executing any JavaScript code on the loaded web page.

To work with the loaded Map we need to use google.maps.Map JavaScript object. Since Google updates http://maps.google.com  very often, you may not know how to access this object on the loaded web page. To avoid this issue I recommend that you embed Google Maps using your own HTML file. You just need to create the map.html file with the following content:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    </style>
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7J1zsErb9_7jxNu5KU5kIENFObAQEbl0&sensor=false">
    </script>
    <script type="text/javascript">
      var map;
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(48.209331, 16.381302),
          zoom: 4
        };
        map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map-canvas"/>
  </body>
</html>

And load the map.html file using the following method:

browser.loadURL("C:\\map.html");

The output should be the following:


Now we can access google.maps.Map JavaScript object and invoke its zoom in/out methods. To change zoom of the map we can use the map.setZoom(zoom:number) method. Let’s add zoom in/out buttons in our example:

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GoogleMapsSample {

    public static final int MIN_ZOOM = 0;
    public static final int MAX_ZOOM = 21;

    /**
     * In map.html file default zoom value is set to 4.
     */
    private static int zoomValue = 4;

    public static void main(String[] args) {
        final Browser browser = BrowserFactory.create();

        JButton zoomInButton = new JButton("Zoom In");
        zoomInButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (zoomValue < MAX_ZOOM) {
                    browser.executeJavaScript("map.setZoom(" + ++zoomValue + ")");
                }
            }
        });

        JButton zoomOutButton = new JButton("Zoom Out");
        zoomOutButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (zoomValue > MIN_ZOOM) {
                    browser.executeJavaScript("map.setZoom(" + --zoomValue + ")");
                }
            }
        });

        JPanel toolBar = new JPanel();
        toolBar.add(zoomInButton);
        toolBar.add(zoomOutButton);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.add(toolBar, BorderLayout.NORTH);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("C:\\map.html");
    }
}

Now you can zoom in/out the map directly from Java Swing application:


Using JxBrowser API you can invoke other methods of the google.maps.Map JavaScript object to access all the required functionality of Google Maps in your Java Swing application.

Useful Links:

  • Google Maps API: https://developers.google.com/maps/documentation/javascript/reference
  • JxBrowser: http://www.teamdev.com/jxbrowser
  • JxBrowser API: https://s3.amazonaws.com/cloud.teamdev.com/downloads/jxbrowser/javadoc/index.html
  • JxBrowser Programmer’s Guide: http://cloud.teamdev.com.s3.amazonaws.com/downloads/jxbrowser/docs/JxBrowser-PGuide.html
  • Samples: https://sites.google.com/a/teamdev.com/jxbrowser-support/samples
  • Licensing: http://www.teamdev.com/jxbrowser#licensing-pricing
Google Maps Java Swing Java (programming language) application Google (verb)

Opinions expressed by DZone contributors are their own.

Related

  • Keep Your Application Secrets Secret
  • How To Build a Google Photos Clone - Part 1
  • Google Cloud Pub/Sub: Messaging With Spring Boot 2.5
  • 10 Ways To Keep Your Java Application Safe and Secure

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: