如何使用C#查找纬度和经度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14354867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:34:43  来源:igfitidea点击:

How to find latitude and longitude using C#

c#restgoogle-mapslatitude-longitude

提问by MaxRecursion

I have a WCFservice in C#.

WCF在 C# 中有一项服务。

In the Service call client sends a city name. I want to convert the city name to latitudes and longitudes and store in Database under demographics.

在服务调用客户端发送一个城市名称。我想将城市名称转换为纬度和经度并存储在人口统计下的数据库中。

I am planning to use Google API to implement above functionality.

我打算使用 Google API 来实现上述功能。

I have obtained an API key from Google and its of type 'Service account'.

我已从 Google 及其“服务帐户”类型获得了一个 API 密钥。

How can I obtain the latitude and longitude using which APIs?

如何使用哪些 API 获取纬度和经度?

Do I need to install some SDKor any RESTService will do?

我需要安装一些SDK或任何REST服务都可以吗?

采纳答案by MaxRecursion

If you want to use the Google Maps API have a look at their REST API, you don't need to install a Google Maps API just send a Request like

如果你想使用谷歌地图 API 看看他们的 REST API,你不需要安装谷歌地图 API 只需发送一个请求

http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false

and you will get a response XML.

你会得到一个响应 XML。

For response JSON:

对于响应 JSON:

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Estancia+Sergipe,&key=**YOUR_API_KEY**

For more Information have a look at

有关更多信息,请查看

https://developers.google.com/maps/documentation/geocoding/index#GeocodingRequests

https://developers.google.com/maps/documentation/geocoding/index#GeocodingRequests

回答by khellang

You could try the NuGet package GoogleMaps.LocationServices, or just spin of its source code. It uses Google's REST API to get lat/long for a given address and vice versa, without the need for an API key.

您可以尝试 NuGet 包GoogleMaps.LocationServices,或者只是对其源代码进行旋转。它使用 Google 的 REST API 获取给定地址的经纬度,反之亦然,无需 API 密钥。

You use it like this:

你像这样使用它:

public static void Main()
{
    var address = "Stavanger, Norway";

    var locationService = new GoogleLocationService();
    var point = locationService.GetLatLongFromAddress(address);

    var latitude = point.Latitude;
    var longitude = point.Longitude;

    // Save lat/long values to DB...
}

回答by Manish sharma

You can pass address in particular url.. and you get latitude and longitude in return value dt(datatable)

您可以在特定的 url 中传递地址 .. 并在返回值 dt(datatable) 中获得纬度和经度

string url = "http://maps.google.com/maps/api/geocode/xml?address=" + address+ "&sensor=false";
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);
        DataTable dtCoordinates = new DataTable();
        dtCoordinates.Columns.AddRange(new DataColumn[4] { new DataColumn("Id", typeof(int)),
                    new DataColumn("Address", typeof(string)),
                    new DataColumn("Latitude",typeof(string)),
                    new DataColumn("Longitude",typeof(string)) });
        foreach (DataRow row in dsResult.Tables["result"].Rows)
        {
            string geometry_id = dsResult.Tables["geometry"].Select("result_id = " + row["result_id"].ToString())[0]["geometry_id"].ToString();
            DataRow location = dsResult.Tables["location"].Select("geometry_id = " + geometry_id)[0];
            dtCoordinates.Rows.Add(row["result_id"], row["formatted_address"], location["lat"], location["lng"]);
        }
    }
    return dtCoordinates;
}

回答by Saurin Vala

     /*Ready to use code :  simple copy paste GetLatLong*/
    public class AddressComponent
    {
        public string long_name { get; set; }
        public string short_name { get; set; }
        public List<string> types { get; set; }
    }

    public class Northeast
    {
        public double lat { get; set; }
        public double lng { get; set; }
    }

    public class Southwest
    {
        public double lat { get; set; }
        public double lng { get; set; }
    }

    public class Bounds
    {
        public Northeast northeast { get; set; }
        public Southwest southwest { get; set; }
    }

    public class Location
    {
        public double lat { get; set; }
        public double lng { get; set; }
    }

    public class Northeast2
    {
        public double lat { get; set; }
        public double lng { get; set; }
    }

    public class Southwest2
    {
        public double lat { get; set; }
        public double lng { get; set; }
    }

    public class Viewport
    {
        public Northeast2 northeast { get; set; }
        public Southwest2 southwest { get; set; }
    }

    public class Geometry
    {
        public Bounds bounds { get; set; }
        public Location location { get; set; }
        public string location_type { get; set; }
        public Viewport viewport { get; set; }
    }

    public class Result
    {
        public List<AddressComponent> address_components { get; set; }
        public string formatted_address { get; set; }
        public Geometry geometry { get; set; }
        public string place_id { get; set; }
        public List<string> types { get; set; }
    }

    public class RootObject
    {
        public List<Result> results { get; set; }
        public string status { get; set; }
    }


    public static RootObject GetLatLongByAddress(string address)
    {
        var root = new RootObject();

        var url =
            string.Format(
                "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true_or_false", address);
        var req = (HttpWebRequest)WebRequest.Create(url);

        var res = (HttpWebResponse)req.GetResponse();

        using (var streamreader=new StreamReader(res.GetResponseStream()))
        {
            var result = streamreader.ReadToEnd();

            if (!string.IsNullOrWhiteSpace(result))
            {
                root = JsonConvert.DeserializeObject<RootObject>(result);
            }
        }
        return root;


    }


          /* Call This*/

var destination_latLong = GetLatLongByAddress(um.RouteDestination);

var lattitude =Convert.ToString( destination_latLong.results[0].geometry.location.lat, CultureInfo.InvariantCulture);

 var longitude=Convert.ToString( destination_latLong.results[0].geometry.location.lng, CultureInfo.InvariantCulture);