Convert Figma logo to code with AI

googlemaps logogoogle-maps-services-java

Java client library for Google Maps API Web Services

1,709
947
1,709
38

Top Related Projects

OpenStreetMap-Tools for Android

Open source routing engine for OpenStreetMap. Use it as Java library or standalone web server.

Vector map library and writer - running on Android and Desktop.

Quick Overview

The googlemaps/google-maps-services-java repository is a Java client library for Google Maps API Web Services. It provides a set of Java interfaces to a variety of Google Maps APIs, allowing developers to easily integrate Google Maps functionality into their Java applications.

Pros

  • Comprehensive coverage of Google Maps APIs
  • Well-documented and maintained by Google
  • Type-safe and easy to use in Java projects
  • Supports both synchronous and asynchronous requests

Cons

  • Requires API key management and potential costs for API usage
  • Limited to server-side applications (not for Android)
  • Dependency on Google's services and potential API changes
  • May require additional libraries for certain features (e.g., JSON parsing)

Code Examples

  1. Geocoding an address:
GeoApiContext context = new GeoApiContext.Builder()
    .apiKey("YOUR_API_KEY")
    .build();
GeocodingResult[] results = GeocodingApi.geocode(context,
    "1600 Amphitheatre Parkway Mountain View, CA 94043").await();
System.out.println(results[0].formattedAddress);
  1. Calculating distance between two points:
DistanceMatrix matrix = DistanceMatrixApi.newRequest(context)
    .origins(new LatLng(40.6655101, -73.89188969999998))
    .destinations(new LatLng(40.6905615, -73.9976592))
    .mode(TravelMode.DRIVING)
    .await();
System.out.println(matrix.rows[0].elements[0].distance.humanReadable);
  1. Getting directions:
DirectionsResult result = DirectionsApi.newRequest(context)
    .origin("Sydney, AU")
    .destination("Melbourne, AU")
    .await();
System.out.println(result.routes[0].summary);

Getting Started

  1. Add the dependency to your project (Maven example):
<dependency>
    <groupId>com.google.maps</groupId>
    <artifactId>google-maps-services</artifactId>
    <version>2.1.2</version>
</dependency>
  1. Create a GeoApiContext with your API key:
GeoApiContext context = new GeoApiContext.Builder()
    .apiKey("YOUR_API_KEY")
    .build();
  1. Use the context to make API requests:
PlacesSearchResponse response = PlacesApi.nearbySearchQuery(context, new LatLng(51.5074, -0.1278))
    .radius(5000)
    .type(PlaceType.RESTAURANT)
    .await();

Remember to replace "YOUR_API_KEY" with your actual Google Maps API key.

Competitor Comparisons

OpenStreetMap-Tools for Android

Pros of osmdroid

  • Open-source and free to use without API key requirements
  • Supports offline map rendering and caching
  • More customizable with a wider range of map sources

Cons of osmdroid

  • Less comprehensive documentation and community support
  • May require more manual implementation for advanced features
  • Potentially less stable and optimized compared to Google's offering

Code Comparison

osmdroid:

MapView map = new MapView(context);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);

google-maps-services-java:

GeoApiContext context = new GeoApiContext.Builder()
    .apiKey("YOUR_API_KEY")
    .build();
GeocodingResult[] results = GeocodingApi.geocode(context, "1600 Amphitheatre Parkway").await();

Summary

osmdroid offers a free, open-source alternative to Google Maps with offline capabilities and customization options. However, it may require more effort to implement advanced features and has less extensive documentation. google-maps-services-java provides a more polished and well-supported solution but requires an API key and may have usage limitations. The choice between the two depends on project requirements, budget constraints, and desired features.

Open source routing engine for OpenStreetMap. Use it as Java library or standalone web server.

Pros of GraphHopper

  • Open-source and self-hosted, allowing for full control and customization
  • Supports multiple transportation modes (car, bike, foot, etc.)
  • Offers advanced routing features like turn restrictions and time-dependent routing

