Ejemplo n.º 1
0
 public void GetHighways()
 {
     var northEast = new LatLng { lat = 31.6331, lng = 34.9286 };
     var southWest = new LatLng { lat = 31.6320, lng = 34.9266 };
     var highways = _gateway.GetHighways(northEast, southWest).Result;
     Assert.AreEqual(1, highways.Count);
 }
Ejemplo n.º 2
0
		public void Equals(double lat, double lng)
		{
			LatLng latLng1 = new LatLng(lat, lng);
			LatLng latLng2 = new LatLng(lat, lng);

			Assert.IsTrue(latLng1.Equals(latLng2), "Equals fails.");
		}
		public void GetElevationForTwoLocations()
		{
			// expectations
			var expectedStatus = ServiceResponseStatus.Ok;
			var expectedResultCount = 2;

			var expectedElevation1 = 1608.6m;
			var expectedLocation1 = new LatLng(39.739153,-104.984703);
			var expectedElevation2 = -50.789m;
			var expectedLocation2 = new LatLng(36.4555560,-116.8666670);

			// test
			var request = new ElevationRequest();

			request.AddLocations(expectedLocation1, expectedLocation2);
			request.Sensor = false;
			var response = new ElevationService().GetResponse(request);

			// asserts
			Assert.AreEqual(expectedStatus, response.Status);

			Assert.AreEqual(expectedResultCount, response.Results.Length);
			
			Assert.That(expectedElevation1, Is.EqualTo(response.Results[0].Elevation).Within(0.1));
			Assert.That(expectedLocation1, Is.EqualTo(response.Results[0].Location));
			
			Assert.That(expectedElevation2, Is.EqualTo(response.Results[1].Elevation).Within(0.1));
			Assert.That(expectedLocation2, Is.EqualTo(response.Results[1].Location));
		}
Ejemplo n.º 4
0
        public Task Initialize()
        {
            var elevationCacheFolder = Path.Combine(ConfigurationManager.AppSettings[ProcessHelper.BIN_FOLDER_KEY], ELEVATION_CACHE);
            if (Directory.Exists(elevationCacheFolder) == false)
            {
                _logger.Error($"!!! The folder: {elevationCacheFolder} does not exists, please change the binFolder key in the configuration file !!!");
                return Task.Run(() => { });
            }
            var hgtZipFiles = Directory.GetFiles(elevationCacheFolder, "*.hgt.zip");
            _logger.Debug("Found " + hgtZipFiles.Length + " files in: " + elevationCacheFolder);
            foreach (var hgtZipFile in hgtZipFiles)
            {
                var bottomLeftLat = int.Parse(Path.GetFileName(hgtZipFile).Substring(1, 2));
                var bottomLeftLng = int.Parse(Path.GetFileName(hgtZipFile).Substring(4, 3));
                var key = new LatLng { lat = bottomLeftLat, lng = bottomLeftLng };

                _initializationTaskPerLatLng[key] = Task.Run(() =>
                {
                    _logger.Debug("Reading file " + hgtZipFile);
                    var byteArray = GetByteArrayFromZip(hgtZipFile);
                    int samples = (short) (Math.Sqrt(byteArray.Length/2.0) + 0.5);
                    var elevationArray = new short[samples, samples];
                    for (int byteIndex = 0; byteIndex < byteArray.Length; byteIndex += 2)
                    {
                        short currentElevation = BitConverter.ToInt16(new[] {byteArray[byteIndex + 1], byteArray[byteIndex]}, 0);
                        elevationArray[(byteIndex/2)/samples, (byteIndex/2)%samples] = currentElevation;
                    }
                    _elevationData[key] = elevationArray;
                    _logger.Debug("Finished reading file " + hgtZipFile);
                });
            }

            return Task.WhenAll(_initializationTaskPerLatLng.Values);
        }
Ejemplo n.º 5
0
		private static LatLng BoxCorners(LatLng center, double d, double brngdeg)
		{
			double a = center.GetLat();
			double b = center.GetLng();
			double R = 3963.0; // radius of earth in miles
			double brng = (MathHelper.PI * brngdeg / 180);
			double lat1 = (MathHelper.PI * a / 180);
			double lon1 = (MathHelper.PI * b / 180);

			// Haversine formula
			double lat2 = Math.Asin(Math.Sin(lat1) * Math.Cos(d / R) +
			                        Math.Cos(lat1) * Math.Sin(d / R) * Math.Cos(brng));
			double lon2 = lon1 + Math.Atan2(Math.Sin(brng) * Math.Sin(d / R) * Math.Cos(lat1),
			                                Math.Cos(d / R) - Math.Sin(lat1) * Math.Sin(lat2));

			lat2 = (lat2 * 180) / MathHelper.PI;
			lon2 = (lon2 * 180) / MathHelper.PI;

			// normalize long first
			LatLng ll = NormLng(lat2, lon2);

			// normalize lat - could flip poles
			ll = NormLat(ll.GetLat(), ll.GetLng());

			return ll;
		}
Ejemplo n.º 6
0
 public Marker(LatLng point, String title, String iconSource, IMapServiceJS mapServiceJS):base(mapServiceJS)
 {
     this.point = point;
     this.title = title;
     this.iconSource = iconSource;
     Redraw();
 }
