Skip to content

Instantly share code, notes, and snippets.

@JuanuMusic
Created June 2, 2018 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JuanuMusic/75c18a55af8ecfa9c6bcfb11810846e5 to your computer and use it in GitHub Desktop.
Save JuanuMusic/75c18a55af8ecfa9c6bcfb11810846e5 to your computer and use it in GitHub Desktop.
Calling Snap to Roads Google API from C#. This code has mainly been created using Xamarin Libraries, so It might not work on other platforms.
using Xamarin.Forms.Maps;
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.Threading.Tasks;
public static class GoogleRoads
{
/// <summary>
/// Using Google API, snaps a list of given points to a list of points snapped to the roads.
/// </summary>
/// <param name="pPoints"></param>
/// <param name="pGoogleApiKey"></param>
/// <returns></returns>
public static async Task<IEnumerable<Position>> SnapToRoads(IEnumerable<Position> pPoints, string pGoogleApiKey, bool pInterpolate)
{
string points = String.Empty;
try
{
// Generate an array of strings with latitude and longituded, separeted by comma
string[] strPoints = pPoints.Select(pnts => $"{pnts.Latitude},{pnts.Longitude}").ToArray();
// Join the strings together using a pipe character.
string parameter = $"path={string.Join("|", strPoints)}";
// Generate the URL
Uri url = new Uri($"https://roads.googleapis.com/v1/snapToRoads?{parameter}&key={pGoogleApiKey}&interpolate={pInterpolate}");
// Make the request and get the json String.
points = await ServiceManager.GetStringAsync(url);
// Get the response
SnappedPointsRoot pointsResponse = JsonConvert.DeserializeObject<SnappedPointsRoot>(points);
// Convert the points to a list of position.
IEnumerable<Position> retVal = pointsResponse.SnappedPoints.Select(sp => new Position(sp.Location.Latitude, sp.Location.Longitude));
// Return the values.
return retVal;
}
catch (Exception ex)
{
throw new Exception("An unhandled exception occurred while snapping points to roads using Google API.", ex);
}
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
public static class ServiceManager
{
/// <summary>
/// Returns a string using the GET verb.
/// </summary>
/// <param name="url">The URL to make the request from.</param>
/// <returns></returns>
public static async Task<string> GetStringAsync(Uri url)
{
try
{
// Instantiate the HttpClient
HttpClient client = new HttpClient();
// Make the GET request.
HttpResponseMessage response = await client.GetAsync(url);
try
{
// Make sure the status code is Success
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex)
{
// Get the error string
string error = await response.Content.ReadAsStringAsync();
return error;
}
// Get the string response.
string retVal = await response.Content.ReadAsStringAsync();
// Return the response string.
return retVal;
}
catch (Exception ex)
{
throw ex;
}
}
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
public class SnappedPoint
{
/// <summary>
/// The location of the snapped point.
/// </summary>
[JsonProperty("location")]
public Location Location { get; set; }
/// <summary>
/// An integer value indicating the corresponding value on the original request. Each value on the request must lead to a value adjusted to the response.
/// </summary>
[JsonProperty("originalIndex")]
public int OriginalIndex { get; set; }
/// <summary>
/// A unique identifier for a site.
/// </summary>
[JsonProperty("placeId")]
public string PlaceId { get; set; }
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
public class SnappedPointsRoot
{
/// <summary>
/// A list of snapped points.
/// </summary>
[JsonProperty("snappedPoints")]
public SnappedPoint[] SnappedPoints { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment