Skip to content

About

Official Java client for the My Geocode API. Geocoding, reverse geocoding, autocomplete, IP, timezone, elevation and postcode lookups. Java 8+, no dependencies.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

My Geocode Java SDK

The official Java client for the My Geocode API: forward and reverse geocoding, address autocomplete, IPv4 and IPv6 lookup, timezones, elevation and postal codes.

Java 8 and newer Dependencies: none License: MIT

  • Works on every Java from 8 to 27, so it also runs on the Java 8 and 11 that many servers and older projects still use. No warnings on any of them, and nothing it uses is deprecated in any of them.
  • No dependencies. It uses only the JDK, with the JDK's own HttpURLConnection for HTTP.
  • Every method has an ...Async twin that returns a CompletableFuture.
  • Safe to drop into any project: no global settings, no system properties, no shared state outside the client. Results are read-only and safe to share between threads.
  • Usable from Kotlin, Scala and the other JVM languages.
  • 2,500 free requests a day without a key or an account.

Install

Maven:

<dependency>
  <groupId>com.mygeocode</groupId>
  <artifactId>mygeocode</artifactId>
  <version>1.1.1</version>
</dependency>

Gradle:

implementation("com.mygeocode:mygeocode:1.1.1")

Without a build tool, download mygeocode-1.1.1.jar from the releases page and put it on the class path. It is the only jar you need.

Quick start (no key)

import com.mygeocode.Client;
import com.mygeocode.ForwardResponse;
import com.mygeocode.Place;
import com.mygeocode.ReverseResponse;

Client client = Client.builder().build();

ForwardResponse found = client.forward("Brandenburg Gate, Berlin");
Place place = found.getResults().get(0);
System.out.println(place.getFormatted());                    // Brandenburg Gate, State of Berlin, Germany
System.out.println(place.getLat() + " " + place.getLon());   // 52.516268 13.377692

ReverseResponse address = client.reverse(48.8584, 2.2945);
System.out.println(address.getResult().getFormatted());      // 5 Avenue Anatole France, 75007 Paris, France

Without a key, each network gets 2,500 free requests a day. found.getMeta().getQuotaFreeRemaining() tells you how many are left. Make one client and share it: it is immutable and thread safe.

Using a key

A key adds your account's prepaid credit or Unlimited package on top of the free requests. Create one in the dashboard.

Client client = Client.builder().key("YOUR_KEY").build();

If you leave out the key, the client reads the MYGEOCODE_KEY environment variable. Pass key("") to make sure no key is sent. The key always travels in the X-API-Key header, never in the URL, and the SDK never writes it anywhere.

Language

Results are in English unless you set lang. Set it once on the client, or per call:

Client client = Client.builder().lang("de").build();

client.reverse(48.8584, 2.2945, new ReverseOptions().lang("fr")); // this call only

lang takes an ISO 639-1 code such as de, ja or pt-BR. The whole address comes back in that language and script. On its own, the API answers each result in the language of its area; the SDK sends lang=en by default so that every result reads the same.

Methods

Every method takes its main arguments first, then an options object with setters named after the API's own parameters in camelCase (placeId is the API's place_id, countryInfo is country_info). Each method has its own options class, such as ForwardOptions or ReverseOptions, so an option that does not belong to a method does not compile. The setters chain:

new ForwardOptions().limit(3).countries("de", "at").timezone(true)

Every options class also has:

  • params(Map) and param(name, value): more query parameters, sent as they are (and winning over the named options), so a parameter the API adds later works before the SDK knows it.
  • pretty(true) for indented JSON.

Pass null for no options. Points are Point.of(lat, lon), and lists of points are List<Point>.

Method Endpoint
forward GET /v1/forward
reverse GET /v1/reverse
autocomplete GET /v1/autocomplete
ip, ipv4, ipv6 GET /v1/ip, /v1/ipv4, /v1/ipv6
timezone GET /v1/timezone
elevation GET /v1/elevation
postcode GET /v1/postcode
forwardBatch POST /v1/forward
reverseBatch POST /v1/reverse
ipBatch, ipv4Batch, ipv6Batch GET /v1/ip, /v1/ipv4, /v1/ipv6 with ips
timezoneBatch GET /v1/timezone with locations
elevationBatch POST /v1/elevation

forward

Text, structured address fields or a place id to coordinates. Returns a ForwardResponse whose getResults() holds up to limit Place objects, best first. An empty list means nothing matched.

ForwardResponse found = client.forward("Brandenburg Gate, Berlin");
System.out.println(found.getResults().get(0).getFormatted()); // Brandenburg Gate, State of Berlin, Germany

client.forward("Brandenburg Gate, Berlin", new ForwardOptions().limit(3).countries("de"));
client.forward(null, new ForwardOptions().street("10 Downing Street").city("London").country("GB"));

ForwardOptions:

Option What it does
street, city, state, postcode, country Structured search instead of (or as well as) free text. Pass null as the query to search by these alone.
placeId Look up a place_id from an earlier result.
limit 1 to 10 results.
countries ISO 3166-1 alpha-2 codes to search in, such as countries("de", "at"). Also takes a Collection<String>.
bounds A box that results should fall in: bounds(south, west, north, east) or the API's own text.
strict Only return results inside bounds.
proximity Prefer results near this point: proximity(lat, lon) or a Point.
types Kinds of result to keep, such as address or poi.
lang Language of the result.
timezone, elevation, wikidata, countryInfo, codes, sun, regions, districts, census, demographics, road, site Each adds its extra block to every result.
annotations Adds every extra block at once.

reverse

A point to the nearest address. Returns a ReverseResponse whose getResult() is a Place, or null when nothing is in range.

ReverseResponse address = client.reverse(48.8584, 2.2945);
System.out.println(address.getResult().getFormatted());  // 5 Avenue Anatole France, 75007 Paris, France
System.out.println(address.getResult().getDistanceM());  // 47 (metres from the point you gave)

client.reverse(48.8584, 2.2945, new ReverseOptions().level("city").timezone(true));

ReverseOptions:

Option What it does
level address, street, postcode, city, region or country.
radius Search radius in metres, 1 to 5000.
lang Language of the result.
boundaries Add the administrative boundaries the point falls in (Australia).
timezone, elevation, wikidata, countryInfo, codes, sun, regions, districts, census, demographics, road, site Each adds its extra block, as for forward.
annotations Adds every extra block at once.

autocomplete

Suggestions while someone types an address. Returns an AutocompleteResponse with a getSuggestions() list; each Suggestion has getText(), getLat(), getLon(), getType(), getPrecision() and getPlaceId().

AutocompleteResponse typed = client.autocomplete("1600 Pennsylvania");
System.out.println(typed.getSuggestions().get(0).getText()); // 1600 Pennsylvania Avenue NW, Washington, DC 20500, United States

client.autocomplete("1600 Pennsylvania", new AutocompleteOptions().limit(5).countries("us"));

AutocompleteOptions: limit, countries, proximity, bounds, strict, types and lang, as for forward.

ip, ipv4, ipv6

Country, region, city, coordinates, timezone, network owner (ASN) and proxy, VPN and data centre flags for an IP address. ip takes either version; ipv4 and ipv6 accept only their own. Without an address you get the address the request came from. Returns an IpInfo.

IpInfo google = client.ip("8.8.8.8");
System.out.println(google.getCountry() + " " + google.getCity());   // United States Mountain View
System.out.println(google.getAsn() + " " + google.getAsName());     // 15169 Google LLC
System.out.println(google.getIsDatacenter());                       // true

client.ipv6("2001:4860:4860::8888");
client.ip();                                              // the address the request came from
client.ipv4("8.8.8.8", new IpOptions().elevation(true));  // adds elevation_m

IpOptions: elevation. The full list of IpInfo fields is under Results and meta.

timezone

The IANA zone, UTC offset, daylight saving state and local time for a point, now or at a given moment. Returns a TimezoneInfo.

