Sample Code - Google Map API - Get Location Info by Zipcode

2015/07/032 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. API Constants
  3. Get Location Method
  4. Conclusion

Introduction

This post provides a C# code snippet to get location information (state and county) by zipcode from the Google Map API.

API Constants

///
        /// google map api to get location info by zipcode
        /// {0} is the zipcode
        ///
        private const string GOOGLEMAP_API_FORMAT = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true";
        private const string GOOGLEMAP_API_RESULT_FAILED = "ZERO_RESULTS";
        private const string GOOGLEMAP_API_FILTER_TYPE_STATE = "administrative_area_level_1";
        private const string GOOGLEMAP_API_FILTER_TYPE_COUNTY = "administrative_area_level_2";

Get Location Method

public LocationEntity GetLocation(string zipCode)
        {
            if (string.IsNullOrWhiteSpace(zipCode))
            {
                return null;
            }

            LocationRootObject googleMapObj = BaseGetLocation(zipCode);
            if (googleMapObj == null)
            {
                return null;
            }

            return FindLocation(googleMapObj);
        }

        private LocationRootObject BaseGetLocation(string zipCode)
        {
            using (HttpClient client = new HttpClient())
            {
                var response = client.GetAsync(string.Format(GOOGLEMAP_API_FORMAT, zipCode));
                var localObj = JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result);
                if (localObj.status.Equals(GOOGLEMAP_API_RESULT_FAILED, StringComparison.CurrentCultureIgnoreCase))
                {
                    return null;
                }

                return localObj;
            }
        }

        private LocationEntity FindLocation(LocationRootObject localObj)
        {
            var state = localObj.results.FirstOrDefault().address_components
                .FirstOrDefault(_ => _.types.Contains(GOOGLEMAP_API_FILTER_TYPE_STATE));
            var county = localObj.results.FirstOrDefault().address_components
                .FirstOrDefault(_ => _.types.Contains(GOOGLEMAP_API_FILTER_TYPE_COUNTY));
            return new LocationEntity
            {
                County = county.short_name,
                State = state.short_name
            };
        }

Conclusion

This code demonstrates how to use the Google Map API to retrieve location information by zipcode in C#. It sends a geocode request, parses the JSON response, and extracts the state and county from the address components.