Google Maps API for C#
Asked Answered
S

3

23

I'm really new to using APIs so after looking on Google Maps API page, I'm not sure if there are APIs designed to be used for C#. I don't need a Google map to be shown on my app; all I need to know is if I can use the Google Maps API on C#. This is the one I'd like to use.

I've looked for it on many places but all I could found was alternatives to using Gmaps but that is not what I want.

Is it possible to use it?

Storytelling answered 4/1, 2016 at 18:13 Comment(3)
Welcome to StackOverflow! We like to have some actual code in our questions and answers. This question as-is is likely to be closed. Don't let that discourage you to ask other questions in the future.Sestina
@Sestina is that a SO guideline? If yes, can you provide a link to it?Carruth
Hm, this is not a great question IMO, but given the twelve upvotes the community thinks otherwise. I'd vote to close this as too broad. (now called 'needs more focus'. "Needs more focus - This question currently includes multiple questions in one. It should focus on one problem only."Sestina
D
21

1. Create Requests to the Google Maps API by yourself

You can just send HTTP-Requests to the google maps API and then work with the results. You could use WebRequest to forge requests to the google api. You need a Maps API Key for that.


You would have to build up the GET parameters eg. origin=...&destination=...&key=YOUR_API_KEY + parse the JSON response to do something with it.

Google Maps Api Documentation (under Web Service APIs) lists the request parameters and example responses.

string url = @"https://maps.googleapis.com/maps/api/directions/json?origin=75+9th+Ave+New+York,+NY&destination=MetLife+Stadium+1+MetLife+Stadium+Dr+East+Rutherford,+NJ+07073&key=YOUR_API_KEY";

WebRequest request = WebRequest.Create(url);

WebResponse response = request.GetResponse();

Stream data = response.GetResponseStream();

StreamReader reader = new StreamReader(data);

// json-formatted string from maps api
string responseFromServer = reader.ReadToEnd();

response.Close();

A JSON response will look something like this (from Directions API )