Ejemplo n.º 7
0
 public Task Initialize()
 {
     return Task.Run(() =>
     {
         var hgtFolder = ConfigurationManager.AppSettings["hgtFolder"].ToString();
         if (Directory.Exists(hgtFolder) == false)
         {
             _logger.Error("!!! The folder: " + hgtFolder + " does not exists, please change the hgtFolder key in the configuration file !!!");
             return;
         }
         var hgtZipFiles = Directory.GetFiles(hgtFolder, "*.hgt.zip");
         _logger.Debug("Found " + hgtZipFiles.Length + " files in: " + hgtFolder);
         foreach (var hgtZipFile in hgtZipFiles)
         {
             _logger.Debug("Reading file " + hgtZipFile);
             var byteArray = GetByteArrayFromZip(hgtZipFile);
             int samples = (short)(Math.Sqrt(byteArray.Length / 2) + 0.5);
             var bottomLeftLat = int.Parse(Path.GetFileName(hgtZipFile).Substring(1, 2));
             var bottomLeftLng = int.Parse(Path.GetFileName(hgtZipFile).Substring(4, 3));
             var key = new LatLng { Lat = bottomLeftLat, Lng = bottomLeftLng };
             _elevationData[key] = new short[samples, samples];
             for (int byteIndex = 0; byteIndex < byteArray.Length; byteIndex += 2)
             {
                 short currentElevation = BitConverter.ToInt16(new[] { byteArray[byteIndex + 1], byteArray[byteIndex] }, 0);
                 _elevationData[key][(byteIndex / 2) / samples, (byteIndex / 2) % samples] = currentElevation;
             }
         }
     });
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Decode encoded polyline information to a collection of <see cref="LatLng"/> instances.
        /// </summary>
        /// <param name="value">ASCII string</param>
        /// <returns></returns>
        public static IEnumerable<LatLng> Decode(string value)
        {
            //decode algorithm adapted from saboor awan via codeproject:
            //http://www.codeproject.com/Tips/312248/Google-Maps-Direction-API-V3-Polyline-Decoder
            //note the Code Project Open License at http://www.codeproject.com/info/cpol10.aspx

            if (value == null || value == "") return new List<LatLng>(0);

            char[] polylinechars = value.ToCharArray();
            int index = 0;

            int currentLat = 0;
            int currentLng = 0;
            int next5bits;
            int sum;
            int shifter;

            List<LatLng> poly = new List<LatLng>();

            while (index < polylinechars.Length)
            {
                // calculate next latitude
                sum = 0;
                shifter = 0;
                do
                {
                    next5bits = (int)polylinechars[index++] - 63;
                    sum |= (next5bits & 31) << shifter;
                    shifter += 5;
                } while (next5bits >= 32 && index < polylinechars.Length);

                if (index >= polylinechars.Length)
                    break;

                currentLat += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);

                //calculate next longitude
                sum = 0;
                shifter = 0;
                do
                {
                    next5bits = (int)polylinechars[index++] - 63;
                    sum |= (next5bits & 31) << shifter;
                    shifter += 5;
                } while (next5bits >= 32 && index < polylinechars.Length);

                if (index >= polylinechars.Length && next5bits >= 32)
                    break;

                currentLng += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
                LatLng point = new LatLng(
                    latitude: Convert.ToDouble(currentLat) / 100000.0,
                    longitude: Convert.ToDouble(currentLng) / 100000.0
                );
                poly.Add(point);
            }

            return poly;
        }
		public void Ex_1_precision()
		{
			LatLng expected = new LatLng(30.3, 40.4);

			LatLng actual = new LatLng(30.31, 40.41);

			Assert.That(expected, Is.EqualTo(actual).Using(LatLngComparer.Within(0.1f)));
		}
		public void Ex_6_precision()
		{
			LatLng expected = new LatLng(30.343434, 40.412121);

			LatLng actual = new LatLng(30.34343400001, 40.41212100001);

			Assert.That(expected, Is.EqualTo(actual).Using(LatLngComparer.Within(0.000001f)));
		}
Ejemplo n.º 11
0
 public PolyLine(LatLng[] points, Color color, int strokeWeight, double strokeOpacity, IMapServiceJS mapServiceJS):base(mapServiceJS)
 {
     this.strokeColor = color;
     this.strokeWeight = strokeWeight;
     this.strokeOpacity = strokeOpacity;
     this.points = points;
     Redraw();
 }
Ejemplo n.º 12
0
		/// <summary>
		/// Approximates a box centered at the given point with the given width and height in miles.
		/// </summary>
		/// <param name="center">The center.</param>
		/// <param name="widthMi">The width mi.</param>
		/// <param name="heightMi">The height mi.</param>
		/// <returns></returns>
		public static LLRect CreateBox(LatLng center, double widthMi, double heightMi)
		{
			double d = widthMi;
			LatLng ur = BoxCorners(center, d, 45.0); // assume right angles
			LatLng ll = BoxCorners(center, d, 225.0);

			return new LLRect(ll, ur);
		}
Ejemplo n.º 13
0
		public void ToString_default_format()
		{
			LatLng latlng = new LatLng(-35.3353m, 95.4454m);

			string expected = "-35.335300,95.445400";
			string actual = latlng.ToString();

			Assert.AreEqual(expected, actual);
		}
 public void GetHighways_ShouldReturnResults()
 {
     var gateway = new ElasticSearchGateway(new TraceLogger());
     gateway.Initialize();
     var northEast = new LatLng(31.7553, 35.0516);
     var southWest = new LatLng(31.7467, 35.0251);
     var results = gateway.GetHighways(northEast, southWest).Result;
     Assert.AreEqual(36, results.Count);
 }
Ejemplo n.º 15
0
		public void Parse_test()
		{
			string value = "40.714224,-73.961452";

			LatLng expected = new LatLng(40.714224m, -73.961452m);
			LatLng actual = LatLng.Parse(value);

			Assert.AreEqual(expected.Latitude, actual.Latitude);
			Assert.AreEqual(expected.Longitude, actual.Longitude);
		}