Cons of GraphHopper

  • Requires more setup and maintenance compared to Google Maps Services
  • May have less comprehensive global map data coverage
  • Limited integration with other Google services

Code Comparison

GraphHopper:

GraphHopper hopper = new GraphHopper();
hopper.setOSMFile("map.osm.pbf");
hopper.setGraphHopperLocation("graph-cache");
hopper.setEncodingManager(EncodingManager.create("car"));
hopper.importOrLoad();

Google Maps Services Java:

GeoApiContext context = new GeoApiContext.Builder()
    .apiKey("YOUR_API_KEY")
    .build();
DirectionsResult result = DirectionsApi.getDirections(context,
    "Sydney, AU", "Melbourne, AU").await();

Both libraries offer routing capabilities, but GraphHopper provides more flexibility for self-hosting and customization, while Google Maps Services Java offers easier integration with Google's ecosystem and global map data. The choice between them depends on specific project requirements, such as data control, coverage needs, and integration with other services.

Vector map library and writer - running on Android and Desktop.

Pros of mapsforge

  • Open-source and community-driven, allowing for more customization and flexibility
  • Supports offline map rendering, reducing dependency on internet connectivity
  • Lightweight and optimized for mobile devices, with a smaller footprint

Cons of mapsforge

  • Limited to OpenStreetMap data, which may not be as comprehensive as Google Maps
  • Requires more setup and configuration compared to Google Maps Services
  • May have fewer features and less frequent updates than Google's offering

Code Comparison

mapsforge:

MapView mapView = new MapView(context);
mapView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
mapView.setClickable(true);
mapView.getMapScaleBar().setVisible(true);
mapView.setBuiltInZoomControls(true);

google-maps-services-java:

GeoApiContext context = new GeoApiContext.Builder()
    .apiKey("YOUR_API_KEY")
    .build();
GeocodingResult[] results = GeocodingApi.geocode(context, "1600 Amphitheatre Parkway Mountain View, CA 94043").await();
System.out.println(results[0].formattedAddress);

The code examples demonstrate the different approaches: mapsforge focuses on map rendering and UI controls, while Google Maps Services emphasizes API interactions for geocoding and other services.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Java Client for Google Maps Services

Build Status Coverage Status Maven Central Version Javadocs GitHub contributors Stack Exchange questions

[!TIP] If you are looking for Java client libraries for the following APIs, see the Google Maps Platform APIs in the Cloud Client Libraries for Java (releases).

The new APIs will not be added to this client library.

Description

Use Java? Want to geocode something? Looking for directions? Maybe matrices of directions? This library brings the Google Maps API Web Services to your server-side Java application.

The Java Client for Google Maps Services is a Java Client library for the following Google Maps APIs:

Requirements

  • Java 1.8 or later
  • A Cloud project with the relevant API(s) enabled
  • An API key associated with the project above

API Key Security

The Java Client for Google Maps Services is designed for use in both server and Android applications. In either case, it is important to add API key restrictions to improve the security of your API key. Additional security measures, such as hiding your key from version control, should also be put in place to further improve the security of your API key.

You can refer to API Security Best Practices to learn more about this topic.

[!NOTE] If you are using this library on Android, ensure that your application is using at least version 0.19.0 of this library so that API key restrictions can be enforced.

Installation

You can add the library to your project via Maven or Gradle.

[!NOTE] Since 0.1.18 there is now a dependency on SLF4J. You need to add one of the adapter dependencies that makes sense for your logging setup. In the configuration samples below we are integrating slf4j-nop, but there are others like slf4j-log4j12 and slf4j-jdk14 that will make more sense in other configurations. This will stop a warning message being emitted when you start using google-maps-services.

Maven

<dependency>
  <groupId>com.google.maps</groupId>
  <artifactId>google-maps-services</artifactId>
  <version>(insert latest version)</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>1.7.25</version>
</dependency>

Gradle

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.google.maps:google-maps-services:(insert latest version)'
    implementation 'org.slf4j:slf4j-simple:1.7.25'
}

