Skip to content

Commit

Permalink
Merge pull request #40 from Purdue-ACM-SIGAPP/30-implement-distance-b…
Browse files Browse the repository at this point in the history
…etween-locations-endpoint-integrate-with-google-maps-api

Fix Middleware
  • Loading branch information
SashimiDaBest authored Nov 6, 2024
2 parents fe00d4f + 8eacd70 commit fbe93ad
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 0 deletions.
9 changes: 9 additions & 0 deletions Controllers/BuildingController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,17 @@
using MongoDB.Driver;
using SimpleWebAppReact.Services;









namespace SimpleWebAppReact.Controllers
{

/// <summary>
/// Defines endpoints for operations relating the Building table
/// </summary>
Expand Down
89 changes: 89 additions & 0 deletions Controllers/MapsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
namespace SimpleWebAppReact.Controllers;
using Microsoft.AspNetCore.Mvc;
using SimpleWebAppReact.Services;
using SimpleWebAppReact.Entities;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

[ApiController]
[Route("api/maps")]
public class MapsController : ControllerBase
{
private readonly ILogger<MapsController> _logger;
private readonly IMongoCollection<Building>? _buildings;
private readonly HttpClient _httpClient;
private readonly string _googleApiKey = "AIzaSyCzKs4kUhXuPhBxYB2BU0ODXXIUBJnenhA";

public MapsController(ILogger<MapsController> logger, MongoDbService mongoDbService, HttpClient httpClient)
{
_logger = logger;
_buildings = mongoDbService.Database?.GetCollection<Building>("building");
_httpClient = httpClient;
}

[HttpGet("distance")]
public async Task<IActionResult> GetDistance(string buildingId1, string buildingId2)
{
if (_buildings == null)
{
return StatusCode(500, new { message = "Building collection not initialized." });
}

// Fetch the two buildings from the database using their IDs
var building1 = await _buildings.Find(b => b.Id == buildingId1).FirstOrDefaultAsync();
var building2 = await _buildings.Find(b => b.Id == buildingId2).FirstOrDefaultAsync();

if (building1 == null || building2 == null)
{
return NotFound(new { message = "One or both buildings not found." });
}

// Extract addresses
string address1 = building1.Address ?? string.Empty;
string address2 = building2.Address ?? string.Empty;

if (string.IsNullOrEmpty(address1) || string.IsNullOrEmpty(address2))
{
return BadRequest(new { message = "Addresses are missing for one or both buildings." });
}

// Prepare the Distance Matrix API request
string url = $"https://maps.googleapis.com/maps/api/distancematrix/json?origins={address1}&destinations={address2}&units=imperial&key={_googleApiKey}";

try
{
// Send the request to Google Maps API
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
var jsonData = JObject.Parse(jsonResponse);

// Parse distance and duration from the response
var distance = jsonData["rows"]?[0]?["elements"]?[0]?["distance"]?["text"]?.ToString();
var duration = jsonData["rows"]?[0]?["elements"]?[0]?["duration"]?["text"]?.ToString();

if (distance == null || duration == null)
{
return BadRequest(new { message = "Could not calculate distance or duration." });
}

// Return the distance and duration as the response
return Ok(new
{
building1 = building1.Name,
building2 = building2.Name,
distance,
duration
});
}
catch (HttpRequestException e)
{
_logger.LogError(e, "Error while calling Google Maps API");
return StatusCode(500, new { message = "Error while calling Google Maps API." });
}
}
}

11 changes: 11 additions & 0 deletions Entities/Building.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,15 @@ public class Building

[BsonElement("address"), BsonRepresentation(BsonType.String)]
public string? Address { get; set; }

// <field>: { type: <GeoJSON type> , coordinates: <coordinates> }



// location: {
// type: "Point",
// coordinates: [-73.856077, 40.848447]
// }
// <field>: [<longitude>, <latitude> ]

}
1 change: 1 addition & 0 deletions SimpleWebAppReact.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.33" />
<PackageReference Include="MongoDB.Driver" Version="2.28.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="xunit" Version="2.9.0" />
</ItemGroup>
Expand Down
1 change: 1 addition & 0 deletions Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public Startup(IConfiguration configuration)
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddHttpClient();

// Configure CORS to allow requests from React Native frontend
services.AddCors(options =>
Expand Down

0 comments on commit fbe93ad

Please sign in to comment.