Search code examples
c#apimodel-view-controllergoogle-geocoding-apigoogle-geolocation

Get latitude and Longitude from Google Geo Code JSON in MVC(C#)


I am having trouble to retrieve values from JSON results received from google geo code API

Function

 public static async Task GetLatLogFromAddress()
        {     
            using (var client = new HttpClient())
            {
                Uri Inputuri = new Uri("https://maps.googleapis.com/maps/api/geocode/json?address=123+N+TRY+Street+Paul,+MN&key=APIKey");
                client.BaseAddress = Inputuri;

                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // List data response.
                HttpResponseMessage response = await client.GetAsync(client.BaseAddress); ;  // Blocking call! Program will wait here until a response is received or a timeout occurs.
                if (response.IsSuccessStatusCode)
                {
                    // Parse the response body

                    string result = await response.Content.ReadAsStringAsync();
                    dynamic jsonData = JsonConvert.DeserializeObject<dynamic>(result);
                    foreach(var geo in jsonData)
                    {
                        var lat = (decimal)geo[0].geometry.location.lat;
                        var longi = (decimal)geo[0].geometry.location.lng;
                    }

                }
                else
                {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

                } 
                client.Dispose();
            }
        }

Results in JSON are

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Winnetka",
               "short_name" : "Winnetka",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Los Angeles",
               "short_name" : "LA",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Los Angeles County",
               "short_name" : "Los Angeles County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Winnetka, Los Angeles, CA, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 34.2355209,
                  "lng" : -118.5534191
               },
               "southwest" : {
                  "lat" : 34.1854649,
                  "lng" : -118.588536
               }
            },
            "location" : {
               "lat" : 34.2048586,
               "lng" : -118.5739621
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 34.2355209,
                  "lng" : -118.5534191
               },
               "southwest" : {
                  "lat" : 34.1854649,
                  "lng" : -118.588536
               }
            }
         },
         "place_id" : "ChIJ0fd4S_KbwoAR2hRDrsr3HmQ",
         "types" : [ "neighborhood", "political" ]
      }
   ],
   "status" : "OK"
}

These are the results we get from Google GeoCode API

I am trying to get Latitude and Longitude but I get an error that Geo does not contain any definition of geometry. How can I access JSON results received from google geo code API?


Solution

  • var data = JsonConvert.DeserializeObject<dynamic>(result);
    foreach(var item in data.results)
    {
        var lat = (decimal)(item.geometry.location.lat);
        var longi = (decimal)(item.geometry.location.lng);
    }
    

    The problem was that you believed jsonData represented results when in fact, it was an object which contained the results array.