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

2015/7/31 min read
bookmark this
Responsive image
   /// <summary>
        /// google map api to get location info by zipcode
        /// {0} is the zipcode
        /// </summary>
        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";
   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<LocationRootObject>(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
            };
        }