TimezoneInfo tokyo = client.timezone(35.6762, 139.6503);
System.out.println(tokyo.getTimezone() + " " + tokyo.getUtcOffset());   // Asia/Tokyo +09:00
System.out.println(tokyo.getName() + " " + tokyo.getAbbreviation());    // Japan Standard Time JST
System.out.println(tokyo.getLocalTime());                               // 2026-11-24T18:07:15+09:00

client.timezone(35.6762, 139.6503, new TimezoneOptions().timestamp(1767225600L));
client.timezone(new TimezoneOptions().tz("Europe/Paris"));

TimezoneOptions:

Option What it does
tz Look up a zone by its IANA or Windows id instead of a point (use timezone(options) without lat and lon).
timestamp Unix time to answer for. Default: now.
lang Language of the zone name. Sent as the API's language parameter, only when you set it here or on the client. language works as another name for this option.
locations Several points: a List<Point>, "lat,lon|lat,lon" or an enc: polyline.
path, samples Points along a path, sampled samples times (2 to 100).
bounds, rows, cols A grid of points over a box.

For a plain list of points, timezoneBatch is simpler.

elevation

Height in metres above sea level (negative for the sea floor), from a global 15 arc-second grid. Returns an ElevationResponse whose getResults() holds ElevationPoint objects with getLat(), getLon(), getElevationM() and getResolutionM().

ElevationResponse everest = client.elevation(27.9881, 86.9250);
System.out.println(everest.getResults().get(0).getElevationM()); // 8627.0

client.elevation(new ElevationOptions().path(Arrays.asList(Point.of(27.9881, 86.9250), Point.of(28.0, 86.85))).samples(10));

ElevationOptions (use elevation(options) without lat and lon):

Option What it does
locations Several points.
path, samples Heights along a path.
bounds, rows, cols Heights over a grid.

postcode

A postal code to its place, region and coordinates. Returns a PostcodeResponse whose getResults() lists every place that uses the code.

PostcodeResponse nyc = client.postcode("10001", new PostcodeOptions().country("US"));
PostcodePlace first = nyc.getResults().get(0);
System.out.println(first.getPlace() + " " + first.getRegionCode());  // New York NY
System.out.println(first.getLat() + " " + first.getLon());           // 40.748401 -73.996702

client.postcode("75008", new PostcodeOptions().country("FR"));

PostcodeOptions: country (ISO alpha-2). Without it, the code is matched in every country.

forwardBatch

Up to 100 searches in one request (each counts as one request against your quota). Returns a ForwardBatchResponse whose getResults() holds one ForwardBatchEntry per search, in the order you sent them; each entry has the getQuery() and its own getResults() list of Place objects.

ForwardBatchResponse batch = client.forwardBatch(Arrays.asList("Brandenburg Gate, Berlin", "Sydney Opera House", "Statue of Liberty, New York"));
for (ForwardBatchEntry entry : batch.getResults()) {
    System.out.println(entry.getQuery() + ": " + entry.getResults().get(0).getFormatted());
}
// Brandenburg Gate, Berlin: Brandenburg Gate, State of Berlin, Germany
// Sydney Opera House: Sydney Opera House, Sydney, New South Wales, Australia
// Statue of Liberty, New York: Statue of Liberty, New York, New York, United States

client.forwardBatch(Arrays.asList("Brandenburg Gate, Berlin", "Sydney Opera House"), new ForwardBatchOptions().limit(1).timezone(true));

ForwardBatchOptions apply to every search in the batch:

Option What it does
limit 1 to 10 results per search.
countries, bounds, strict, proximity, types Filters for every search, as for forward.
lang Language of the results.
timezone, elevation, wikidata, countryInfo, codes, sun, regions, districts, census, demographics, road, site Each adds its extra block to every result.
annotations Adds every extra block at once.

Structured fields and placeId are not available in a batch; use forward for those.

reverseBatch

Up to 100 points in one request (each counts as one request). Returns a ReverseBatchResponse whose getResults() holds one ReverseResponse per point, in the order you sent them; its getResult() is a Place, or null when nothing is in range.

