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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

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
  • A Systematic Approach for Java Software Upgrades

Trending

  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Memory Leak Due to Time-Taking finalize() Method
  • Infrastructure as Code (IaC) Beyond the Basics
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  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.

By 
Vladimir Ikryanov user avatar
Vladimir Ikryanov
·
Mar. 22, 14 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
152.4K 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
  • A Systematic Approach for Java Software Upgrades

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!