forked from microsoft/react-native-windows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LocationModule.cs
209 lines (179 loc) · 7.54 KB
/
LocationModule.cs
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Collections;
using ReactNative.Modules.Core;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using static System.FormattableString;
namespace ReactNative.Modules.Location
{
class LocationModule : ReactContextNativeModuleBase, ILifecycleEventListener
{
private readonly SerialDisposable _currentSubscription = new SerialDisposable();
public LocationModule(ReactContext reactContext)
: base(reactContext)
{
}
public override string Name
{
get
{
return "LocationObserver";
}
}
[ReactMethod]
public async void getCurrentPosition(
JObject options,
ICallback success,
ICallback error)
{
var locationOptions = LocationOptions.FromJson(options);
var geolocator = new Geolocator
{
DesiredAccuracy = locationOptions.HighAccuracy ? PositionAccuracy.High : PositionAccuracy.Default,
MovementThreshold = locationOptions.DistanceFilter,
};
try
{
// TODO: Enable retrieval from position history using `MaximumAge` filter
var task = geolocator.GetGeopositionAsync().AsTask();
var completedTask = await Task.WhenAny(
task,
Task.Delay(TimeSpan.FromMilliseconds(locationOptions.Timeout))).ConfigureAwait(false);
if (completedTask == task)
{
var geoposition = await task.ConfigureAwait(false);
success.Invoke(ConvertGeoposition(geoposition));
}
else
{
error.Invoke("Location request timed out");
}
}
catch (Exception ex)
{
error.Invoke(Invariant($"Location request failed with exception: {ex}"));
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "CompositeDisposable managed by serial disposable and parent module.")]
[ReactMethod]
public void startObserving(JObject options)
{
var locationOptions = LocationOptions.FromJson(options);
var geolocator = new Geolocator
{
DesiredAccuracy = locationOptions.HighAccuracy ? PositionAccuracy.High : PositionAccuracy.Default,
MovementThreshold = locationOptions.DistanceFilter,
};
var positionObservable =
Observable.FromEventPattern<
TypedEventHandler<Geolocator, PositionChangedEventArgs>,
Geolocator,
PositionChangedEventArgs>(
h => geolocator.PositionChanged += h,
h => geolocator.PositionChanged -= h);
var positionQuery = from e in positionObservable
select e.EventArgs.Position;
var positionSubscription = positionQuery.Subscribe(position =>
Context.GetJavaScriptModule<RCTDeviceEventEmitter>()
.emit("geolocationDidChange", ConvertGeoposition(position)));
var statusObservable =
Observable.FromEventPattern<
TypedEventHandler<Geolocator, StatusChangedEventArgs>,
Geolocator,
StatusChangedEventArgs>(
h => geolocator.StatusChanged += h,
h => geolocator.StatusChanged -= h);
var statusQuery = from e in statusObservable
select e.EventArgs.Status;
var statusSubscription = statusQuery.Subscribe(status =>
{
if (status == PositionStatus.Disabled)
{
Context.GetJavaScriptModule<RCTDeviceEventEmitter>()
.emit("geolocationError", "Location settings are turned off.");
}
else if (status == PositionStatus.NotAvailable)
{
Context.GetJavaScriptModule<RCTDeviceEventEmitter>()
.emit("geolocationError", "Location services is not available.");
}
else if (status == PositionStatus.NoData || status == PositionStatus.Initializing)
{
Context.GetJavaScriptModule<RCTDeviceEventEmitter>()
.emit("geolocationError", "Location services is temporarily unavailable.");
}
});
_currentSubscription.Disposable =
new CompositeDisposable(2)
{
positionSubscription,
statusSubscription,
};
}
[ReactMethod]
public void stopObserving()
{
_currentSubscription.Disposable = Disposable.Empty;
}
public void OnSuspend()
{
}
public void OnResume()
{
}
public void OnDestroy()
{
_currentSubscription.Dispose();
}
private static JObject ConvertGeoposition(Geoposition geoposition)
{
var coords = new JObject
{
{ "latitude", geoposition.Coordinate.Point.Position.Latitude },
{ "longitude", geoposition.Coordinate.Point.Position.Longitude },
{ "altitude", geoposition.Coordinate.Point.Position.Altitude },
{ "accuracy", geoposition.Coordinate.Accuracy },
{ "bearing", geoposition.Coordinate.Heading },
{ "speed", geoposition.Coordinate.Speed }
};
return new JObject
{
{ "coords", coords },
{ "timestamp", geoposition.Coordinate.Timestamp.ToUnixTimeMilliseconds() },
};
}
class LocationOptions
{
private const double DefaultLocationAccuracy = 100;
private const double DefaultMaximumAge = 86.4e6 /* TimeSpan.FromDays(1).TotalMilliseconds */;
private LocationOptions(long timeout, double maximumAge, bool highAccuracy, double distanceFilter)
{
Timeout = timeout;
MaximumAge = maximumAge;
HighAccuracy = highAccuracy;
DistanceFilter = distanceFilter;
}
public long Timeout { get; }
public double MaximumAge { get; }
public bool HighAccuracy { get; }
public double DistanceFilter { get; }
public static LocationOptions FromJson(JObject json)
{
var timeout =
json.ContainsKey("timeout") ? json.Value<long>("timeout") : -1;
var maximumAge =
json.ContainsKey("maximumAge") ? json.Value<double>("maximumAge") : double.PositiveInfinity;
var highAccuracy =
json.ContainsKey("enableHighAccuracy") && json.Value<bool>("enableHighAccuracy");
var distanceFilter =
json.ContainsKey("distanceFilter") ? json.Value<double>("distanceFilter") : 100;
return new LocationOptions(timeout, maximumAge, highAccuracy, distanceFilter);
}
}
}
}