ReverseBatchResponse batch = client.reverseBatch(Arrays.asList(Point.of(48.8584, 2.2945), Point.of(40.6892, -74.0445), Point.of(-33.8568, 151.2153)));
for (ReverseResponse point : batch.getResults()) {
    System.out.println(point.getResult() != null ? point.getResult().getFormatted() : "nothing in range");
}
// 5 Avenue Anatole France, 75007 Paris, France
// 1 Liberty Island, New York, NY 10004, United States
// 2B Macquarie Street, Sydney NSW 2000, Australia

It takes the same ReverseOptions as reverse, applied to every point in the batch.

ipBatch, ipv4Batch, ipv6Batch

Up to 100 addresses in one request. ipBatch takes both versions mixed; ipv4Batch and ipv6Batch accept only their own. Returns an IpBatchResponse whose getResults() holds one IpInfo per address, in the order you sent them. An address the API cannot read gets an entry whose getStatus() is error and whose getError() explains why, while the rest still answer.

IpBatchResponse batch = client.ipv4Batch(Arrays.asList("8.8.8.8", "1.1.1.1", "9.9.9.9"));
for (IpInfo info : batch.getResults()) {
    System.out.println(info.getIp() + ": " + ("ok".equals(info.getStatus()) ? info.getAsName() : info.getError().get("message")));
}
// 8.8.8.8: Google LLC
// 1.1.1.1: Cloudflare, Inc.
// 9.9.9.9: Quad9

client.ipv6Batch(Arrays.asList("2001:4860:4860::8888", "2606:4700:4700::1111"));
client.ipBatch(Arrays.asList("8.8.8.8", "2606:4700:4700::1111"), new IpOptions().elevation(true));

IpOptions: elevation, adds elevation_m to every address.

timezoneBatch

Timezones for up to 100 points. Returns a TimezoneBatchResponse whose getResults() holds one TimezoneInfo per point, in the order you sent them.

TimezoneBatchResponse batch = client.timezoneBatch(Arrays.asList(Point.of(48.8584, 2.2945), Point.of(40.6892, -74.0445), Point.of(-33.8568, 151.2153)));
for (TimezoneInfo zone : batch.getResults()) {
    System.out.println(zone.getTimezone());
}
// Europe/Paris
// America/New_York
// Australia/Sydney

TimezoneBatchOptions: timestamp (Unix time, default now) and lang (also accepted as language), as for timezone. An encoded polyline goes in timezoneBatch("enc:...", options).

elevationBatch

Heights for up to 100 points, sent as a POST body. Returns an ElevationResponse.

ElevationResponse batch = client.elevationBatch(Arrays.asList(Point.of(48.8584, 2.2945), Point.of(40.6892, -74.0445), Point.of(-33.8568, 151.2153)));
for (ElevationPoint point : batch.getResults()) {
    System.out.println(point.getElevationM());
}
// 37.0
// 0.0
// 10.0

Async

Every method above has an ...Async twin with the same arguments that returns a CompletableFuture. An error completes the future exceptionally, with the SDK's exception as the cause.

CompletableFuture<TimezoneInfo> tokyo = client.timezoneAsync(35.6762, 139.6503);
CompletableFuture<ElevationResponse> everest = client.elevationAsync(27.9881, 86.9250);
System.out.println(tokyo.get().getTimezone() + " " + everest.get().getResults().get(0).getElevationM()); // Asia/Tokyo 8627.0

The calls run on a small pool of daemon threads that belongs to the SDK. To use your own, set Client.builder().executor(yourExecutor).

Results and meta

Results are read-only objects whose getters carry the API's own field names in camelCase (place_id is getPlaceId()), so the API documentation describes them field by field:

Place place = client.forward("Brandenburg Gate, Berlin").getResults().get(0);

place.getFormatted();                    // "Brandenburg Gate, State of Berlin, Germany"
place.getPrecision();                    // "house"
place.getComponents().getPoi();          // "Brandenburg Gate"
place.getComponents().getCountryCode();  // "de"
place.getComponents().getCity();         // null: not every address has every part

