summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Maps.WinRT.Tablet/GeocoderBackend.cs
blob: 565182d46de5143da913f4bcd43b99142a6b6bb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Bing.Maps;
using Bing.Maps.Search;

namespace Xamarin.Forms.Maps.WinRT
{
	internal class GeocoderBackend
	{
		public static void Register()
		{
			Geocoder.GetPositionsForAddressAsyncFunc = GetPositionsForAddress;
			Geocoder.GetAddressesForPositionFuncAsync = GetAddressesForPositionAsync;
		}

		static async Task<IEnumerable<string>> GetAddressesForPositionAsync(Position position)
		{
			var results = new List<string>();
			var source = new TaskCompletionSource<IEnumerable<string>>();
			var requestOptions = new ReverseGeocodeRequestOptions(new Location(position.Latitude, position.Longitude));
			var response =
				await
					new Bing.Maps.Map { Credentials = FormsMaps.AuthenticationToken }.SearchManager.ReverseGeocodeAsync(requestOptions);
			if (!response.HasError)
			{
				foreach (var address in response.LocationData)
					results.Add(address.Address.FormattedAddress);
			}

			return results;
		}

		static async Task<IEnumerable<Position>> GetPositionsForAddress(string s)
		{
			var results = new List<Position>();

			if (string.IsNullOrEmpty(s))
				return results;

			var requestOptions = new GeocodeRequestOptions(s);
			var response =
				await new Bing.Maps.Map { Credentials = FormsMaps.AuthenticationToken }.SearchManager.GeocodeAsync(requestOptions);
			if (!response.HasError)
			{
				foreach (var address in response.LocationData)
					results.Add(new Position(address.Location.Latitude, address.Location.Longitude));
			}
			return results;
		}
	}
}