Author: Dasan | Date: April 11, 2025
In this post, weโll cover how to use Google Maps and a suite of supporting APIs in an ASP.NET Core Web API backend. We'll include:
Make sure HttpClient is configured:
// Program.cs
builder.Services.AddHttpClient();
// GET /api/google/places?query=restaurants in Chennai
[HttpGet("places")]
public async Task<IActionResult> GetPlaces([FromQuery] string query)
{
var url = $"https://maps.googleapis.com/maps/api/place/textsearch/json?query={Uri.EscapeDataString(query)}&key={_apiKey}";
var response = await _httpClient.GetStringAsync(url);
return Content(response, "application/json");
}
Note: Transit directions are excluded.
// GET /api/google/directions?origin=Chennai&destination=Bangalore
[HttpGet("directions")]
public async Task<IActionResult> GetDirections(string origin, string destination)
{
var url = $"https://maps.googleapis.com/maps/api/directions/json?origin={origin}&destination={destination}&mode=driving&key={_apiKey}";
var response = await _httpClient.GetStringAsync(url);
return Content(response, "application/json");
}
// GET /api/google/distance?origins=Chennai&destinations=Bangalore
[HttpGet("distance")]
public async Task<IActionResult> GetDistanceMatrix(string origins, string destinations)
{
var url = $"https://maps.googleapis.com/maps/api/distancematrix/json?origins={origins}&destinations={destinations}&mode=driving&key={_apiKey}";
var response = await _httpClient.GetStringAsync(url);
return Content(response, "application/json");
}
// GET /api/google/elevation?locations=27.9881,86.9250
[HttpGet("elevation")]
public async Task<IActionResult> GetElevation(string locations)
{
var url = $"https://maps.googleapis.com/maps/api/elevation/json?locations={locations}&key={_apiKey}";
var response = await _httpClient.GetStringAsync(url);
return Content(response, "application/json");
}
// GET /api/google/geocode?address=New York
[HttpGet("geocode")]
public async Task<IActionResult> Geocode(string address)
{
var url = $"https://maps.googleapis.com/maps/api/geocode/json?address={Uri.EscapeDataString(address)}&key={_apiKey}";
var response = await _httpClient.GetStringAsync(url);
return Content(response, "application/json");
}
// GET /api/google/roads?path=60.170880,24.942795|60.170879,24.942796
[HttpGet("roads")]
public async Task<IActionResult> SnapToRoads(string path)
{
var url = $"https://roads.googleapis.com/v1/snapToRoads?path={path}&key={_apiKey}";
var response = await _httpClient.GetStringAsync(url);
return Content(response, "application/json");
}
appsettings.json or environment variables.Youโve successfully integrated a full suite of Google Maps Web APIs into your ASP.NET Core Web API. These endpoints now serve as your backend support for frontend apps using Maps, Places, Geocoding, and more.
In the next blog, weโll explore how to connect these APIs with a React Native frontend for a real-time mobile experience.