Numbers and booleans are boxed (Double, Long, Integer, Boolean), so a field the API did not send is null, never a made-up 0 or false. Check for null before you use one. The fields this SDK reads are never renamed or removed from the API: if one ever has to go, it keeps coming back as null, and your code keeps working. A list that comes back as null reads as an empty list, and the address parts in Components are always text.

Every result also has getRaw(), the decoded JSON as a read-only Map, so fields added to the API later are readable before the SDK knows them.

What each method returns, and the getters you can call (each getXxx() reads the API field of the same name):

Class Returned by Fields
ForwardResponse forward status, query, results (list of Place), meta
ReverseResponse reverse, each entry of reverseBatch status, lat, lon, result (Place or null), boundaries, meta
Place inside forward and reverse results formatted, lat, lon, type, precision, confidence, placeId, components, bounds, distanceM, formattedPlace, place, parcel, codes, population, unLocode, timezone, elevationM, wikidata, countryInfo, sun, regions, districts, census, demographics, road, intersection, site
Components Place.getComponents() poi, building, unit, level, houseNumber, road, lot, suburb, municipality, city, county, state, stateCode, postcode, country, countryCode, officialName
Bounds Place.getBounds() north, south, east, west
AutocompleteResponse autocomplete status, query, suggestions (list of Suggestion), meta
Suggestion inside autocomplete results text, lat, lon, type, precision, placeId
IpInfo ip, ipv4, ipv6, each entry of the IP batches status, ip, version, found, prefix, country, countryCode, continent, continentCode, region, regionCode, city, postcode, lat, lon, elevationM, timezone, utcOffset, utcOffsetSeconds, isEu, asn, asName, org, usageType, registry, allocated, tags, isAnycast, isSatellite, isDatacenter, isProxy, isVpnProvider, isTor, crawler, isPrivate, reason, abuseEmail, threat, updatedAt, error, meta
TimezoneInfo timezone, each entry of timezoneBatch status, lat, lon, timezone, name, abbreviation, utcOffset, utcOffsetSeconds, rawOffsetSeconds, dst, dstOffsetSeconds, timestamp, localTime, countryCode, isOcean, windowsTimezone, nextTransition (TimezoneTransition), meta
TimezoneTransition TimezoneInfo.getNextTransition() timestamp, utcOffset, utcOffsetSeconds, dst, abbreviation
ElevationResponse elevation, elevationBatch status, results (list of ElevationPoint), meta
ElevationPoint inside elevation results lat, lon, elevationM, resolutionM
PostcodeResponse postcode status, postcode, countryCode, results (list of PostcodePlace), meta
PostcodePlace inside postcode results postcode, place, region, regionCode, country, countryCode, lat, lon
ForwardBatchResponse forwardBatch status, results (list of ForwardBatchEntry), meta
ForwardBatchEntry inside forward batch results query, results (list of Place)
ReverseBatchResponse reverseBatch status, results (list of ReverseResponse), meta
IpBatchResponse ipBatch, ipv4Batch, ipv6Batch status, results (list of IpInfo), meta
TimezoneBatchResponse timezoneBatch status, timestamp, results (list of TimezoneInfo), meta

The extra blocks you ask for with the flags (timezone, elevation, wikidata and the rest) are fields of Place and stay plain read-only maps. getMeta() is null on an entry inside a batch; the batch response has the meta.

Every response has getMeta(), filled from the response headers (null when a header was not sent):

Getter Header Meaning
getRequestId() X-Request-Id Quote it when you contact support.
getQuotaLimit() X-Quota-Limit Free requests a day for this key's account or network.
getQuotaUsed() X-Quota-Used Free requests used today.
getQuotaFreeRemaining() X-Quota-Free-Remaining Free requests left today.
getQuotaReset() X-Quota-Reset Unix time when the free requests reset.
getCreditsRemaining() X-Credits-Remaining Prepaid credit left, when a key with credit is used.

Errors

Every exception the SDK throws is unchecked and extends MyGeocodeException:

