Write a service in asp.net core MVC .net 8 that uses Google maps nearby search api and…
- User
Write a service in asp.net core MVC .net 8 that uses Google maps nearby search api and make it available as a service
- Assistant
Write a service in asp.net core MVC .net 8 that uses Google maps nearby search api and make it available as a service
Sure! I'll guide you through creating an ASP.NET Core MVC service in .NET 8 that utilizes the Google Maps Places API for Nearby Search. This service will expose endpoints that clients can use to search for places near a specific location.
Prerequisites:
Open your terminal or command prompt, navigate to the directory where you want to create the project, and run:
dotnet new mvc -n GoogleMapsNearbySearchService
cd GoogleMapsNearbySearchService
This command creates a new ASP.NET Core MVC project named GoogleMapsNearbySearchService.
We'll need:
Microsoft.Extensions.Http: For making HTTP requests.Newtonsoft.Json: For JSON serialization/deserialization (the default System.Text.Json can also be used).Run the following commands:
dotnet add package Microsoft.Extensions.Http
dotnet add package Newtonsoft.Json
We'll store the API key in the appsettings.json file for configuration.
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"GoogleMapsSettings": {
"ApiKey": "YOUR_GOOGLE_MAPS_API_KEY"
}
}
Important: Replace YOUR_GOOGLE_MAPS_API_KEY with your actual API key.
Define models that represent the data returned by the Google Maps Nearby Search API.
Models/Place.cs
using Newtonsoft.Json;
namespace GoogleMapsNearbySearchService.Models
{
public class Place
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("geometry")]
public Geometry Geometry { get; set; }
// Add other properties as needed
}
public class Geometry
{
[JsonProperty("location")]
public Location Location { get; set; }
}
public class Location
{
[JsonProperty("lat")]
public double Latitude { get; set; }
[JsonProperty("lng")]
public double Longitude { get; set; }
}
// Root object for deserialization
public class PlacesApiResponse
{
[JsonProperty("results")]
public List<Place> Results { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
}
}
Services/GoogleMapsService.cs
using GoogleMapsNearbySearchService.Models;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace GoogleMapsNearbySearchService.Services
{
public class GoogleMapsService
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
public GoogleMapsService(HttpClient httpClient, IOptions<GoogleMapsSettings> settings)
{
_httpClient = httpClient;
_apiKey = settings.Value.ApiKey;
}
public async Task<PlacesApiResponse> GetNearbyPlacesAsync(double latitude, double longitude, int radius, string keyword)
{
var url = $"https://maps.googleapis.com/maps/api/place/nearbysearch/json" +
$"?location={latitude},{longitude}" +
$"&radius={radius}" +
$"&keyword={Uri.EscapeDataString(keyword)}" +
$"&key={_apiKey}";
var response = await _httpClient.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
// Handle errors (e.g., log them)
return null;
}
var json = await response.Content.ReadAsStringAsync();
var placesResponse = JsonConvert.DeserializeObject<PlacesApiResponse>(json);
return placesResponse;
}
}
}
Models/GoogleMapsSettings.cs
namespace GoogleMapsNearbySearchService.Models
{
public class GoogleMapsSettings
{
public string ApiKey { get; set; }
}
}
Program.cs
using GoogleMapsNearbySearchService.Models;
using GoogleMapsNearbySearchService.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Configure Google Maps settings
builder.Services.Configure<GoogleMapsSettings>(
builder.Configuration.GetSection("GoogleMapsSettings"));
// Register GoogleMapsService with the HTTP client
builder.Services.AddHttpClient<GoogleMapsService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// Authorization is optional here
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Controllers/PlacesController.cs
using GoogleMapsNearbySearchService.Models;
using GoogleMapsNearbySearchService.Services;
using Microsoft.AspNetCore.Mvc;
namespace GoogleMapsNearbySearchService.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PlacesController : ControllerBase
{
private readonly GoogleMapsService _googleMapsService;
public PlacesController(GoogleMapsService googleMapsService)
{
_googleMapsService = googleMapsService;
}
[HttpGet("nearby")]
public async Task<IActionResult> GetNearbyPlaces(
[FromQuery] double latitude,
[FromQuery] double longitude,
[FromQuery] int radius = 500, // in meters
[FromQuery] string keyword = "")
{
var result = await _googleMapsService.GetNearbyPlacesAsync(latitude, longitude, radius, keyword);
if (result == null || result.Status != "OK")
{
return StatusCode(500, "Error retrieving data from Google Maps API.");
}
return Ok(result.Results);
}
}
}
Run the application:
dotnet run
Access the API endpoint using a web browser or a tool like Postman:
https://localhost:5001/api/places/nearby?latitude=37.7749&longitude=-122.4194&radius=1000&keyword=coffee
This should return a JSON response with places near the specified location matching the keyword "coffee".
CORS: If you plan to call this API from a web application hosted on a different domain, you might need to enable Cross-Origin Resource Sharing (CORS).
Program.cs
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
// ...
app.UseCors("AllowAll");
Error Handling: Enhance error handling by checking for different statuses returned by the Google Maps API (e.g., ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED).
Logging: Implement logging to keep track of API calls and errors.
Rate Limiting: Be mindful of the Google Maps API usage limits and consider implementing rate limiting on your service if necessary.
Security: Do not expose your API key in client-side code or public repositories. Consider moving sensitive configurations to secure storage or environment variables.
You've now created a simple ASP.NET Core MVC service that interacts with the Google Maps Places API to perform nearby searches. This service can be extended with additional features such as more detailed place information, filtering options, and support for more query parameters.
Let me know if you need further assistance or have questions about extending this service!
Not yet included in a published release.