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

  • Automatic Code Transformation With OpenRewrite
  • How to Quarantine a Malicious File in Java
  • Build Your Own GitHub-Like Tool With React in One Hour
  • Seamless Transition from Elasticsearch to OpenSearch

Trending

  • Advancing Robot Vision and Control
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • How to Perform Custom Error Handling With ANTLR
  • How to Use AWS Aurora Database for a Retail Point of Sale (POS) Transaction System
  1. DZone
  2. Coding
  3. Tools
  4. Router4j: A Free Alternative to Google Maps for Route and Distance Calculation

Router4j: A Free Alternative to Google Maps for Route and Distance Calculation

Router4j is a free and open-source tool for calculating routes and straight-line distances based on geographic coordinates — a free alternative to Google Maps.

By 
Thiago Nascimento user avatar
Thiago Nascimento
DZone Core CORE ·
Jan. 14, 25 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
4.6K Views

Join the DZone community and get the full member experience.

Join For Free

Google Maps is probably the first thing that comes to mind when considering a routing and distance calculation solution. However, its pricing may discourage its use in open-source projects or projects with severe budget constraints. This article will present two alternatives encapsulated by a free library known as router4j.

Geospatial APIs

As stated by its developer, Ryan McCaffery, the Geospatial API or simply geo.dev is:

a prototype to experiment with Geospatial Data from OpenStreetMap and explore Cloudflare Serverless Services.

The API offers three endpoints, as detailed in its documentation. For the scope of this article, only two are presented:

  • Text Search: Search the world with any text.
  • Distance: Calculate the distance in a straight line or as indicated in the documentation: as the crow flies.

Pros

  1. The project does not require any API key to use the endpoints.
  2. There is no restriction on the number of requests
  3. Low global latency for requests and responses

Cons

  1.  As assumed by its developer, the project is a prototype. So, there is no guarantee of API uptime.
  2. There is no route distance calculation — the most common distance used by applications that need to deal with the path length between two geolocated points.
  3. The Text Search endpoint is more imprecise than other APIs. As an example, searching for "Curitiba, Paraná," the smartest city in the world in the year 2023, the API returns seven records. Other APIs hit the nail on the head — just one record.

Open Route Service

The Open Route Service (ORS) is a project maintained by the Heidelberg Institute for Geoinformation Technology. According to the official documentation, the API:

consumes user-generated and collaboratively collected free geographic data, directly from OpenStreetMap.

The project is open source and freely available for all to download and contribute to on GitHub. The API is made up of nine endpoints, all of which are well-documented. Using the API requires registration to obtain a private key. Users can control the API usage through the dashboards available after login. An example is the "Token quota" table, which indicates the number of requests consumed and the number left. The quota is renewed every 24 hours.

Token quota

Token quota

This article will focus only on endpoints analogous to those provided by the Geospatial API.

  • Geocode Search Structured: Returns a formatted list of objects corresponding to the search input.
  • Matrix: Returns duration or routing distance matrix for multiple source and destination points.

Pros

  1. It is a well-supported and stable project which already serves relevant clients.
  2. Free token quota is suitable for small and medium-sized projects. Broader limits may be granted to humanitarian, academic, government, or non-profit organizations.

Cons

  1. The need to obtain an API token to consume the endpoints.
  2. The token quota is renewed only after 24 hours.

Router4j

Router4j is an open-source project that creates an abstraction layer over APIs focused on calculating routes and distances. Its first version includes only Geospatial and ORS APIs. To use the library in a Java project, simply add the Maven dependency to the pom.xml file.

XML
 
<dependency>
    <groupId>io.github.tnas</groupId>
    <artifactId>router4j</artifactId>
    <version>1.0.0</version>
</dependency>


The RouterApi main interface of router4j provides four methods:

Java
 
public interface RouterApi {

	Distance getRoadDistance(Point from, Point to, String apiKey);

	Locality getLocality(String name, String region, String apiKey);

	Locality getLocality(String name, String region, String country, String apiKey);
	
	ApiQuota getApiQuota();
}


The next code snippet describes how to look up the geographic coordinates of a place — "Curitiba, Paraná." The code will use the Geospatial API under the hood, as indicated by the first command that instantiates the GeoDevRouterApi class. Note that no API key is passed to the method getLocality as the underlying API does not require a private token.

Java
 
RouterApi geoDevRouterApi = new GeoDevRouterApi();
Locality locality = geoDevRouterApi.getLocality("Curitiba", "Paraná", null);
assertEquals(7, locality.getLocations().length);

var location = Stream.of(locality.getLocations())
    .filter(l -> l.getName().equals("Curitiba"))
    .findFirst()
    .orElse(null);
assertNotNull(location);
assertEquals(-49.28433, location.getPoint().getLongitude());
assertEquals(-25.49509, location.getPoint().getLatitude());
assertEquals("Curitiba", location.getName());
assertEquals("South Region", location.getRegion());


The code to calculate the distance is analogous to the above. But, in this case, as the ORS is the subjacent API, it is mandatory to pass the token - API Key.

Java
 
String apiKey = "ORS_API_TOKEN";
RouterApi orsRouterApi = new OrsRouterApi();

Point from = PointBuilder.newBuilder().apiType(ApiType.ORS)
    .longitude(-49.279708).latitude(-25.46005)
    .build();
Point to = PointBuilder.newBuilder().apiType(ApiType.ORS)
    .longitude(-50.311719).latitude(-23.302293)
    .build();

Distance distance = orsRouterApi.getRoadDistance(from, to, apiKey);

assertEquals(382.56, distance.getValue());
assertEquals(-25.46005, distance.getFrom().getLatitude());
assertEquals(-49.279708, distance.getFrom().getLongitude());
assertEquals(-23.302293, distance.getTo().getLatitude());
assertEquals(-50.311719, distance.getTo().getLongitude());
assertEquals(Metric.KM, distance.getMetric());


Conclusion

A very useful feature of the Google Maps API is the route distance calculation. There would be no downside to integrating it into applications (web and mobile) if it weren't for its pricing policy. In view of this, router4j arises as a very simple alternative to just one of the many features of Google Maps. As the project is in its early stages, only two underlying APIs are covered by the proposed abstraction layer. Despite this, the library can be a good option for projects that can use the ORS endpoints within the limits defined by the free quota. 

API Google Maps Open source Data Types Tool

Opinions expressed by DZone contributors are their own.

Related

  • Automatic Code Transformation With OpenRewrite
  • How to Quarantine a Malicious File in Java
  • Build Your Own GitHub-Like Tool With React in One Hour
  • Seamless Transition from Elasticsearch to OpenSearch

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!