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

时间:2013-01-16 09:20:12

标签: c# rest google-maps latitude-longitude

我在C#中有WCF服务。

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

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

我已从Google及其类型为'服务帐户获取API密钥。

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

我是否需要安装一些SDK或任何REST服务?

4 个答案:

答案 0 :(得分:57)

您可以尝试NuGet包GoogleMaps.LocationServices,或者只旋转其source code。它使用Google的REST API来获取给定地址的纬度/经度,反之亦然,而无需API密钥。

你这样使用它:

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...
}

答案 1 :(得分:17)

如果您想使用Google Maps API查看其REST API,则无需安装Google Maps API即可发送请求

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

您将获得XML响应。

欲了解更多信息,请查看

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

答案 2 :(得分:6)

您可以在特定网址中传递地址..并且您在返回值dt(数据表)中获得纬度和经度

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;
}

答案 3 :(得分:4)

     /*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);