Ejemplo n.º 16
0
		public void GetAsUrlEncoded(double lat, double lng, string expected)
		{
			LatLng latlng = new LatLng(lat,lng);

			//string expected = "-35.335300,95.445400";
			string actual = latlng.GetAsUrlParameter();

			//note, if this test starts failing, it may be because the 'comma' is being (in some circles' opinion) "properly" url encoded to %2c
			Assert.AreEqual(expected, actual);
		}
Ejemplo n.º 17
0
 private async Task<SegmentSummary[]> RetrieveSegments()
 {
     // retrieve segments near Zalaegerszeg, Hungary
     var southWest = new LatLng { Latitude = 46.828100f, Longitude = 16.781540f };
     var northEast = new LatLng { Latitude = 46.859259f, Longitude = 16.832550f };
     var segments = (await _client.Segments.Explore(southWest, northEast)).ToArray();
     Assert.NotNull(segments);
     Assert.True(segments.Length > 1);
     return segments;
 }
Ejemplo n.º 18
0
 public Polygon(LatLng[] points, Color strokeColor, int strokeWeight, double strokeOpacity, Color fillColor, double fillOpacity,IMapServiceJS mapServiceJS):base(mapServiceJS)
 {
     this.strokeColor = Utility.ColorToRGB(strokeColor);
     this.strokeWeight = strokeWeight;
     this.strokeOpacity = strokeOpacity;
     this.fillColor = Utility.ColorToRGB(fillColor);
     this.fillOpacity = fillOpacity;
     this.points = points;
     Redraw();
 }
Ejemplo n.º 19
0
 public void ShapeMarker(MapShapes shape, LatLng point, String title, String iconSource)
 {
     String icon = "G_DEFAULT_ICON";
     if (iconSource != null)
     {
         icon = "new GIcon(G_DEFAULT_ICON,'" + iconSource + "')";
     }
     String evalString = shape.Id + " = new GMarker(new GLatLng(" + point.ToString() + "),{title: '" + title + "',icon:" + icon + "});";
     HtmlPage.Window.Eval(evalString);
     ShapeInitClickHandler(shape.Id);
 }
Ejemplo n.º 20
0
 public async Task<List<CompleteWay>> GetHighways(LatLng northEast, LatLng southWest)
 {
     var boundsString = string.Join(",", southWest.lat, southWest.lng, northEast.lat, northEast.lng);
     var address = $"{OVERPASS_INTERPRETER_ADDRESS}?data=(way[\"highway\"]({boundsString});>;);out;";
     using (var client = new HttpClient())
     {
         var response = await client.GetAsync(address);
         var source = new XmlOsmStreamSource(await response.Content.ReadAsStreamAsync());
         var completeSource = new OsmSimpleCompleteStreamSource(source);
         return completeSource.OfType<CompleteWay>().ToList();
     }
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Application 对象的构造函数。
        /// </summary>
        public App()
        {
            IsFromSearchPage = false;
            IsFromRoutePage = false;
            TempMap = null;
            _latlng = null;
            _bearing = 0;
            _tile = 0;
            _cameraIsNew = true;
            _isNew = true;
            SocketClient=new SocketClient();

            // 未捕获的异常的全局处理程序。
            UnhandledException += Application_UnhandledException;

            // 标准 XAML 初始化
            InitializeComponent();

            // 特定于电话的初始化
            InitializePhoneApplication();

            // 语言显示初始化
            InitializeLanguage();

            /*******************************************
               填写高德地图服务key
               *******************************************/
            const string key = "a1b63541add32fada5840b302d2325f8";

            AMapConfig.Key = key;//地图显示key
            AMapSearchConfig.Key = key;

            // 调试时显示图形分析信息。
            if (Debugger.IsAttached)
            {
                // 显示当前帧速率计数器。
                Current.Host.Settings.EnableFrameRateCounter = true;

                // 显示在每个帧中重绘的应用程序区域。
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // 启用非生产分析可视化模式,
                // 该模式显示递交给 GPU 的包含彩色重叠区的页面区域。
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // 通过禁用以下对象阻止在调试过程中关闭屏幕
                // 应用程序的空闲检测。
                //  注意: 仅在调试模式下使用此设置。禁用用户空闲检测的应用程序在用户不使用电话时将继续运行
                // 并且消耗电池电量。
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
            SetUriMapping();
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Gets the distance.
 /// </summary>
 /// <param name="p1">The p1.</param>
 /// <param name="p2">The p2.</param>
 /// <returns></returns>
 public static double GetDistance(LatLng p1, LatLng p2)
 {
     var radLat1 = Rad(p1.Latitude);
     var radLat2 = Rad(p2.Latitude);
     var a = radLat1 - radLat2;
     var b = Rad(p1.Longitude) - Rad(p2.Longitude);
     var s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
     Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
     s = s * EARTH_RADIUS; ;
     s = Math.Round(s * 10000) / 10000;
     return s;
 }
		public void encode_coords_1()
		{
			LatLng[] points = new LatLng[] { 
				new LatLng(38.5,-120.2),
				new LatLng(40.7,-120.95),
				new LatLng(43.252,-126.453)
			};

			string actual = PolylineEncoder.EncodeCoordinates(points);
			string expected = "_p~iF~ps|U_ulLnnqC_mqNvxq`@";

			Assert.AreEqual(expected, actual);
		}
Ejemplo n.º 24
0
        public void NotEquals(double lat, double lng)
        {
            LatLng latLng1 = new LatLng(lat, lng);
            LatLng latLng2 = new LatLng(0d, lng);

            Assert.IsFalse(latLng1.Equals(latLng2));

            LatLng latLng3 = new LatLng(lat, 0d);
            Assert.IsFalse(latLng1.Equals(latLng3));

            LatLng latLng4 = new LatLng(0d, 0d);
            Assert.IsFalse(latLng1.Equals(latLng4));
        }
        public void GetResultForDirections_ex1()
        {
            // expectations
            var expectedStatus = ServiceResponseStatus.Ok;
            var expectedRoutesCount = 1;

            var expectedEndAddress = "Montreal, QC, Canada";
            var expectedEndLocation = new LatLng(45.508570, -73.553770);

            var expectedStartAddress = "Toronto, ON, Canada";
            var expectedStartLocation = new LatLng(43.653310, -79.382770);

            var expectedBounds = new Viewport(
                northEast: new LatLng(45.51048, -73.55332),
                southWest: new LatLng(43.65331, -79.38373)
            );

            var expectedDistance = new ValueText() { Text = "542 km", Value = "542382" };
            var expectedDuration = new ValueText() { Text = "5 hours 27 mins", Value = "19608" };

            var expectedSteps = 13;

            var expectedSummary = "ON-401 E";

            // test
            var request = new DirectionRequest();
            request.Origin = "Toronto";
            request.Destination = "Montreal";
            request.Sensor = false;

            var response = new DirectionService().GetResponse(request);

            // asserts
            Assert.AreEqual(expectedStatus, response.Status, "Status");
            Assert.AreEqual(expectedRoutesCount, response.Routes.Length, "ResultCount");

            var currentLeg = response.Routes[0].Legs[0];

            Assert.That(expectedStartAddress, Is.EqualTo(currentLeg.StartAddress), "Leg.StartAddress");
            Assert.That(expectedStartLocation, Is.EqualTo(currentLeg.StartLocation).Using(LatLngComparer.Within(0.000001f)), "Leg.StartLocation");

            Assert.That(expectedEndAddress, Is.EqualTo(currentLeg.EndAddress), "Leg.EndAddress");
            Assert.That(expectedEndLocation, Is.EqualTo(currentLeg.EndLocation).Using(LatLngComparer.Within(0.000001f)), "Leg.EndLocation");

            Assert.That(expectedDistance, Is.EqualTo(currentLeg.Distance).Using(new ValueTextComparer(StringComparer.InvariantCultureIgnoreCase)));
            Assert.That(expectedDuration, Is.EqualTo(currentLeg.Duration).Using(new ValueTextComparer(StringComparer.InvariantCultureIgnoreCase)));

            Assert.That(expectedSteps, Is.EqualTo(currentLeg.Steps.Count()), "Leg.Steps");

            Assert.That(expectedSummary, Is.EqualTo(response.Routes[0].Summary), "Route.Summary");
        }
Ejemplo n.º 26
0
 public void ShapePolyLine(MapShapes shape, LatLng[] points, System.Windows.Media.Color color, Int32 weight, Double opacity)
 {
     StringBuilder sb = new StringBuilder();
     sb.Append("var " + shape.Id + " = new GPolyline([");
     for (int i = 0; i < points.Length - 1; i++)
     {
         sb.Append("new GLatLng(" + points[i].ToString() + ")");
         sb.Append(",");
     }
     sb.Append("new GLatLng(" + points[points.Length - 1].ToString() + ")],");
     sb.Append("'" + Utility.ColorToRGB(color) + "'," + weight + "," + opacity + ");");
     HtmlPage.Window.Eval(sb.ToString());
     ShapeInitClickHandler(shape.Id);
 }
Ejemplo n.º 27
0
        public double GetElevation(double lat, double lng)
        {
            var key = new LatLng { Lat = (int)lat, Lng = (int)lng };
            if (_elevationData.ContainsKey(key) == false)
            {
                return 0;
            }
            var array = _elevationData[key];
            var samplesSize = 1.0 / array.GetLength(0);
            var latIndex = (array.GetLength(0) - 1) - (int)((lat - key.Lat) / samplesSize);
            var lngIndex = (int)((lng - key.Lng) / samplesSize);

            return array[latIndex, lngIndex];
        }
        public void GetGeocodingForAddress1()
        {
            // expectations
            var expectedStatus = ServiceResponseStatus.Ok;
            var expectedResultCount = 1;
            var expectedType = AddressType.StreetAddress;
            var expectedFormattedAddress = "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA";
            var expectedComponentTypes = new AddressType[] {
                AddressType.StreetNumber,
                AddressType.Route,
                AddressType.Locality,
                AddressType.AdministrativeAreaLevel1,
                AddressType.AdministrativeAreaLevel2,
                AddressType.AdministrativeAreaLevel3,
                AddressType.Country,
                AddressType.PostalCode,
                AddressType.Political
            };
            var expectedLocation = new LatLng(37.42219410, -122.08459320);
            var expectedLocationType = LocationType.Rooftop;
            Viewport expectedViewport = new Viewport(
                southWest: new LatLng(37.42084511970850, -122.0859421802915),
                northEast: new LatLng(37.42354308029149, -122.0832442197085)
            );

            // test
            var request = new GeocodingRequest();
            request.Address = "1600 Amphitheatre Parkway Mountain View CA";
            request.Sensor = false;
            var response = new GeocodingService().GetResponse(request);

            // asserts
            Assert.AreEqual(expectedStatus, response.Status, "Status");
            Assert.AreEqual(expectedResultCount, response.Results.Length, "ResultCount");
            Assert.AreEqual(expectedType, response.Results.Single().Types.First(), "Type");
            Assert.AreEqual(expectedFormattedAddress, response.Results.Single().FormattedAddress, "FormattedAddress");
            //Assert.IsTrue(
            //    expectedComponentTypes.OrderBy(x => x).SequenceEqual(
            //        response.Results.Single().AddressComponents.SelectMany(y => y.Types).Distinct().OrderBy(z => z)), "Types");
            //Assert.AreEqual(expectedLatitude, response.Results.Single().Geometry.Location.Latitude, "Latitude");
            Assert.That(expectedLocation, Is.EqualTo(response.Results[0].Geometry.Location).Using(LatLngComparer.Within(0.000001f)), "Longitude");
            Assert.AreEqual(expectedLocationType, response.Results.Single().Geometry.LocationType, "LocationType");
            //Assert.AreEqual(expectedSouthwestLatitude, response.Results.Single().Geometry.Viewport.Southwest.Latitude, "Southwest.Latitude");
            //Assert.AreEqual(expectedSouthwestLongitude, response.Results.Single().Geometry.Viewport.Southwest.Longitude, "Southwest.Longitude");
            //Assert.AreEqual(expectedNortheastLatitude, response.Results.Single().Geometry.Viewport.Northeast.Latitude, "Northeast.Latitude");
            //Assert.AreEqual(expectedNortheastLongitude, response.Results.Single().Geometry.Viewport.Northeast.Longitude, "Northeast.Longitude");
        }
Ejemplo n.º 29
0
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        GoogleMarkers GoogleMarker = new GoogleMarkers();

        GoogleMarker.DataLatitudeField = "45.17654";
        GoogleMarker.DataLongitudeField = "14.4967";
        GoogleMarker.TargetControlID = "GoogleMap1";

        GoogleDirections gDirections = new GoogleDirections();
        LatLng gLatLngDestination = new LatLng();
        gLatLngDestination.Latitude = 45.17654;
        gLatLngDestination.Longitude = 14.4967;

        LatLng gLatLngOrigin = new LatLng();
        gLatLngOrigin.Latitude = 46.17654;
        gLatLngOrigin.Longitude = 14.4967;
    }
Ejemplo n.º 30
0
        public async Task<double> GetElevation(LatLng latLng)
        {
            var key = new LatLng { lat = (int)latLng.lat, lng = (int)latLng.lng };
            if (_initializationTaskPerLatLng.ContainsKey(key) == false)
            {
                return 0;
            }
            await _initializationTaskPerLatLng[key];
            if (_elevationData.ContainsKey(key) == false)
            {
                return 0;
            }
            var array = _elevationData[key];
            var samplesSize = 1.0 / array.GetLength(0);
            var latIndex = (array.GetLength(0) - 1) - (int)((latLng.lat - key.lat) / samplesSize);
            var lngIndex = (int)((latLng.lng - key.lng) / samplesSize);

            return array[latIndex, lngIndex];
        }
Ejemplo n.º 31
0
        //decode polypoints from json object
        List <LatLng> DecodePolylinePoints(string encodedPoints)
        {
            if (encodedPoints == null || encodedPoints == "")
            {
                return(null);
            }
            List <LatLng> poly = new List <LatLng>();

            char[] polylinechars = encodedPoints.ToCharArray();
            int    index         = 0;
            int    currentLat    = 0;
            int    currentLng    = 0;
            int    next5bits;
            int    sum;
            int    shifter;

            try
            {
                while (index < polylinechars.Length)
                {
                    // calculate next latitude
                    sum     = 0;
                    shifter = 0;
                    do
                    {
                        next5bits = (int)polylinechars[index++] - 63;
                        sum      |= (next5bits & 31) << shifter;
                        shifter  += 5;
                    } while (next5bits >= 32 && index < polylinechars.Length);

                    if (index >= polylinechars.Length)
                    {
                        break;
                    }

                    currentLat += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);

                    //calculate next longitude
                    sum     = 0;
                    shifter = 0;
                    do
                    {
                        next5bits = (int)polylinechars[index++] - 63;
                        sum      |= (next5bits & 31) << shifter;
                        shifter  += 5;
                    } while (next5bits >= 32 && index < polylinechars.Length);

                    if (index >= polylinechars.Length && next5bits >= 32)
                    {
                        break;
                    }

                    currentLng += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);

                    double latdouble = Convert.ToDouble(currentLat) / 100000.0;
                    double lngdouble = Convert.ToDouble(currentLng) / 100000.0;
                    LatLng p         = new LatLng(latdouble, lngdouble);
                    poly.Add(p);
                }
            }
            catch (Exception ex)
            {
                Log.Debug("Polyline", ex.ToString());                // logo it
            }
            return(poly);
        }
