Google Geolocation API - Use longitude and latitude to get address in textbox?

后端 未结 8 614
有刺的猬
有刺的猬 2021-01-31 05:25

I have noticed a lot of information about how to get your location using Google geolocation looks, based on IP address. But I am wondering if and how I could use this service t

8条回答
  •  野的像风
    2021-01-31 05:55

    private string getLocationByGeoLocation(string longitude, string latitude)
        {
            string locationName = string.Empty;
    
            try
            {
                if (string.IsNullOrEmpty(longitude) || string.IsNullOrEmpty(latitude))
                    return "";
    
                string url = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false", latitude, longitude);
    
    
                WebRequest request = WebRequest.Create(url);
    
                using (WebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        DataSet dsResult = new DataSet();
                        dsResult.ReadXml(reader);
                        try
                        {
                            foreach (DataRow row in dsResult.Tables["result"].Rows)
                            {
                                string fullAddress = row["formatted_address"].ToString();
                            }
                        }
                        catch (Exception)
                        {
    
                        }
    
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
    
    
            return locationName;
        }
    

提交回复
热议问题