926 words, 5 minutes read time.


Mastering TypeScript: Build enterprise-ready, modular web applications using TypeScript 4 and modern frameworks, 4th Edition
Introduction
Calculating distances between two locations is a common task in many applications. Whether you’re building a delivery service app or simply need to show driving distances in your project, integrating external APIs can save you time and effort. In this blog post, we’ll guide you through building a Mileage Calculator app using C# and the OSRM (Open Source Routing Machine) API. This app will calculate the driving distance between two addresses, and we’ll highlight the key steps to help you get started.
The full source code for the Mileage Calculator app is available for download on GitHub, but let’s go over the key parts of the code so you understand how it all fits together.
Why Use the OSRM API for Mileage Calculation?
The OSRM API is a fast, open-source routing engine that calculates routes and distances based on OpenStreetMap data. It supports multiple modes of transportation, such as driving, cycling, and walking. For our app, we’ll focus on using OSRM to calculate driving distances between two addresses.
Here’s why it’s a good choice for mileage calculation:
- Free and open-source: No API key required to use the service.
- Fast and accurate: Delivers real-time routing data based on current OpenStreetMap data.
- Scalable: Handles many requests efficiently, which is perfect for apps that need routing and distance calculations.
Key Steps in Building the Mileage Calculator
Now let’s dive into the highlights of the app’s core features.
1. Set Up the User Interface
For simplicity, the user interface (UI) consists of two textboxes for input (tbFrom, tbTo) and a button (btnGetMileage) to trigger the mileage calculation.
This basic UI setup is straightforward in Windows Forms. The actual layout and controls can be designed using the Visual Studio Form Designer, with two textboxes for entering the addresses and a button to trigger the API calls.
2. Integrate with the Nominatim API for Address Geocoding
Before calculating the distance, we need to convert the human-readable addresses into geographical coordinates (latitude and longitude). For this, we use the Nominatim API (a geocoding service based on OpenStreetMap data).
Here’s the key part where we query Nominatim for both the starting and destination addresses:
string urlFrom = $"https://nominatim.openstreetmap.org/search?format=json&q={fromAddress}";
HttpResponseMessage responseFrom = await client.GetAsync(urlFrom);
string responseDataFrom = await responseFrom.Content.ReadAsStringAsync();
dynamic dataFrom = JsonConvert.DeserializeObject(responseDataFrom);
double fromLat = dataFrom[0].lat;
double fromLon = dataFrom[0].lon;
This code sends a request to the Nominatim API and extracts the latitude and longitude from the response. The same logic is applied for the destination address (toAddress).
3. Calculate the Distance Using OSRM API
Once we have the coordinates for both addresses, the next step is to calculate the driving distance using the OSRM API. We send a request to the OSRM routing engine, which returns the driving distance between the two coordinates.
Here’s the request to the OSRM API:
string osrmUrl = $"http://router.project-osrm.org/route/v1/driving/{fromLon},{fromLat};{toLon},{toLat}?overview=false";
HttpResponseMessage osrmResponse = await client.GetAsync(osrmUrl);
string osrmResponseData = await osrmResponse.Content.ReadAsStringAsync();
The OSRM API responds with the distance (in meters), which we convert to kilometers and miles for display:
dynamic osrmData = JsonConvert.DeserializeObject(osrmResponseData); double distanceMeters = osrmData.routes[0].legs[0].distance; double distanceKm = distanceMeters / 1000; // Convert meters to kilometers double distanceMiles = distanceKm * 0.621371; // Convert kilometers to miles
4. Handle User Input and Display the Result
Once we have the driving distance, it’s important to display the result in the UI for the user. When the user clicks the button, we check if both addresses have been entered and then call the GetMileage function.
Here’s the click event handler for the button:
private async void btnGetMileage_Click(object sender, EventArgs e)
{
string fromAddress = tbFrom.Text;
string toAddress = tbTo.Text;
if (string.IsNullOrEmpty(fromAddress) || string.IsNullOrEmpty(toAddress))
{
MessageBox.Show("Please enter both starting and destination addresses.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
await GetMileage(fromAddress, toAddress);
}
This code ensures that the user provides both the starting and destination addresses before performing the calculation.
Full Project on GitHub
You can download the full project from GitHub here. The repository contains the complete source code for the Mileage Calculator app, along with detailed setup instructions.
Testing and Debugging Tips
- Error Handling: Make sure to handle potential errors, such as invalid addresses, network issues, or API timeouts.
- Address Validation: Implement validation to ensure the addresses entered by the user are properly formatted.
- Edge Cases: Test cases where the addresses are close together, in different countries, or invalid.
Conclusion
In this quick guide, we’ve shown you how to build a simple Mileage Calculator app using C# and the OSRM API. This app allows you to calculate driving distances between two addresses by leveraging the power of the OSRM API, which uses OpenStreetMap data for fast and accurate routing.
If you want to build your own mileage calculator or integrate distance calculations into your project, this app provides a solid foundation. Feel free to download the complete source code from GitHub and start building today!
Subscribe for More Updates
If you found this guide helpful, don’t forget to subscribe to our newsletter for more tutorials, tips, and updates!
Sources
- OpenRouteService API Documentation
- OpenStreetMap – Official Website
- OpenStreetMap API Usage Rules
- Using Promises in JavaScript – MDN
- Asynchronous Programming in C# – Microsoft Docs
- C# Exception Handling – TutorialsPoint
- Async and Await in C# – C# Corner
- Understanding Async and Await – CodeProject
- Synchronous vs Asynchronous Calls in C# – GeeksforGeeks
- Professional ASP.NET AJAX – O’Reilly Media
- Async Programming in C# – .NET Perls
- Fetch API – MDN Web Docs
- Async and Await in JavaScript – Codingame
- Handling Exceptions in Async Methods – Telerik
Disclaimer:
The views and opinions expressed in this post are solely those of the author. The information provided is based on personal research, experience, and understanding of the subject matter at the time of writing. Readers should consult relevant experts or authorities for specific guidance related to their unique situations.