{
   "geocoded_waypoints" : [
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJRVY_etDX3IARGYLVpoq7f68",
         "types" : [
            "bus_station",
            "transit_station",
            "point_of_interest",
            "establishment"
         ]
      },
      {
         "geocoder_status" : "OK",
         "partial_match" : true,
         "place_id" : "ChIJp2Mn4E2-woARQS2FILlxUzk",
         "types" : [ "route" ]
      }
   ],
   "routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : 34.1330949,
               "lng" : -117.9143879
            },
            "southwest" : {
               "lat" : 33.8068768,
               "lng" : -118.3527671
            }
         },
         "copyrights" : "Map data ©2016 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "35.9 mi",
                  "value" : 57824
               },
               "duration" : {
                  "text" : "51 mins",
                  "value" : 3062
               },
               "end_address" : "Universal Studios Blvd, Los Angeles, CA 90068, USA",
               "end_location" : {
                  "lat" : 34.1330949,
                  "lng" : -118.3524442
               },
               "start_address" : "Disneyland (Harbor Blvd.), S Harbor Blvd, Anaheim, CA 92802, USA",
               "start_location" : {
                  "lat" : 33.8098177,
                  "lng" : -117.9154353
               },

  ... Additional results truncated in this example[] ...


         "overview_polyline" : {
            "points" : "knjmEnjunUbKCfEA?_@]@kMBeE@qIIoF@wH@eFFk@WOUI_@?u@j@k@`@EXLTZHh@Y`AgApAaCrCUd@cDpDuAtAoApA{YlZiBdBaIhGkFrDeCtBuFxFmIdJmOjPaChDeBlDiAdD}ApGcDxU}@hEmAxD}[tt@yNb\\yBdEqFnJqB~DeFxMgK~VsMr[uKzVoCxEsEtG}BzCkHhKWh@]t@{AxEcClLkCjLi@`CwBfHaEzJuBdEyEhIaBnCiF|K_Oz\\
            {MdZwAbDaKbUiB|CgCnDkDbEiE|FqBlDsLdXqQra@kX|m@aF|KcHtLm@pAaE~JcTxh@w\\`v@gQv`@}F`MqK`PeGzIyGfJiG~GeLhLgIpIcE~FsDrHcFfLqDzH{CxEwAbBgC|B}F|DiQzKsbBdeA{k@~\\oc@bWoKjGaEzCoEzEwDxFsUh^wJfOySx[uBnCgCbCoFlDmDvAiCr@eRzDuNxC_EvAiFpCaC|AqGpEwHzFoQnQoTrTqBlCyDnGmCfEmDpDyGzGsIzHuZzYwBpBsC`CqBlAsBbAqCxAoBrAqDdDcNfMgHbHiPtReBtCkD|GqAhBwBzBsG~FoAhAaCbDeBvD_BlEyM``@uBvKiA~DmAlCkA|B}@lBcChHoJnXcB`GoAnIS~CIjFDd]A|QMlD{@jH[vAk@`CoGxRgPzf@aBbHoB~HeMx^eDtJ}BnG{DhJU`@mBzCoCjDaAx@mAnAgCnBmAp@uAj@{Cr@wBPkB@kBSsEW{GV}BEeCWyAWwHs@qH?
            cIHkDXuDn@mCt@mE`BsH|CyAp@}AdAaAtAy@lBg@pCa@jE]fEcBhRq@pJKlCk@hLFrB@lD_@xCeA`DoBxDaHvM_FzImDzFeCpDeC|CkExDiJrHcBtAkDpDwObVuCpFeCdHoIl\\uBjIuClJsEvMyDbMqAhEoDlJ{C|J}FlZuBfLyDlXwB~QkArG_AnDiAxC{G|OgEdLaE`LkBbEwG~KgHnLoEjGgDxCaC`BuJdFkFtCgCnBuClD_HdMqEzHcBpB_C|BuEzCmPlIuE|B_EtDeBhCgAdCw@rCi@|DSfECrCAdCS~Di@jDYhA_AlC{AxCcL`U{GvM_DjFkBzBsB`BqDhBaEfAsTvEmEr@iCr@qDrAiFnCcEzCaE~D_@JmFdGQDwBvCeErEoD|BcFjC}DbEuD~D`@Zr@h@?d@Wr@}@vAgCbEaHfMqA`Cy@dAg@bAO`@gCi@w@W"
         },
         "summary" : "I-5 N and US-101 N",
         "warnings" : [],
         "waypoint_order" : []
      }
   ],
   "status" : "OK"
}

2. ... or use a dedicated library

  • gmaps-api-net (github) offers an api interface for Google Maps. You can get it via nuget. I haven't testet it, but it looks very easy to use.

This library is outdated, see https://mcmap.net/q/563571/-google-maps-api-for-c

Divan answered 4/1, 2016 at 18:23 Comment(5)
msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx for English WebRequest page.Lifeboat
why "YOUR_API_KEY". Is it no more free available.Marin
@Marin It's free up to a certain number of requests. You're free to look at Google's own documentation about thisTernopol
There's also this library that is very simple and easy to use and has the most popular features. github.com/guimsilva/GuigleCore You can install it with the nuget command Install-Package GuigleCoreErnieernst
What if there are waypoints in url. Would it include that information?Vallecula
C
8

As mentioned in the other respose(s), you can make HTTP requests and use the JSON response.

If you want a .NET library that makes your life easier by abstracting the query/response you can use one of these .NET wrapper libraries for the Google Maps API :

  1. GoogleApi
  2. google-maps

gmaps-api-net is outdated (at this time of answering) - the last update for the Directions API was made in 2016.

Usage example for GoogleApi:

using GoogleApi.Entities.Common;
using GoogleApi.Entities.Maps.Directions.Request;
using GoogleApi.Entities.Maps.Directions.Response;

public void GetRoute()
{
    DirectionsRequest request = new DirectionsRequest();    

    request.Key = "AIzaSyAJgBs8LYok3rt15rZUg4aUxYIAYyFzNcw";

    request.Origin = new Location("Brasov");
    request.Destination = new Location("Merghindeal");

    var response = GoogleApi.GoogleMaps.Directions.Query(request);

    Console.WriteLine(response.Routes.First().Legs.First().DurationInTraffic);
    Console.WriteLine(response.Routes.First().Legs.First().Distance);
    Console.WriteLine(response.Routes.First().Legs.First().Steps);
}
Carruth answered 30/4, 2020 at 20:2 Comment(1)
This is a very informative answer. Do we have a link that can explain to me the various tasks that can be carried out by GoogleApi and how they can be carried out? You see, the Readme is really not very informative and this surely will fix my issueStedman
A
1

Adding to Alex's answer above.

In their example they first try to write DurationInTraffic, which only works if you supply a departureTime. Also, you want the value not the object to display the seconds or the text. You could just use duration without the traffic option too.

If you do want to set departure time, this project will set to epoc/Linux/seconds since 1970 for you automatically. However, I don't see a "now" option like in Google, so be sure to set it to UTC first.

If you don't supply a departureTime, DurationInTraffic will be null so this would error.

request.DepartureTime = DateTime.Now.ToUniversalTime();

...

var x = response.Routes.First().Legs.First();
                Console.WriteLine("Duration w/ traffic: " + x.DurationInTraffic.Value + " vs w/o " + x.Duration.Value);
                Console.ReadLine();
Ancestor answered 13/7, 2020 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.