aboutsummaryrefslogtreecommitdiffhomepage
path: root/examples/csharp/route_guide/RouteGuide/RouteGuideUtil.cs
blob: 6fb8b1e28abb751b05b377aead1a10548aeb666e (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace examples
{
    public static class RouteGuideUtil
    {
        public const string DefaultFeaturesFile = "route_guide_db.json";

        private const double CoordFactor = 1e7;

        /// <summary>
        /// Indicates whether the given feature exists (i.e. has a valid name).
        /// </summary>
        public static bool Exists(Feature feature)
        {
            return feature != null && (feature.Name.Length != 0);
        }

        public static double GetLatitude(Point point)
        {
            return point.Latitude / CoordFactor;
        }

        public static double GetLongitude(Point point)
        {
            return point.Longitude / CoordFactor;
        }

        /// <summary>
        /// Parses features from a JSON file.
        /// </summary>
        public static List<Feature> ParseFeatures(string filename)
        {
            var features = new List<Feature>();
            var jsonFeatures = JsonConvert.DeserializeObject<List<JsonFeature>>(File.ReadAllText(filename));


            foreach(var jsonFeature in jsonFeatures)
            {
                features.Add(Feature.CreateBuilder().SetName(jsonFeature.name).SetLocation(
                    Point.CreateBuilder()
                        .SetLongitude(jsonFeature.location.longitude)
                        .SetLatitude(jsonFeature.location.latitude).Build()).Build());
            }
            return features;
        }

        private class JsonFeature
        {
            public string name;
            public JsonLocation location;
        }

        private class JsonLocation
        {
            public int longitude;
            public int latitude;
        }
    }
}