杰瑞科技汇

如何在Java中集成Google Maps?

Of course! Using Google Maps in a Java application is a common requirement, but it's important to understand that you don't run the map inside a Java desktop application (like a Swing or JavaFX window). Instead, you typically embed an interactive map into a web page (HTML/JavaScript) and then use Java to serve that web page or interact with it via an API.

如何在Java中集成Google Maps?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the main approaches, from the most common to more advanced ones.


Approach 1: The Standard Way (Server-Side Rendering with Java)

This is the most common and practical approach for most applications. You use Java as a backend to generate an HTML page that contains the Google Map. The user's browser then renders the map.

Step-by-Step Guide: Creating a Simple Web Server with Java

Let's create a simple Java web server using the built-in com.sun.net.httpserver.HttpServer (for demonstration) or a framework like SparkJava (much easier and recommended).

Goal: A Java application that, when you visit http://localhost:4567, displays a webpage with an interactive Google Map centered on Sydney.

如何在Java中集成Google Maps?-图2
(图片来源网络,侵删)

Prerequisites:

  1. A Google Maps API Key:
    • Go to the Google Cloud Console.
    • Create a new project (e.g., "Java Map App").
    • Enable the Maps JavaScript API and Geocoding API for your project.
    • Go to "Credentials", create a new API Key, and copy it. Important: For production, you must restrict this key to prevent unauthorized use.

Option A: Using SparkJava (Recommended for Beginners)

SparkJava is a lightweight micro-framework that makes creating web servers in Java incredibly simple.

Add SparkJava Dependency: If you're using Maven, add this to your pom.xml:

<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-core</artifactId>
    <version>2.9.4</version>
</dependency>

Create the Java Server: Create a file named MapServer.java.

如何在Java中集成Google Maps?-图3
(图片来源网络,侵删)
import static spark.Spark.*;
public class MapServer {
    public static void main(String[] args) {
        // Set the port to listen on
        port(4567);
        // Define the route for the main page
        get("/", (req, res) -> {
            // Read the HTML template and return it
            return getHtmlTemplate();
        });
    }
    private static String getHtmlTemplate() {
        // Replace YOUR_API_KEY with your actual Google Maps API key
        String apiKey = "YOUR_API_KEY";
        return "<!DOCTYPE html>" +
               "<html>" +
               "<head>" +
               "    <title>Java Google Map</title>" +
               "    <style>" +
               "        #map { height: 100%; }" +
               "        html, body { height: 100%; margin: 0; padding: 0; }" +
               "    </style>" +
               "    <script async defer src=\"https://maps.googleapis.com/maps/api/js?key=" + apiKey + "&callback=initMap\"></script>" +
               "</head>" +
               "<body>" +
               "    <div id=\"map\"></div>" +
               "    <script>" +
               "        function initMap() {" +
               "            // The location of Sydney" +
               "            const sydney = { lat: -33.8688, lng: 151.2093 };" +
               "            // The map, centered at Sydney" +
               "            const map = new google.maps.Map(document.getElementById(\"map\"), {" +
               "                zoom: 12," +
               "                center: sydney," +
               "            });" +
               "            // The marker, positioned at Sydney" +
               "            new google.maps.Marker({" +
               "                position: sydney," +
               "                map: map," +
               "            });" +
               "        }" +
               "    </script>" +
               "</body>" +
               "</html>";
    }
}

Run the Application: Execute the MapServer.java file. You will see some output from SparkJava indicating the server is running.

View the Map: Open your web browser and navigate to http://localhost:4567. You should see an interactive map of Sydney with a marker!


Approach 2: JavaFX with a WebView (Desktop Application)

If you want to embed the map directly into a JavaFX desktop application, you can use the WebView component. This component is essentially a miniature web browser inside your app.

Add JavaFX Dependency: For modern Java projects (Java 11+), you need to include JavaFX modules. If using Maven:

<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>17</version>
</dependency>
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-web</artifactId>
    <version>17</version>
</dependency>

Create the JavaFX Application: Create a file named JavaFxMapApp.java.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class JavaFxMapApp extends Application {
    // IMPORTANT: Replace with your own API Key
    private static final String MAPS_API_KEY = "YOUR_API_KEY";
    private static final String HTML_MAP = "<!DOCTYPE html>\n" +
            "<html>\n" +
            "<head>\n" +
            "    <title>JavaFX Map</title>\n" +
            "    <style>\n" +
            "        html, body { height: 100%; margin: 0; padding: 0; }\n" +
            "        #map { height: 100%; width: 100%; }\n" +
            "    </style>\n" +
            "    <script async defer src=\"https://maps.googleapis.com/maps/api/js?key=" + MAPS_API_KEY + "\"></script>\n" +
            "</head>\n" +
            "<body>\n" +
            "    <div id=\"map\"></div>\n" +
            "    <script>\n" +
            "        function initMap() {\n" +
            "            const map = new google.maps.Map(document.getElementById(\"map\"), {\n" +
            "                center: { lat: -34.397, lng: 150.644 },\n" +
            "                zoom: 8\n" +
            "            });\n" +
            "        }\n" +
            "    </script>\n" +
            "</body>\n" +
            "</html>";
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("JavaFX Google Map");
        WebView webView = new WebView();
        webView.getEngine().loadContent(HTML_MAP);
        Scene scene = new Scene(webView, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}

Run the Application: Run the JavaFxMapApp.java file. A JavaFX window will appear containing the interactive map.


Approach 3: Using the Google Maps Platform APIs (Data-Driven)

Sometimes you don't need to display a map, but you need to get data from Google Maps. For this, you use Google's REST APIs directly from your Java code. This is perfect for backend services.

Common APIs:

  • Geocoding API: Convert addresses to coordinates (lat/lng) and vice-versa.
  • Directions API: Get routes, travel time, and distance between points.
  • Places API: Search for businesses, landmarks, etc.

Example: Geocoding an Address with Java

Add HTTP Client Dependency: Use a library like OkHttp or Apache HttpClient. Here's OkHttp in Maven:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.10.0</version>
</dependency>

Create the Java Code: This code fetches the coordinates for "1600 Amphitheatre Parkway, Mountain View, CA".

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class GeocodingApiExample {
    // IMPORTANT: Replace with your own API Key
    private static final String API_KEY = "YOUR_API_KEY";
    private static final OkHttpClient client = new OkHttpClient();
    public static void main(String[] args) {
        String address = "1600 Amphitheatre Parkway, Mountain View, CA";
        String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=" + API_KEY;
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // The response body contains the JSON data
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

When you run this, it will print a large JSON object containing the location details, including latitude and longitude.


Summary: Which Approach to Choose?

Approach Best For Pros Cons
Server-Side Rendering (Spark/Servlet) Web applications, websites, backend services that need to display a map. Mature, standard web development. Full control over the page. Requires a web server. The map is rendered client-side.
JavaFX WebView Desktop applications where you want to embed a map in a window. Creates a true desktop app feel. No separate web server needed. Tightly couples your app to JavaFX. Can be slower than a native browser.
Google Maps Platform APIs Backend services that need map data (coordinates, routes, places) without displaying a map. Powerful, data-driven. Can be used from any Java application. Does not provide a visual map. You have to handle JSON/XML parsing.

For most use cases, Approach 1 is the way to go. It's the standard, most flexible, and most widely used method for integrating Google Maps with a Java-based backend.

分享:
扫描分享到社交APP
上一篇
下一篇