Working with the Google Location API

前端 未结 6 2102
别跟我提以往
别跟我提以往 2021-02-06 05:50

Forgive me for my ignorance, but after several hours of searching, I\'m having little luck.

Anyway, I am attempting to write a small desktop application that will allow

6条回答
  •  难免孤独
    2021-02-06 06:25

    Here is a sample code to get what you want

    using System;
    using System.Web;
    using System.Net;
    using System.Runtime.Serialization.Json;
    
    namespace GoogleMapsSample
    {
        public class GoogleMaps
        {
    
            /// 
            /// 
            /// 
            /// 
            /// 
            public static GeoResponse GetGeoCodedResults(string address)
            {
                string url = string.Format(
                        "http://maps.google.com/maps/api/geocode/json?address={0}®ion=dk&sensor=false",
                        HttpUtility.UrlEncode(address)
                        );
                var request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeoResponse));
                var res = (GeoResponse)serializer.ReadObject(request.GetResponse().GetResponseStream());
                return res;
            }
    
    
        }
    

    and you helper class would be

     namespace GoogleMapsSample
    {
        [DataContract]
        public class GeoResponse
        {
            [DataMember(Name = "status")]
            public string Status { get; set; }
            [DataMember(Name = "results")]
            public CResult[] Results { get; set; }
    
            [DataContract]
            public class CResult
            {
                [DataMember(Name = "geometry")]
                public CGeometry Geometry { get; set; }
    
                [DataContract]
                public class CGeometry
                {
                    [DataMember(Name = "location")]
                    public CLocation Location { get; set; }
    
                    [DataContract]
                    public class CLocation
                    {
                        [DataMember(Name = "lat")]
                        public double Lat { get; set; }
                        [DataMember(Name = "lng")]
                        public double Lng { get; set; }
                    }
                }
            }
    
            public GeoResponse()
            { }
        }
    
    
    }
    

    Then you can use this code in your control/winforms like this

                GeoResponse response = new GeoResponse();
                response = GoogleMaps.GetGeoCodedResults(TextBoxPostcode.Text);
    

    and build the JS on the code behind using StringBuilder or anyting else

提交回复
热议问题