Как позвонить в службу BEST Maps REST с помощью NuGet Bing.RestClient - PullRequest
0 голосов
/ 28 марта 2019

Я хочу использовать NuGet с именем Bing.RestClient v0.8 beta 1 в Visual Studio 2017, но я понятия не имею, как использовать его в Windows Forms для определения местоположения (широта / долгота).

Я еще не знаком со службами REST.

Какой-нибудь пример кода, который может помочь мне структурировать проект и понять, как он работает?

Я пытался с веб-клиентом, и я могу получить ответ TEXT, который я могу проанализировать, но я хочу использовать классы, доступные в NuGet Bing.RestClient.

public partial class Form1 : Form
{
    // PERSONAL BING KEY
    String BingKey = "*******************************";

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        GetFind();
    }

    private async void  GetFind()
    {

        // Take advantage of built-in Point of Interest groups
        var list = PoiEntityGroups.Government();
        list.Add(PoiEntityTypes.Bank);
        // Build your filter list from the group.
        var filter = PoiEntityGroups.BuildFilter(list);
        var client = new Bing.SpatialDataClient(BingKey);

        //---------------------------------------------------------
        // This does NOT use the Nuget but just a WebClient and I get the response in TEXT format. But this is not what I want.
        String AddressQuery = "Via Ravenna 10, Milano";
        String BaseQueryURL;
        BaseQueryURL = String.Format("http://dev.virtualearth.net/REST/v1/Locations?query={0}?maxResults=1&key={1}", AddressQuery, BingKey);

        // Create web client simulating IE6.
        using (System.Net.WebClient wclient = new WebClient())
        {
            wclient.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)";

            byte[] arr = wclient.DownloadData(BaseQueryURL);
            txtResult.Text = "Bytes: " + arr.Length + Environment.NewLine;
            txtResult.Text = txtResult.Text + wclient.DownloadString(BaseQueryURL);
        }
        //---------------------------------------------------------
    }
}

Я ожидаю, что результат будет десериализован с помощью классов NuGet, но я не знаю, как их использовать, чтобы получить широту и долготу, запрашивая по адресу.

Ответы [ 2 ]

0 голосов
/ 29 марта 2019

Спасибо Брайану за ваш драгоценный пример.Наконец-то у меня все работает очень хорошо, в Windows Forms:

public partial class Form1 : Form
    {
        // PERSONAL BING KEY
        String BingKey = "*******************************";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            GetFind();
        }

        private async void GetFind()
        {    
            var request = new GeocodeRequest()
            {
                Query = "Via trento 1, Sondrio",
                IncludeIso2 = true,
                IncludeNeighborhood = true,
                MaxResults = 25,
                BingMapsKey = BingKey
            };


            //Process the request by using the ServiceManager.
            var response = await request.Execute();

            if (response != null &&
                response.ResourceSets != null &&
                response.ResourceSets.Length > 0 &&
                response.ResourceSets[0].Resources != null &&
                response.ResourceSets[0].Resources.Length > 0)
            {
                var result = response.ResourceSets[0].Resources[0] as Location;

                var myAddr = result.Address.AddressLine;
                var CAP = result.Address.PostalCode;
                var City = result.Address.Locality;
                var Province = result.Address.AdminDistrict2;
                var Region = result.Address.AdminDistrict;
                var Stato = result.Address.CountryRegion;

                var coords = result.Point.Coordinates;
                if (coords != null && coords.Length == 2)
                {
                    var lat = coords[0];
                    var lng = coords[1];

                    string Latitude = String.Format("{0:00.000000}", lat);
                    string Longitude = String.Format("{0:000.000000}", lng);

                    txtResult.Text = "Indirizzo: " + myAddr +
                        Environment.NewLine + "CAP: " + CAP +
                        Environment.NewLine + "Città: " + City +
                        Environment.NewLine + "Provincia: " + Province +
                        Environment.NewLine + "Regione: " + Region +
                        Environment.NewLine + "Stato: " + Stato + 
                        Environment.NewLine + $"Coordinate - Lat: {Latitude} / Long: {Longitude}"
                        ;
                }
            }
        } 
    }
}
0 голосов
/ 28 марта 2019

Я бы предложил вам ознакомиться с примерами, представленными на странице GitHub для пакета NuGet BingMapsRESTToolkit.(https://github.com/Microsoft/BingMapsRESTToolkit/blob/master/Docs/Getting%20Started.md#HowToMakeARequest)

Вот базовый пример с GitHub, который я получил в Visual Studio в качестве консольного приложения:

    static async Task Main()
    {
        var bingKey = "**********************";

        var request = new GeocodeRequest()
        {
            Query = "Via Ravenna 10, Milano",
            IncludeIso2 = true,
            IncludeNeighborhood = true,
            MaxResults = 25,
            BingMapsKey = bingKey
        };

        //Process the request by using the ServiceManager.
        var response = await request.Execute();

        if (response != null &&
            response.ResourceSets != null &&
            response.ResourceSets.Length > 0 &&
            response.ResourceSets[0].Resources != null &&
            response.ResourceSets[0].Resources.Length > 0)
        {
            var result = response.ResourceSets[0].Resources[0] as Location;

            var coords = result.Point.Coordinates;
            if (coords != null && coords.Length == 2)
            {
                var lat = coords[0];
                var lng = coords[1];
                Console.WriteLine($"Geocode Results - Lat: {lat} / Long: {lng}");
            }
        }
    }

Теперь у вас есть пара лат /Если введите Double, используйте их в своей форме Windows, как считаете нужным.

...