You can find the latest version at the top of this README or by searching Maven Central.

Documentation

View the javadoc.

Additional documentation for the included web services is available at https://developers.google.com/maps/.

Usage

This example uses the Geocoding API with an API key:

GeoApiContext context = new GeoApiContext.Builder()
    .apiKey("AIza...")
    .build();
GeocodingResponse response =  GeocodingApi.geocode(context,
    "1600 Amphitheatre Parkway Mountain View, CA 94043").await();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(response.results[0].addressComponents));

// Invoke .shutdown() after your application is done making requests
context.shutdown();

Note: The GeoApiContext is designed to be a Singleton in your application. Please instantiate one on application startup, and continue to use it for the life of your application. This will enable proper QPS enforcement across all of your requests.

At the end of the execution, call the shutdown() method of GeoApiContext, otherwise the thread will remain instantiated in memory.

For more usage examples, check out the tests.

Features

Google App Engine Support

To use Google App Engine with this client library add the latest App Engine dependency to your build.gradle file:

dependencies {
    implementation 'com.google.appengine:appengine-api-1.0-sdk:<latest version>'
}

You can then use this client library on Google App Engine with the following code change:

new GeoApiContext.Builder(new GaeRequestHandler.Builder())
    .apiKey("AIza...")
    .build();

The new GaeRequestHandler.Builder() argument to GeoApiContext.Builder's requestHandlerBuilder tells the Java Client for Google Maps Services to utilise the appropriate calls for making HTTP requests from Google App Engine, instead of the default OkHttp3 based strategy.

Rate Limiting

Never sleep between requests again! By default, requests are sent at the expected rate limits for each web service, typically 50 queries per second for free users. If you want to speed up or slow down requests, you can do that too, using new GeoApiContext.Builder().queryRateLimit(qps).build(). Note that you still need to manually handle the delay between the initial request and successive pages when you're paging through multiple result sets.

Retry on Failure

Automatically retry when intermittent failures occur. That is, when any of the retriable 5xx errors are returned from the API.

To alter or disable automatic retries, see these methods in GeoApiContext:

  • .disableRetries()
  • .maxRetries()
  • .retryTimeout()
  • .setIfExceptionIsAllowedToRetry()

POJOs

Native objects for each of the API responses.

Asynchronous or synchronous -- you choose

All requests support synchronous or asynchronous calling style.

GeocodingApiRequest req = GeocodingApi.newRequest(context).address("Sydney");

// Synchronous
try {
    req.await();
    // Handle successful request.
} catch (Exception e) {
    // Handle error
}

req.awaitIgnoreError(); // No checked exception.

// Async
req.setCallback(new PendingResult.Callback<GeocodingResponse>() {
  @Override
  public void onResult(GeocodingResponse result) {
    // Handle successful request.
  }

  @Override
  public void onFailure(Throwable e) {
    // Handle error.
  }
});

Building the Project

[!NOTE] You will need an API key to run the tests.

# Compile and package the project
$ ./gradlew jar

# Run the tests
$ ./gradlew test

Terms

This library uses Google Maps Platform services. Use of Google Maps Platform services through this library is subject to the Google Maps Platform Terms of Service.

This library is not a Google Maps Platform Core Service. Therefore, the Google Maps Platform Terms of Service (e.g. Technical Support Services, Service Level Agreements, and Deprecation Policy) do not apply to the code in this library.

Support

This library is offered via an open source license. It is not governed by the Google Maps Platform Support Technical Support Services Guidelines, the SLA, or the Deprecation Policy (however, any Google Maps Platform services used by the library remain subject to the Google Maps Platform Terms of Service).

This library adheres to semantic versioning to indicate when backwards-incompatible changes are introduced. Accordingly, while the library is in version 0.x, backwards-incompatible changes may be introduced at any time.

If you find a bug, or have a feature request, please file an issue on GitHub. If you would like to get answers to technical questions from other Google Maps Platform developers, ask through one of our developer community channels. If you'd like to contribute, please check the Contributing guide in the GitHub repository.