4

给定一个位置的坐标,有没有办法得到地名?

我不是指地址,我指的是地点的“标题”,例如:

Coordinates: 76.07, -62.0 // or whatever they are
Address: 157 Riverside Avenue, Champaign, Illinois
Place name: REO Speedwagon's Rehearsal Spot

-或者:

Coordinates: 76.07, -62.0 // or whatever they are
Address: 77 Sunset Strip, Hollywood, CA
Place name: Famous Amos Cookies

那么是否有反向地理编码网络服务或我可以调用的东西,例如:

string placeName = GetPlaceNameForCoordinates(76.07, -62.0)

...这将返回“Wal*Mart”或“Columbia Jr. College”或任何合适的?

我找到了对其他语言的引用,例如 java 和 ios(我猜是目标 C),但没有专门针对如何在 Windows 商店应用程序中使用 C# 执行此操作...

更新

我已经有了这个来获取地址(改编自 Freeman 的“Metro Revealed:使用 XAML 和 C# 构建 Windows 8 应用程序”第 75 页):

public static async Task<string> GetStreetAddressForCoordinates(double latitude, double longitude)
{
    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("http://nominatim.openstreetmap.org");
    HttpResponseMessage httpResult = await httpClient.GetAsync(
        String.Format("reverse?format=json&lat={0}&lon={1}", latitude, longitude));

    JsonObject jsonObject = JsonObject.Parse(await httpResult.Content.ReadAsStringAsync());

    return string.format("{0} {1}", jsonObject.GetNamedObject("address").GetNamedString("house"),
                                    jsonObject.GetNamedObject("address").GetNamedString("road"));
 }

...但我在他们的文档中看不到地名;他们似乎提供房屋、道路、村庄、城镇、城市、县、邮政编码和国家,但没有提供地名。

4

4 回答 4

3

I usually store the latitude/longitude coordinates and then use GMaps to look up the location, then "on a best effort basis" - look up the place's name using the address - again via Google Maps.

static string baseUri = 
  "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false";
string location = string.Empty;

public static void RetrieveFormatedAddress(string lat, string lng)
{
    string requestUri = string.Format(baseUri, lat, lng);

    using (WebClient wc = new WebClient())
    {
        string result = wc.DownloadString(requestUri);
        var xmlElm = XElement.Parse(result);
        var status = (from elm in xmlElm.Descendants() where 
            elm.Name == "status" select elm).FirstOrDefault();
        if (status.Value.ToLower() == "ok")
        {
            var res = (from elm in xmlElm.Descendants() where 
                elm.Name == "formatted_address" select elm).FirstOrDefault();
            requestUri = res.Value;
        }
    }
}

Edit:

Here's a simple version of the reverse:

public static Coordinate GetCoordinates(string region)
{
    using (var client = new WebClient())
    {

        string uri = "http://maps.google.com/maps/geo?q='" + region + 
          "'&output=csv&key=sadfwet56346tyeryhretu6434tertertreyeryeryE1";

        string[] geocodeInfo = client.DownloadString(uri).Split(',');

        return new Coordinate(Convert.ToDouble(geocodeInfo[2]), 
                   Convert.ToDouble(geocodeInfo[3]));
    }
}

public struct Coordinate
{
    private double lat;
    private double lng;

    public Coordinate(double latitude, double longitude)
    {
        lat = latitude;
        lng = longitude;

    }

    public double Latitude { get { return lat; } set { lat = value; } }
    public double Longitude { get { return lng; } set { lng = value; } }

}
于 2012-12-04T04:56:36.097 回答
3

我找到了对其他语言的引用,例如 java 和 ios(我猜是 Objective C)

仔细查看这些参考资料——它们中的大多数都可能使用反向地理编码Web 服务……您的 Windows 应用商店应用程序也可以使用这些参考资料。为您的应用选择具有适当功能和限制的服务,并向其发出 HTTP 请求。(您甚至可能会发现有一个合适的客户端库可用,尽管我认为现在相对不太可能,因为 Windows 8 的最新性...)

于 2012-12-03T18:45:45.000 回答
1
          Geolocator geolocator = new Geolocator(); 
           Geoposition geoposition = await geolocator.GetGeopositionAsync();
            string lat = geoposition.Coordinate.Point.Position.Latitude.ToString();
            string lon = geoposition.Coordinate.Point.Position.Longitude.ToString();
            string baseUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false", lat, lon);
            HttpClient client = new HttpClient();
            var response = await client.GetStringAsync(baseUri);
            var responseElement = XElement.Parse(response);
            IEnumerable<XElement>statusElement = from st in responseElement.Elements("status") select st;
            if (statusElement.FirstOrDefault() != null)
            {
                string status = statusElement.FirstOrDefault().Value;
                if (status.ToLower() == "ok")
                {
                    IEnumerable<XElement> resultElement = from rs in responseElement.Elements("result") select rs;
                    if (resultElement.FirstOrDefault() != null)
                    {
                        IEnumerable<XElement> addressElement = from ad in resultElement.FirstOrDefault().Elements("address_component") select ad;
                        foreach (XElement element in addressElement)
                        {
                            IEnumerable<XElement> typeElement = from te in element.Elements("type") select te;
                            string type = typeElement.FirstOrDefault().Value;
                            if(type=="locality")
                            {
                                IEnumerable<XElement> cityElement = from ln in element.Elements("long_name") select ln;
                                string city = cityElement.FirstOrDefault().Value;
                                break;
                            }
                        }
                    }
                }
            }
于 2015-05-11T06:03:00.543 回答
1

在 c# 控制台应用程序中使用以下代码。传递具有坐标的 CSV 路径,它将从响应中获取地址标签并将其放入 CSV

 using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Google_Padouri

{
    class Program
    {
        static void Main(string[] args)
        {
            Google obj = new Google();
            obj.Execute();
        }



}

class Google
{

    public void Execute()
    {
        string result = string.Empty;
        try
        {
            Console.WriteLine("Enter complete csv path");
            string path = Console.ReadLine();

            //string path = @"C:\tmp\google\test_file.csv";

            string[] rows = File.ReadAllLines(path);
            StringBuilder sb = new StringBuilder();
            int count = 0;

            foreach(string row in rows)
            {
                string[] arr = row.Split(',');
                string lat = arr[0];
                string lng = arr[1];

                if (count > 0) 
                {
                    result = GetResult(lat, lng);
                    if (result.Length > 1)
                    {
                        result = GetAddress(result);
                        if (result.Length > 1)
                        {
                            Console.WriteLine("Working on row number " + count);
                            sb.Append(lat + "," + lng + "," + result.Replace(",", "") + "\n");

                            //if(count==200)
                            //{
                            //    break;
                            //}
                        }
                        else
                        {
                            Console.WriteLine("Could not fetch results");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Google API response failed");
                    }
                }
                count = count+1;
            }

            string dir = Path.GetDirectoryName(path);
            string file = Path.GetFileNameWithoutExtension(path);
            file = file + "_output.csv";
            string fullpath = dir + "\\" + file;
            using (StreamWriter wrtier = File.CreateText(fullpath))
            {
                wrtier.Write(sb.ToString());
            }
            Console.Write("File compiled successfully");
            Console.Read();

        }
        catch (Exception ex)
        {
            Console.Write(ex);
        }
    }

    public string GetResult(string lat,string lang)
    {

        string method = "GET";
        string URL = "https://maps.googleapis.com/maps/api/geocode/json?";
        string Key = "key=YOUR_KEY";
        string Sensor = "sensor=false&";
        string latlng = "latlng=" + lat + "," + lang;
        string result = string.Empty;

        URL = URL + Key + Sensor + latlng;

        try
        {
            using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                wc.Encoding = Encoding.UTF8;
                wc.Headers.Add("User-Agent: Other");

                switch (method.ToUpper())
                {
                    case "GET":
                        result = wc.DownloadString(URL);
                        break;
                }
            }
        }
        catch (Exception ex)
        {
            Console.Write(ex);
            Console.Read();
        }

        return result;
    }

    public string GetAddress(string data)
    {
        string result = string.Empty;
        try
        {
            if (data.Length > 1)
            {
                JToken token = JToken.Parse(data);
                JArray array = JArray.Parse(token["results"].ToString());



                    result = array.First["formatted_address"].ToString();


            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            Console.Read();
        }
        return result;
    }


   }

}
于 2019-09-02T19:25:45.957 回答