Ejemplo n.º 32
0
 public LLRect(LatLng ll, LatLng ur)
 {
     _ll = ll;
     _ur = ur;
 }
Ejemplo n.º 33
0
 void Update()
 {
     transformString = myTransform.position.x.ToString() + "," + myTransform.position.y.ToString();
     mLocation       = ConversionTool.LatLongFromUnityVector3D(myTransform.position);
     locString       = mLocation.ToString();
 }
Ejemplo n.º 34
0
 public void OnMapLongClick(LatLng latLng)
 {
     Log.Debug(TAG, "OnMapLongClick: latLng " + " please input latLng");
 }
 public bool Equals(LatLng[] x, LatLng[y])
 {
     return(a.SequenceEquals(y, new MyLatLngComparer(0.001)));
 }
Ejemplo n.º 36
0
 internal void SetPosition(LatLng position)
 {
     Position = position;
 }
 public void OnMapLongClick(LatLng point)
 {
     Map.SendMapLongClicked(point.ToPosition());
 }
Ejemplo n.º 38
0
 public MyItem(double lat, double lng)
 {
     mPosition = new LatLng(lat, lng);
     mTitle    = null;
     mSnippet  = null;
 }
Ejemplo n.º 39
0
 public MyItem(double lat, double lng, string title, string snippet)
 {
     mPosition = new LatLng(lat, lng);
     mTitle    = title;
     mSnippet  = snippet;
 }