Class When
ApiException The API answered with an error. getStatus() is the HTTP status, getCode() the API's error code (such as invalid_request, invalid_key or quota_exceeded), getMessage() its explanation, getParam() the parameter at fault, getRequestId(), getRetryAfter() (a Duration, or null) and getBody() (the decoded answer).
RequestTimeoutException No answer within timeout.
NetworkException The connection failed: DNS, refused, reset or TLS. getCause() holds the original exception.
DecodeException The answer could not be read as JSON.
try {
    client.forward("Brandenburg Gate, Berlin");
} catch (ApiException error) {
    System.out.println(error.getStatus() + " " + error.getCode() + " " + error.getMessage());
} catch (MyGeocodeException error) {
    System.out.println("Could not reach the API: " + error.getMessage());
}

The errors page lists every error code.

Retries

The client retries on its own, up to maxRetries times (default 2):

  • 429 (too many requests): waits for Retry-After, or until X-Quota-Reset. If that is longer than maxRetryWait (default 60 seconds), for example when the day's free requests are gone, it throws the ApiException straight away instead of waiting.
  • 500: tries once more after one second.
  • 503: waits for Retry-After, or 1, 2 and then 4 seconds.
  • Timeouts and connection errors: retried with the same 1, 2, 4 second pattern for GET requests. The POST batch calls are not retried after a connection error, so a batch is never charged twice.

Other errors are thrown at once.

Configuration

All options are optional:

Client client = Client.builder()
        .key("YOUR_KEY")                         // default: MYGEOCODE_KEY, else no key
        .baseUrl("https://api.mygeocode.com/v1")
        .timeout(Duration.ofSeconds(10))         // connect and read timeout of each attempt
        .maxRetries(2)
        .maxRetryWait(Duration.ofSeconds(60))
        .lang("en")
        .build();

The default transport follows the JVM's proxy and TLS settings (https.proxyHost, the default trust store). For a proxy just for this client, use .transport(new DefaultTransport(proxy)) with a java.net.Proxy. executor sets where the ...Async methods run. transport, sleep and clock replace the HTTP layer, the wait and the clock the retry logic uses; they are meant for tests, see below.

Testing your code (transport hook)

The client sends every request through its Transport: an interface with one method that takes an HttpRequest (getMethod(), getUrl(), getHeaders(), getBody(), getTimeout()) and returns an HttpResponse (status, headers, body text). Give it your own to test code that uses the SDK without touching the network:

Transport canned = request -> new HttpResponse(200, Collections.singletonMap("Content-Type", "application/json"),
        "{\"status\":\"ok\",\"lat\":48.8584,\"lon\":2.2945,"
        + "\"result\":{\"formatted\":\"5 Avenue Anatole France, 75007 Paris, France\",\"lat\":48.858821,\"lon\":2.294596}}");

Client client = Client.builder().transport(canned).sleep(wait -> { }).build(); // no real waiting in retry tests
System.out.println(client.reverse(48.8584, 2.2945).getResult().getFormatted()); // 5 Avenue Anatole France, 75007 Paris, France

The same hook plugs in any HTTP library, such as OkHttp or Apache HttpClient. Return every HTTP status as an HttpResponse, and throw an IOException only when no answer arrived: a SocketTimeoutException is read as a timeout, any other IOException as a network failure.

Running the SDK's own tests

The tests need nothing but the JDK, so the same suite runs on every version from 8 up. It answers from real recorded API responses and never calls the API:

mvn test

Without Maven, compile src/main/java and src/test/java with javac and run com.mygeocode.TestRunner. Anything written to standard error during the run counts as a failed test.

Requirements

  • Java 8 or newer. Tested on every release from 8 to 27 and on the Java 28 early access build: the release jar passes the whole test suite on each, and each of them compiles the source against its own JDK with every warning turned into an error (so nothing it uses is deprecated there).
  • Nothing else: no dependencies.
  • Android: the SDK uses java.time, which needs Android 8.0 (API 26) or core library desugaring. It has not been tested on Android.

Links

Licence

MIT. See LICENSE.

About

Official Java client for the My Geocode API. Geocoding, reverse geocoding, autocomplete, IP, timezone, elevation and postcode lookups. Java 8+, no dependencies.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages