📍 GeocodingService.cs Documentation

Welcome to the detailed documentation for IrbyImaging/Services/GeocodingService.cs. This service wraps the Bing Maps REST API to convert a postal address into geographic coordinates (latitude & longitude).


📑 Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Class Diagram (UML)
  4. Key Functional Areas
  5. Public API
  6. Detailed Method Breakdown
  7. Error Handling & Return Types
  8. Third‑party Integrations & Security
  9. Usage Examples
  10. Conclusion & Best Practices

1. Overview & Purpose

GeocodingService is a simple, reusable .NET service that:

  • 🌐 Queries the Bing Maps REST API
  • 🎯 Parses the JSON response
  • 🔍 Extracts the first matching coordinate pair (latitude & longitude)
  • 🔄 Returns a nullable tuple for fail‑safe operation

This is intended for any UI or backend component that needs to convert human‑readable addresses into map coordinates.


2. Dependencies & Technologies

Dependency Purpose
System.Net.Http Perform HTTP GET requests
Newtonsoft.Json Parse and navigate the JSON response object
.NET Standard Cross‑platform library compatibility

Key points:

  • Uses HttpClient via Dependency Injection for testability and reusability.
  • Leverages Newtonsoft.Json.Linq (JObject) for dynamic JSON traversal.

3. Class Diagram (UML)

classDiagram
    class GeocodingService {
        - const string BingMapsKey
        - HttpClient _httpClient
        + GeocodingService(HttpClient httpClient)
        + Task<(double Latitude, double Longitude)?> GetCoordinates(string address)
    }
    GeocodingService --> HttpClient

4. Key Functional Areas

  1. API Key Management
    • 🔑 BingMapsKey constant (should be moved to secure config!)
  2. HTTP Communication
    • _httpClient.GetAsync(url)
  3. JSON Parsing & Validation
    • JObject.Parse(...)
    • Null‑checks before extracting coordinates
  4. Result Wrapping
    • Returns (double Latitude, double Longitude)?

5. Public API

5.1 Constructor

public GeocodingService(HttpClient httpClient)
  • Purpose: Injects an HttpClient instance to perform outbound HTTP calls.
  • Parameter:
    • httpClient: Configured HttpClient (preferably named/client-specific with base address).

5.2 GetCoordinates Method

public async Task<(double Latitude, double Longitude)?> GetCoordinates(string address)
  • Purpose:
    • Send a geocoding request with the given address.
    • Parse the response and return the first set of coordinates.
  • Parameter:
    • address (string): The address to geocode.
  • Return Type:
    • Task<(double Latitude, double Longitude)?>
      • A nullable tuple containing latitude & longitude, or null if not found.

6. Detailed Method Breakdown

public async Task<(double Latitude, double Longitude)?> GetCoordinates(string address)
{
    // 1️⃣ Build URL
    var url = $"http://dev.virtualearth.net/REST/v1/Locations?q={Uri.EscapeDataString(address)}&key={BingMapsKey}";

    // 2️⃣ Execute HTTP GET
    var response = await _httpClient.GetAsync(url);

    if (response.IsSuccessStatusCode)
    {
        // 3️⃣ Read content & parse JSON
        var data = await response.Content.ReadAsStringAsync();
        var json = JObject.Parse(data);

        // 4️⃣ Navigate JSON to first result
        var topResult = json["resourceSets"]?[0]?["resources"]?[0];
        if (topResult != null)
        {
            var coords = topResult["point"]["coordinates"];
            // 5️⃣ Extract and return latitude & longitude
            return (coords[0].Value<double>(), coords[1].Value<double>());
        }
    }

    // 6️⃣ Fallback if request fails or no result
    return null;
}

Steps at a glance:

  1. URL Construction ✔️
  2. HTTP Request ✔️
  3. Response → String
  4. JSON Parse
  5. Coordinate Extraction
  6. Return Nullable Tuple

7. Error Handling & Return Types

  • HTTP Errors
    • If IsSuccessStatusCode is false, the method returns null.
  • Missing JSON Nodes
    • Uses safe navigation (?) to avoid exceptions.
    • Returns null on missing resources.
  • Exception Handling
    • Currently, unhandled exceptions (e.g., network failures) bubble up to the caller.
    • Recommendation: Wrap calls in try/catch and log meaningful errors.

8. Third‑party Integrations & Security

🔗 Bing Maps REST API

  • Endpoint: http://dev.virtualearth.net/REST/v1/Locations
  • API Key: Hard‑coded constant
    • ⚠️ Security Risk: Move to secure storage (e.g., Azure Key Vault, IConfiguration).
    • Example:
      // appsettings.json
      "BingMaps": {
        "Key": "YOUR_SECURE_KEY_HERE"
      }
      
      services.AddHttpClient<GeocodingService>()
              .ConfigureHttpClient((sp, client) =>
              {
                  var cfg = sp.GetRequiredService<IConfiguration>();
                  var key = cfg["BingMaps:Key"];
                  client.BaseAddress = new Uri("https://dev.virtualearth.net/REST/v1/");
                  // store key somewhere in the service rather than hardcoding
              });
      

9. Usage Examples

9.1 Registering in ASP.NET Core

// Startup.cs or Program.cs
services.AddHttpClient<GeocodingService>(client =>
{
    // Optional: set base address/proxies
}).SetHandlerLifetime(TimeSpan.FromMinutes(5));

9.2 Injecting & Calling

public class AddressController : Controller
{
    private readonly GeocodingService _geoService;
    public AddressController(GeocodingService geoService)
    {
        _geoService = geoService;
    }

    public async Task<IActionResult> GetLatLong(string address)
    {
        var coords = await _geoService.GetCoordinates(address);
        if (coords.HasValue)
        {
            return Ok(new { Latitude = coords.Value.Latitude, Longitude = coords.Value.Longitude });
        }
        return NotFound("Address could not be geocoded.");
    }
}

9.3 Console App Example

static async Task Main(string[] args)
{
    var services = new ServiceCollection()
        .AddHttpClient<GeocodingService>()
        .BuildServiceProvider();

    var geo = services.GetRequiredService<GeocodingService>();
    var result = await geo.GetCoordinates("1600 Amphitheatre Parkway, Mountain View, CA");
    if (result.HasValue)
        Console.WriteLine($"Lat: {result.Value.Latitude}, Lon: {result.Value.Longitude}");
    else
        Console.WriteLine("Location not found.");
}

10. Conclusion & Best Practices

  • ✅ Keep Logic Simple: Single‑responsibility geocoding wrapper.
  • 🔒 Secure Your Key: Avoid hard‑coding secrets in source code.
  • ⚡ Improve Resilience:
    • Add retries (e.g., Polly)
    • More granular logging & metrics
  • 📈 Extendibility:
    • Support multiple geocoding providers
    • Expose asynchronous cancellation (CancellationToken)
  • 📝 Documentation: As shown, comprehensive docs foster maintainability.

Happy coding! 🛠️🌍