Ejemplo n.º 40
0
 public RaycastMapResult(LatLng tileLatLng, Vector2 <double> pointLatLng, Point3D hitPoint)
 {
     this.TileLatLng  = tileLatLng;
     this.PointLatLng = pointLatLng;
     this.HitPoint    = hitPoint;
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Creates an instance from a Protobuf <see cref="LatLng"/> representation.
 /// Later modifications to the Protobuf representation will not affect the returned object.
 /// </summary>
 /// <param name="proto">A Protobuf location representation.</param>
 /// <returns>A new <see cref="GeoPoint"/> value.</returns>
 public static GeoPoint FromProto(LatLng proto)
 {
     GaxPreconditions.CheckNotNull(proto, nameof(proto));
     return(new GeoPoint(proto.Latitude, proto.Longitude));
 }
Ejemplo n.º 42
0
        private SearchResultsPointOfInterest ConvertFromCoordinates(string name, Coordinate coordinates)
        {
            var latLng = new LatLng(coordinates.Y, coordinates.X, coordinates.Z);

            return(CoordinatesToPointOfInterestConverter.Convert(latLng, name));
        }
Ejemplo n.º 43
0
        public void OnMapReady(GoogleMap googleMap)
        {
            // throw new NotImplementedException();
            mMap = googleMap;
            // googleMap.MyLocationEnabled = true;
            LatLng latlng  = new LatLng(46.770439, 23.591423);
            LatLng latlng2 = new LatLng(47, 23.591423);

            CameraUpdate cameraUpdate = CameraUpdateFactory.NewLatLngZoom(latlng, 10); //pune camera pe marker

            googleMap.MoveCamera(cameraUpdate);
            //we create an instance of Marker Options
            //MarkerOptions markerOptions = new MarkerOptions();
            //markerOptions.SetPosition(latlng);
            //markerOptions.SetTitle("My location");
            //markerOptions.SetSnippet("Cluj-Napoca");
            //markerOptions.Draggable(true); //pot misca marker-ul pe harta

            //add another marker


            //  How to design the marker - asa obtin un marcaj albastru
            //  var bmDescriptor = BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueCyan);
            //  markerOptions.InvokeIcon(bmDescriptor);
            //Marker1
            // googleMap.AddMarker(markerOptions); //To add a marker

            foreach (Depozit d in mDepozit)
            {
                MarkerOptions markerOptions = new MarkerOptions();
                //  var random1 = new Random();
                //    var random2 = new Random();
                //    double randomnumber1 = random1.Next();
                //    double randomnumber2 = random2.Next();

                markerOptions.SetPosition(new LatLng(d.Latitudine, d.Longitudine));
                markerOptions.SetTitle(d.Name);
                googleMap.AddMarker(markerOptions); //To add a marker
            }



            ////Optional
            googleMap.UiSettings.ZoomControlsEnabled = true; // +/- zoom in, zoom out
            googleMap.UiSettings.CompassEnabled      = true; //display compass
            // googleMap.MoveCamera(CameraUpdateFactory.ZoomIn());  // afiseaza harta de mai aproape

            googleMap.MapType = GoogleMap.MapTypeHybrid; //satellite map

            googleMap.MyLocationEnabled = true;


            //Optional2

            //LatLng location = new LatLng(50.897778, 3.013333);

            //unghiul de la care putem vedea harta

            //CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
            //builder.Target(new LatLng(16.03, 108));
            //builder.Zoom(18); //zoom level
            //builder.Bearing(155); // The bearing is the compass measurement clockwise from North
            //builder.Tilt(65); //The Tilt property controls the viewing angle and specifies an angle of 25 degrees from the vertical

            //CameraPosition cameraPosition = builder.Build();

            //CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);

            //googleMap.MoveCamera(cameraUpdate);

            // Marker 2
            //googleMap.AddMarker(new MarkerOptions()
            //    .SetPosition(latlng2)
            //    .SetTitle("Marker 2")
            //    .SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueBlue)));

            mMap.MarkerClick += MMap_MarkerClick;

            mMap.MarkerDragEnd += MMap_MarkerDragEnd;
            mMap.SetInfoWindowAdapter(this);
        }
Ejemplo n.º 44
0
 public WeatherStation(string name, double lat, double lng)
 {
     StationName = name;
     latlng      = new LatLng(lat, lng);
 }
Ejemplo n.º 45
0
 public DirectionStep(LatLng start, LatLng end)
 {
     StartLocation = start;
     EndLocation   = end;
 }
Ejemplo n.º 46
0
 public static CLLocationCoordinate2D ToCLCoordinate(this LatLng pos)
 {
     return(new CLLocationCoordinate2D(pos.Lat, pos.Long));
 }
Ejemplo n.º 47
0
 public MarkerOptions(LatLng position)
 {
     Position = position;
 }
Ejemplo n.º 48
0
 public void SetCenter(LatLng point)
 {
     UserCenters[Context.ConnectionId] = point;
 }
 private void AnimateCamera(LatLng point)
 {
     mapboxMap.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(point, DEFAULT_CAMERA_ZOOM), CAMERA_ANIMATION_DURATION);
 }
Ejemplo n.º 50
0
        public void MostrarEstacionamentosNoMap(JArray lista)
        {
            foreach (Marcador marcador in MarcadoresColocados)
            {
                marcador.Marker.Remove();
                foreach (Polyline linha in marcador.Linhas)
                {
                    linha.Remove();
                }
            }
            MarcadoresColocados.Clear();

            foreach (Polyline linha in Polylines)
            {
                linha.Remove();
            }
            Polylines.Clear();
            foreach (var estacionamento in lista)
            {
                var latitude  = (estacionamento["Localizacao"])["Latitude"].Value <double>();
                var longitude = (estacionamento["Localizacao"])["Longitude"].Value <double>();
                var altitude  = (estacionamento["Localizacao"])["Altitude"].Value <float>();



                LatLng latlng = new LatLng(Convert.ToDouble(latitude), Convert.ToDouble(longitude));


                var           imagemMarcador = BitmapDescriptorFactory.FromResource(Resource.Drawable.parking);
                MarkerOptions options        = new MarkerOptions().SetPosition(latlng).SetTitle("").SetIcon(imagemMarcador);

                Marker ponto = Mapa.AddMarker(options);
                this.Markers.Add(ponto);
                Marcador marcador = new Marcador((JObject)estacionamento, ponto);
                MarcadoresColocados.Add(marcador);
                var pontos = (JArray)estacionamento["Pontos"];
                MostrarPontosNoMapa((JObject)estacionamento, pontos);
                if (!string.IsNullOrEmpty(estacionamento["ImagemBase64"].Value <string>()))
                {
                    try
                    {
                        var swbounds = new LatLng(estacionamento["SWBoundImagem"].Value <double>("Latitude"),
                                                  estacionamento["SWBoundImagem"].Value <double>("Longitude"));
                        var nebounds = new LatLng(estacionamento["NEBoundImagem"].Value <double>("Latitude"),
                                                  estacionamento["NEBoundImagem"].Value <double>("Longitude"));


                        LatLngBounds bounds = new LatLngBounds(swbounds, nebounds);



                        byte[] decodedString = Base64.Decode(estacionamento["ImagemBase64"].Value <string>(), Base64Flags.Default);

                        Bitmap decodedByte = BitmapFactory.DecodeByteArray(decodedString, 0, decodedString.Length);

                        var bitmapDescriptor = BitmapDescriptorFactory.FromBitmap(decodedByte);

                        GroundOverlayOptions newarkMap = new GroundOverlayOptions()
                                                         .InvokeImage(bitmapDescriptor).PositionFromBounds(bounds);

                        var overlay = Mapa.AddGroundOverlay(newarkMap);
                        overlay.Clickable        = true;
                        Mapa.GroundOverlayClick += (obj, args) =>
                        {
                            if (args.GroundOverlay.Id == overlay.Id)
                            {
                                if (STATUS_CONTROLE == StatusGUI.Normal)
                                {
                                    this.EstacionamentoSelecionado = (JObject)estacionamento;
                                    if (this.EstacionamentoSelecionadoEvent != null)
                                    {
                                        (this.EstacionamentoSelecionadoEvent).DynamicInvoke(EstacionamentoSelecionado);
                                    }
                                }
                            }
                            else
                            {
                                if ((Action)this.CliqueNoChaoEvent != null)
                                {
                                    CliqueNoChaoEvent.DynamicInvoke(args.GroundOverlay);
                                }
                            }
                        };
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
Ejemplo n.º 51
0
 public LatLng getLatLong()
 {
     return(mLocation = ConversionTool.LatLongFromUnityVector3D(transform.position));
 }
Ejemplo n.º 52
0
        public void OnMapReady(GoogleMap googleMap)
        {
            try
            {
                Map = googleMap;

                var makerOptions = new MarkerOptions();
                makerOptions.SetPosition(new LatLng(Lat, Lng));
                makerOptions.SetTitle(GetText(Resource.String.Lbl_Location));

                Map.AddMarker(makerOptions);
                Map.MapType = GoogleMap.MapTypeNormal;

                if (AppSettings.SetTabDarkTheme)
                {
                    MapStyleOptions style = MapStyleOptions.LoadRawResourceStyle(this, Resource.Raw.map_dark);
                    Map.SetMapStyle(style);
                }

                //Optional
                googleMap.UiSettings.ZoomControlsEnabled = true;
                googleMap.UiSettings.CompassEnabled      = true;

                OnLocationChanged();

                googleMap.MoveCamera(CameraUpdateFactory.ZoomIn());

                LatLng location = new LatLng(Lat, Lng);

                CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
                builder.Target(location);
                builder.Zoom(18);
                builder.Bearing(155);
                builder.Tilt(65);

                CameraPosition cameraPosition = builder.Build();

                CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);
                googleMap.MoveCamera(cameraUpdate);

                googleMap.MapClick += async(sender, e) =>
                {
                    try
                    {
                        LatLng latLng      = e.Point;
                        var    tapTextView = "Tapped: Point=" + e.Point;
                        Console.WriteLine(tapTextView);

                        Lat = latLng.Latitude;
                        Lng = latLng.Longitude;

                        // Creating a marker
                        MarkerOptions markerOptions = new MarkerOptions();

                        // Setting the position for the marker
                        markerOptions.SetPosition(e.Point);

                        var addresses = await ReverseGeocodeCurrentLocation(latLng);

                        if (addresses != null)
                        {
                            DeviceAddress = addresses.GetAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                            //string city = addresses.Locality;
                            //string state = addresses.AdminArea;
                            //string country = addresses.CountryName;
                            //string postalCode = addresses.PostalCode;
                            //string knownName = addresses.FeatureName; // Only if available else return NULL

                            // Setting the title for the marker.
                            // This will be displayed on taping the marker
                            markerOptions.SetTitle(DeviceAddress);
                        }

                        // Clears the previously touched position
                        googleMap.Clear();

                        // Animating to the touched position
                        googleMap.AnimateCamera(CameraUpdateFactory.NewLatLng(e.Point));

                        // Placing a marker on the touched position
                        googleMap.AddMarker(markerOptions);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }
                };

                googleMap.MapLongClick += (sender, e) =>
                {
                    try
                    {
                        var tapTextView = "Long Pressed: Point=" + e.Point;
                        Console.WriteLine(tapTextView);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }
                };

                googleMap.CameraChange += (sender, e) =>
                {
                    try
                    {
                        var cameraTextView = e.Position.ToString();
                        Console.WriteLine(cameraTextView);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }
                };
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 53
0
 public void OnMapLongClick(LatLng point)
 {
     Mvx.Trace(Cirrious.CrossCore.Platform.MvxTraceLevel.Diagnostic, "OnMapLongClick");
     _locationHelper.UpdateMarkers(point, false);
 }
Ejemplo n.º 54
0
 public static Position ConvertToAbstraction(LatLng position)
 {
     return(new Position(position.Latitude,
                         position.Longitude));
 }
Ejemplo n.º 55
0
 public LLRect(LLRect other)
 {
     _ll = other._ll;
     _ur = other._ur;
 }
Ejemplo n.º 56
0
        protected async Task <Card> GetContainerCard(ITurnContext context, string name, LatLng currentCoordinates, List <PointOfInterestModel> pointOfInterestList, IGeoSpatialService service)
        {
            var model = new PointOfInterestModel
            {
                CardTitle = PointOfInterestSharedStrings.CARD_TITLE,
                PointOfInterestImageUrl = await service.GetAllPointOfInterestsImageAsync(currentCoordinates, pointOfInterestList, ImageSize.OverviewWidth, ImageSize.OverviewHeight),
                Provider = new SortedSet <string>
                {
                    service.Provider
                }
            };

            foreach (var poi in pointOfInterestList)
            {
                model.Provider.UnionWith(poi.Provider);
            }

            model.ProviderDisplayText = model.GenerateProviderDisplayText();

            return(new Card
            {
                Name = GetDivergedCardName(context, name),
                Data = model
            });
        }
Ejemplo n.º 57
0
        protected override async Task OnEventAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await _stateAccessor.GetAsync(dc.Context, () => new PointOfInterestSkillState());

            switch (dc.Context.Activity.Name)
            {
            case Events.Location:
            {
                // Test trigger with
                // /event:{ "Name": "Location", "Value": "34.05222222222222,-118.2427777777777" }
                var value = dc.Context.Activity.Value.ToString();

                if (!string.IsNullOrEmpty(value))
                {
                    var coords = value.Split(',');
                    if (coords.Length == 2)
                    {
                        if (double.TryParse(coords[0], out var lat) && double.TryParse(coords[1], out var lng))
                        {
                            var coordinates = new LatLng
                            {
                                Latitude  = lat,
                                Longitude = lng,
                            };
                            state.CurrentCoordinates = coordinates;
                        }
                    }
                }

                break;
            }

            case Events.ActiveLocation:
            {
                var activeLocationName = dc.Context.Activity.Value.ToString();

                // Set ActiveLocation if one w/ matching name is found in FoundLocations
                var activeLocation = state.LastFoundPointOfInterests?.FirstOrDefault(x => x.Name.Contains(activeLocationName, StringComparison.InvariantCultureIgnoreCase));
                if (activeLocation != null)
                {
                    state.Destination = activeLocation;
                    state.LastFoundPointOfInterests = null;
                }

                // Activity should have text to trigger next intent, update Type & Route again
                if (!string.IsNullOrEmpty(dc.Context.Activity.Text))
                {
                    dc.Context.Activity.Type = ActivityTypes.Message;
                    await RouteAsync(dc);
                }

                break;
            }

            case Events.ActiveRoute:
            {
                int.TryParse(dc.Context.Activity.Value.ToString(), out var routeId);
                var activeRoute = state.FoundRoutes[routeId];
                if (activeRoute != null)
                {
                    state.ActiveRoute = activeRoute;
                    state.FoundRoutes = null;
                }

                var replyMessage = _responseManager.GetResponse(RouteResponses.SendingRouteDetails);
                await dc.Context.SendActivityAsync(replyMessage);

                // Send event with active route data
                var replyEvent = dc.Context.Activity.CreateReply();
                replyEvent.Type  = ActivityTypes.Event;
                replyEvent.Name  = "ActiveRoute.Directions";
                replyEvent.Value = state.ActiveRoute.Legs;
                await dc.Context.SendActivityAsync(replyEvent);

                break;
            }
            }
        }
Ejemplo n.º 58
0
 public DirectionStep(decimal startLat, decimal startLng, decimal endLat, decimal endLng)
 {
     StartLocation = new LatLng(startLat, startLng);
     EndLocation   = new LatLng(endLat, endLng);
 }
Ejemplo n.º 59
0
 public void addPoint(LatLng latLng)
 {
     mPoints.Add(mProjection.ToPoint(latLng));
 }
Ejemplo n.º 60
0
 public StyledMarker(LatLng position)
     : base(position)
 {
 }