private void moveCameraToKml(KmlLayer kmlLayer) { if (mIsRestore) { return; } try { //Retrieve the first container in the KML layer KmlContainer container = (KmlContainer)kmlLayer.Containers.Iterator().Next(); //Retrieve a nested container within the first container container = (KmlContainer)container.Containers.Iterator().Next(); //Retrieve the first placemark in the nested container KmlPlacemark placemark = (KmlPlacemark)container.Placemarks.Iterator().Next(); //Retrieve a polygon object in a placemark KmlPolygon polygon = (KmlPolygon)placemark.Geometry; //Create LatLngBounds of the outer coordinates of the polygon LatLngBounds.Builder builder = new LatLngBounds.Builder(); foreach (LatLng latLng in polygon.OuterBoundaryCoordinates) { builder.Include(latLng); } int width = Resources.DisplayMetrics.WidthPixels; int height = Resources.DisplayMetrics.HeightPixels; getMap().MoveCamera(CameraUpdateFactory.NewLatLngBounds(builder.Build(), width, height, 1)); } catch (Java.Lang.Exception e) { // may fail depending on the KML being shown e.PrintStackTrace(); } }
private void AddMultiGeometry(bool sky, KmlPlacemark placemark, float width, Color polyColor, Color lineColor, KmlMultiGeometry geo) { foreach (KmlGeometry childGeo in geo.Children) { if (childGeo is KmlPoint) { KmlPoint point = (KmlPoint)childGeo; placemark.Point = (KmlPoint)childGeo; AddPlacemark(placemark); } else if (childGeo is KmlLineList) { AddLines(sky, childGeo as KmlLineList, width, lineColor, lineColor, false); } else if (childGeo is KmlPolygon) { KmlPolygon child = (KmlPolygon)childGeo; if (child.OuterBoundary != null) { AddLines(sky, child.OuterBoundary as KmlLineList, width, polyColor, lineColor, child.extrude); // to do 3d work and subtract inner rings } } else if (childGeo is KmlMultiGeometry) { AddMultiGeometry(sky, placemark, width, polyColor, lineColor, childGeo as KmlMultiGeometry); } } }
public async Task <List <FoursquareVenue> > ExplorePopular(KmlPlacemark placemark, string language, CancellationToken cancellationToken) { // TODO: Add support of shapes if (placemark.Coordinates.Length == 0 || _kmlCalculator.PlacemarkIsShape(placemark)) { return(null); } var coord = _formatter.FormatCoordinates(null, placemark); var url = $"{VENUES_EXPLORE_URL}ll={coord}&limit={LIMIT_EXPLORE}"; var data = await DownloadString(url, language, cancellationToken); if (data == null) { return(null); } var response = JsonConvert.DeserializeObject <FoursquareResponse <FoursquareExploreResponseBody> >(data); if (!CheckMeta(url, response)) { return(null); } if (response.Response?.Groups.Length == 0) { return(null); } return(response.Response?.Groups[0].Items .Take(LIMIT_EXPLORE) .Select(x => CreateVenueModel(x.Venue, placemark.Coordinates[0])) .ToList()); }
public virtual GeoJsonFeature ConvertPlacemark(KmlPlacemark placemark, IStyleProvider provider) { // Initialize a new feature GeoJsonFeature feature = new GeoJsonFeature(); // Convert the name and description if (placemark.Name.HasValue()) { feature.Properties.Name = placemark.Name; } if (placemark.Description.HasValue()) { feature.Properties.Description = placemark.Description; } switch (placemark.Geometry) { case KmlPoint point: feature.Geometry = Convert(point); break; case KmlLineString lineString: feature.Geometry = Convert(lineString); break; case KmlPolygon polygon: feature.Geometry = Convert(polygon); break; default: throw new KmlException("Geometry type " + placemark.Geometry.GetType() + " not supported"); } if (string.IsNullOrWhiteSpace(placemark.StyleUrl) == false && provider != null) { if (provider.TryGetStyleMapById(placemark.StyleUrl.Substring(1), out KmlStyleMap styleMap)) { if (styleMap.Normal != null && provider.TryGetStyleById(styleMap.Normal.StyleUrl.Substring(1), out KmlStyle style)) { ConvertProperties(style, feature.Properties); } } else { if (provider.TryGetStyleById(placemark.StyleUrl.Substring(1), out KmlStyle style)) { ConvertProperties(style, feature.Properties); } } } return(feature); }
public async Task When_going_next_the_session_is_updated_and_enabled_discovered_places_are_set() { // Arrange var includedVenues = new List <DiscoveredPlace> { new DiscoveredPlace() }; _userSessionMock.SetupGet(x => x.IncludedVenues).Returns(includedVenues); var matchingPlacemark = new KmlPlacemark(); var matchingVenueVm = new DiscoveredVenueViewModel(new DummyVenue()) { Enabled = true }; var exploringVenueVm = new DiscoveredVenueViewModel(new DummyVenue()) { Enabled = true }; var vm = InitializeAndCreateViewModel(); vm.GetUpperGroupForMatchingPlacemarks().Add(new DiscoveredGroupViewModel { AttachedPlacemark = matchingPlacemark, Venues = { new DiscoveredVenueViewModel(new DummyVenue()) { Enabled = false }, matchingVenueVm } }); vm.GetUpperGroupForExploring().Add(new DiscoveredGroupViewModel { Venues = { new DiscoveredVenueViewModel(new DummyVenue()) { Enabled = false }, exploringVenueVm } }); // Act await _presenter.Object.BeforeGoNext(); // Verify Assert.AreEqual(2, includedVenues.Count); Assert.AreEqual(matchingVenueVm.Venue, includedVenues[0].Venue); Assert.AreEqual(matchingPlacemark, includedVenues[0].AttachedToPlacemark); Assert.AreEqual(exploringVenueVm.Venue, includedVenues[1].Venue); Assert.IsNull(includedVenues[1].AttachedToPlacemark); }
void node_NodeSelected(LayerUITreeNode node) { if (node != null) { KmlPlacemark feature = node.Tag as KmlPlacemark; if (feature != null) { feature.Selected = true; layer.DeselectAll(); layer.RetainedVisualsDirty = true; } } }
private string ExtractFoursquareUrlFromDescription(KmlPlacemark placemark) { // Example: https://foursquare.com/v/barcomis-deli/4af818bef964a520f70a22e3 if (string.IsNullOrEmpty(placemark.Description)) { return(null); } var match = Regex.Match(placemark.Description, @"https?://foursquare\.com/v/.+?/.+?/?(?=\s|$)"); if (match.Success) { return(match.Value); } return(null); }
public void When_converting_kmlplacemark_the_description_is_filtered_and_images_are_reordered() { // Arrange var placemark = new KmlPlacemark { Description = "text<br><br><img src='1'/><br>text<img width='200' height='100' src='2'/><br>text http://sample.url/path/page?q=1&w=2 text" }; // Act var result = _factory.Object.Create(placemark, new List <VenueBase>(), "root-folder"); // Verify Assert.AreEqual("text<br>text<br>text <a href='http://sample.url/path/page?q=1&w=2'>http://sample.url/path/page?q=1&w=2</a> text", result.Description); Assert.AreEqual(2, result.Images.Count); Assert.AreEqual("1", result.Images[0]); Assert.AreEqual("2", result.Images[1]); }
void node_NodeActivated(LayerUITreeNode node) { if (node != null && node.Tag is KmlFeature) { KmlFeature feature = (KmlFeature)node.Tag; if (feature.LookAt != null) { if (feature.sky) { Earth3d.MainWindow.GotoTarget(new TourPlace(feature.Name, feature.LookAt.latitude, (feature.LookAt.longitude + 180) / 15, Classification.Unidentified, "", ImageSetType.Sky, .8), false, false, true); } else { GotoLookAt(feature); } } else if (node.Tag is KmlPlacemark) { KmlPlacemark placemark = (KmlPlacemark)node.Tag; if (placemark.geometry != null) { KmlCoordinate point = placemark.geometry.GetCenterPoint(); if (placemark.sky) { Earth3d.MainWindow.GotoTarget(new TourPlace(placemark.Name, point.Lat, (point.Lng + 180) / 15, Classification.Unidentified, "", ImageSetType.Sky, .8), false, false, true); } else { Earth3d.MainWindow.GotoTarget(new TourPlace(placemark.Name, point.Lat, point.Lng, Classification.Unidentified, "", ImageSetType.Earth, .8), false, false, true); } } //if (placemark.geometry is KmlPoint) //{ // KmlPoint point = (KmlPoint)placemark.geometry; // if (placemark.sky) // { // Earth3d.MainWindow.GotoTarget(new TourPlace(placemark.Name, point.latitude, (point.longitude + 180) / 15, Classification.Unidentified, "", ImageSetType.Sky, .8), false, false, true); // } // else // { // Earth3d.MainWindow.GotoTarget(new TourPlace(placemark.Name, point.latitude, point.longitude, Classification.Unidentified, "", ImageSetType.Earth, .8), false, false, true); // } //} } } }
public void When_converting_kmlplacemark_the_values_are_copied_correctly() { // Arrange var placemark = new KmlPlacemark { Name = "placemark-name", Description = "description-1", Coordinates = new [] { new GeoCoordinate(1, 2, 3) }, IconPath = "icon-path" }; // Act var result = _factory.Object.Create(placemark, new List <VenueBase>(), string.Empty); // Verify Assert.AreEqual(placemark.Name, result.Name); Assert.AreEqual(placemark.Description, result.Description); CollectionAssert.AreEqual(placemark.Coordinates, result.Coordinates); Assert.AreEqual(placemark.IconPath, result.IconPath); }
public async Task <FoursquareVenue> LookupMatchingVenue(KmlPlacemark placemark, string language, CancellationToken cancellationToken) { if (placemark.Coordinates.Length == 0 || _kmlCalculator.PlacemarkIsShape(placemark)) { return(null); } FoursquareResponseVenue venue; var venueUrl = ExtractFoursquareUrlFromDescription(placemark); if (string.IsNullOrEmpty(venueUrl)) { var coord = _formatter.FormatCoordinates(null, placemark); var url = $"{VENUES_SEARCH_URL}ll={coord}&query={Uri.EscapeUriString(placemark.Name)}&intent=match&limit={LIMIT_LOOKUP}"; var data = await DownloadString(url, language, cancellationToken); if (data == null) { return(null); } var response = JsonConvert.DeserializeObject <FoursquareResponse <FoursquareSearchResponseBody> >(data); if (!CheckMeta(url, response)) { return(null); } if (response.Response.Venues.Length == 0) { return(null); } venue = response.Response.Venues[0]; venue = await DownloadVenueDetails(venue.Id, language, cancellationToken) ?? venue; } else { var venueId = ExtractVenueIdFromUrl(venueUrl); venue = await DownloadVenueDetails(venueId, language, cancellationToken); placemark.Description = placemark.Description.Replace(venueUrl, string.Empty).Trim(); } return(CreateVenueModel(venue)); }
public KmlPlacemark CreateKmlPlacemark(XElement xplacemark) { var model = new KmlPlacemark { Name = xplacemark.ElementByLocalName("name")?.Value, Description = xplacemark.ElementByLocalName("description")?.Value }; var xstyleurl = xplacemark.ElementByLocalName("styleUrl"); if (xstyleurl != null) { model.IconPath = ExtractIconPath(xstyleurl); } if (xplacemark.ElementByLocalName("Point") != null) { model.Coordinates = ReadCoordinates(xplacemark.ElementByLocalName("Point")); } else if (xplacemark.ElementByLocalName("LineString") != null) { var xlineString = xplacemark.ElementByLocalName("LineString"); // TODO: How to apply? xlineString.ElementByLocalName("tessellate").Value; model.Coordinates = ReadCoordinates(xlineString); } var xextendeddata = xplacemark.ElementByLocalName("ExtendedData"); if (xextendeddata != null) { model.ExtendedData = xextendeddata.ElementsByLocalName("Data") .Select(xdata => new KmlExtendedData { Name = xdata.Attribute("name")?.Value, Value = xdata.ElementByLocalName("value").Value }) .ToArray(); } return(model); }
public MooiPlacemark Create(KmlPlacemark kmlPlacemark, IEnumerable <VenueBase> venues, string reportTempPath) { var descriptionAndImages = ExtractImagesFromContent(kmlPlacemark.Description); var description = FilterContent(descriptionAndImages.filteredContent); var placemark = new MooiPlacemark { Name = kmlPlacemark.Name, Description = description, AttachedVenues = venues?.ToArray(), Coordinates = kmlPlacemark.Coordinates, IconPath = kmlPlacemark.IconPath }; if (descriptionAndImages.images != null) { placemark.Images.AddRange(descriptionAndImages.images); } if (placemark.IconPath != null && !placemark.IconPathIsOnWeb) { placemark.IconPath = Path.Combine(reportTempPath, placemark.IconPath); } placemark.ThumbnailMapFilePath = Path.Combine(reportTempPath, _resourceName.CreateFileNameForPlacemarkThumbnail(placemark)); placemark.IsShape = _kmlCalculator.PlacemarkIsShape(placemark); if (placemark.IsShape) { var distanceInMeters = _kmlCalculator.CalculateRouteDistanceInMeters(placemark); placemark.Distance = _formatter.FormatDistance(distanceInMeters); } ExtendPlacemarkWithVenueData(placemark); return(placemark); }
private void ResetKml() { // Clear any existing layers from the map. MyMapView.Map.OperationalLayers.Clear(); // Reset the most recently placed placemark. _currentPlacemark = null; // Create a new KML document. _kmlDocument = new KmlDocument() { Name = "KML Sample Document" }; // Create a KML dataset using the KML document. _kmlDataset = new KmlDataset(_kmlDocument); // Create the KML layer using the KML dataset. _kmlLayer = new KmlLayer(_kmlDataset); // Add the KML layer to the map. MyMapView.Map.OperationalLayers.Add(_kmlLayer); }
private void MoveCameraToKml(KmlLayer kmlLayer) { //Retrieve the first container in the KML layer KmlContainer container = kmlLayer.Containers.ToEnumerable <KmlContainer>().FirstOrDefault(); //Retrieve a nested container within the first container container = container.Containers.ToEnumerable <KmlContainer>().FirstOrDefault(); //Retrieve the first placemark in the nested container KmlPlacemark placemark = container.Placemarks.ToEnumerable <KmlPlacemark>().FirstOrDefault(); //Retrieve a polygon object in a placemark KmlPolygon polygon = (KmlPolygon)placemark.Geometry; //Create LatLngBounds of the outer coordinates of the polygon LatLngBounds.Builder builder = new LatLngBounds.Builder(); foreach (LatLng latLng in polygon.OuterBoundaryCoordinates) { builder.Include(latLng); } int width = Resources.DisplayMetrics.WidthPixels; int height = Resources.DisplayMetrics.HeightPixels; googleMap.MoveCamera(CameraUpdateFactory.NewLatLngBounds(builder.Build(), width, height, 1)); }
private void AppendExploredPlaces(IEnumerable <DiscoveredPlace> discoveredPlaces, ICollection <KmlFolder> folders) { var exploredPlaces = discoveredPlaces?.Where(x => !x.IsForPlacemark).ToList(); if (exploredPlaces == null || exploredPlaces.Count == 0) { return; } var folder = new KmlFolder(Resources.Kml_Folder_Explored); foreach (var place in exploredPlaces) { var placemark = new KmlPlacemark { Name = place.Venue.Title, Coordinates = new[] { place.Venue.Coordinate }, IconPath = place.Venue.IconUrl?.ToString() }; place.AttachedToPlacemark = placemark; folder.Placemarks.Add(placemark); } folders.Add(folder); }
public async Task <VenueBase> LookupMatchingVenue(KmlPlacemark placemark, string culture, CancellationToken cancellationToken) { try { if (placemark.Coordinates.Length == 0) { return(null); } if (_kmlCalculator.PlacemarkIsShape(placemark)) { return(null); } var coord = _formatter.FormatCoordinates(null, placemark); var url = $"{PLACES_DISCOVER_URL}at={coord}&refinements=true&size=4&q={Uri.EscapeUriString(placemark.Name)}"; // Refer to: https://developer.here.com/rest-apis/documentation/places/topics_api/resource-search.html var jsonValue = await DownloadString(url, culture, cancellationToken); if (jsonValue == null) { return(null); } var response = JsonConvert.DeserializeObject <HereDiscoverSearchResponse>(jsonValue); var place = response.Results.Items.FirstOrDefault(x => x.Distance < LOOKUP_PLACES_WITHIN_DISTANCE_IN_METERS); if (place == null) { return(null); } var discoveredPlace = new HereVenue { Id = place.Id, Title = place.Title, Coordinate = new GeoCoordinate(place.Position[0], place.Position[1]), Address = ReplaceHtmlNewLines(place.Vicinity), IconUrl = new Uri(place.Icon), OpeningHours = ReplaceHtmlNewLines(place.OpeningHours?.Text), Category = place.Category.Title, Websites = new string[0] }; if (place.Href != null) { var extraInfoUrl = place.Href + "&show_content=wikipedia"; var jsonValueExtra = await DownloadString(extraInfoUrl, culture, cancellationToken); if (jsonValueExtra != null) { var extra = JsonConvert.DeserializeObject <HerePlace>(jsonValueExtra); if (extra.Location?.Address != null) { discoveredPlace.Region = string.Join(", ", extra.Location.Address.State, extra.Location.Address.Country); } discoveredPlace.Tags = extra.Tags?.Select(x => x.Title).ToArray(); if (!string.IsNullOrEmpty(extra.View)) { discoveredPlace.Websites = new [] { extra.View }; } if (extra.Contacts?.Phone?.Length > 0) { discoveredPlace.ContactPhone = extra.Contacts.Phone[0].Value; } if (extra.Contacts?.Website?.Length > 0) { discoveredPlace.Websites = discoveredPlace.Websites .Concat(extra.Contacts.Website.Select(x => x.Value)).ToArray(); } var wikipedia = extra.Media?.Editorials?.Items .FirstOrDefault(x => x.Supplier.Id.Equals("wikipedia", StringComparison.OrdinalIgnoreCase)); if (wikipedia != null) { var requestedLanguage = culture.Split('-')[0]; if (wikipedia.Language.Equals(requestedLanguage, StringComparison.OrdinalIgnoreCase) || wikipedia.Language.Equals(ACCEPTABLE_LANGUAGE, StringComparison.OrdinalIgnoreCase)) { discoveredPlace.WikipediaContent = FilterContent(wikipedia.Description); } } } } if (discoveredPlace.IsUseless()) { return(null); } return(discoveredPlace); } catch (Exception e) { _logger.Exception(e); return(null); } }
public KmlPlacemarkNodeViewModel(KmlPlacemark placemark, KmlObjectTreeNodeViewModel parent) { _placemark = placemark; Parent = parent; }
private async void AddGeometry(UIAlertAction obj) { try { // Create variables for the sketch creation mode and color. SketchCreationMode creationMode; // Set the creation mode and UI based on which button called this method. switch (obj.Title) { case "Point": creationMode = SketchCreationMode.Point; _helpLabel.Text = "Tap to add a point."; break; case "Polyline": creationMode = SketchCreationMode.Polyline; _helpLabel.Text = "Tap to add a vertex."; break; case "Polygon": creationMode = SketchCreationMode.Polygon; _helpLabel.Text = "Tap to add a vertex."; break; default: return; } // Get the user-drawn geometry. Geometry geometry = await _myMapView.SketchEditor.StartAsync(creationMode, true); // Project the geometry to WGS84 (WGS84 is required by the KML standard). Geometry projectedGeometry = GeometryEngine.Project(geometry, SpatialReferences.Wgs84); // Create a KmlGeometry using the new geometry. KmlGeometry kmlGeometry = new KmlGeometry(projectedGeometry, KmlAltitudeMode.ClampToGround); // Create a new placemark. _currentPlacemark = new KmlPlacemark(kmlGeometry); // Add the placemark to the KmlDocument. _kmlDocument.ChildNodes.Add(_currentPlacemark); // Enable the style editing UI. ChooseStyle(); } catch (ArgumentException) { ShowMessage("Error", "Unsupported Geometry"); } finally { // Re-add toolbar. _toolbar.Items = new[] { _addButton, new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), _saveButton, _resetButton }; _helpLabel.Text = ""; } }
private async void Draw(object sender, DialogClickEventArgs e) { try { // Hide the base UI and enable the complete button. _buttonLayout.Visibility = ViewStates.Invisible; _completeButton.Visibility = ViewStates.Visible; // Create variables for the sketch creation mode and color. SketchCreationMode creationMode; // Set the creation mode and UI based on which button called this method. switch (e.Which) { case 0: creationMode = SketchCreationMode.Point; _status.Text = "Tap to add a point."; //StyleText.Text = "Select an icon for the placemark."; break; case 1: creationMode = SketchCreationMode.Polyline; _status.Text = "Tap to add a vertex."; //StyleText.Text = "Select a color for the placemark."; break; case 2: creationMode = SketchCreationMode.Polygon; _status.Text = "Tap to add a vertex."; //StyleText.Text = "Select a color for the placemark."; break; default: return; } // Get the user-drawn geometry. Geometry geometry = await _myMapView.SketchEditor.StartAsync(creationMode, true); // Project the geometry to WGS84 (WGS84 is required by the KML standard). Geometry projectedGeometry = GeometryEngine.Project(geometry, SpatialReferences.Wgs84); // Create a KmlGeometry using the new geometry. KmlGeometry kmlGeometry = new KmlGeometry(projectedGeometry, KmlAltitudeMode.ClampToGround); // Create a new placemark. _currentPlacemark = new KmlPlacemark(kmlGeometry); // Add the placemark to the KmlDocument. _kmlDocument.ChildNodes.Add(_currentPlacemark); // Choose whether to open the icon picker or color picker. if (creationMode == SketchCreationMode.Point) { OpenIconDialog(); } else { OpenColorDialog(); } } catch (ArgumentException) { new AlertDialog.Builder(this).SetMessage("Unsupported Geometry").SetTitle("Error").Show(); } finally { // Reset the UI. _buttonLayout.Visibility = ViewStates.Visible; _completeButton.Visibility = ViewStates.Invisible; _status.Text = ""; } }
public void AddPlacemark(KmlPlacemark placemark) { Placemarks.Add(placemark); }
/// <summary> /// 调用此方法 /// </summary> /// <param name="xmlname">xml名称</param> /// <param name="filename">导出文件名</param> /// <param name="lst">数据</param> /// <returns></returns> public static int CreateKml(string xmlname, string filename, List <dataFormat> lst) { List <KmlPlacemark> ls = new List <KmlPlacemark>(); foreach (dataFormat d in lst) { string type = d.type; string coords = d.coordinates.Trim(); string styleUrl = d.styleUrl; string name = d.name; if (string.IsNullOrEmpty(name)) { name = ""; } string description = d.description; if (string.IsNullOrEmpty(description)) { description = ""; } if (type == "point") { if (string.IsNullOrEmpty(styleUrl)) { styleUrl = "#downArrowIcon"; } KmlPoint p = new KmlPoint(coords); KmlPlacemark placemark = new KmlPlacemark(name, description, styleUrl, p, null, null); ls.Add(placemark); } else if (type == "line") { if (string.IsNullOrEmpty(styleUrl)) { styleUrl = "#blue"; } KmlLineString line = new KmlLineString(coords.Split(';').ToList()); KmlPlacemark placemark = new KmlPlacemark(name, description, styleUrl, null, line, null); ls.Add(placemark); } else if (type == "polygon") { if (string.IsNullOrEmpty(styleUrl)) { styleUrl = "#blue"; } KmlPolygon polygon = new KmlPolygon(coords.Split(';').ToList()); KmlPlacemark placemark = new KmlPlacemark(name, description, styleUrl, null, null, polygon); ls.Add(placemark); } } try { KmlDocument document = new KmlDocument(xmlname, filename, ls); Kml kml = new Kml(document); kml.GenerateKmlFile("a.kml"); return(1); } catch (Exception e) { return(0); } }
public GeoJsonFeature ConvertPlacemark(KmlPlacemark placemark) { return(ConvertPlacemark(placemark, default)); }
private async void Edit_Click(object sender, EventArgs e) { try { // Hide the base UI and enable the complete button. ShapeGrid.IsVisible = false; CompleteButton.IsVisible = true; SaveResetGrid.IsEnabled = false; // Create variables for the sketch creation mode and color. SketchCreationMode creationMode; // Set the creation mode and UI based on which button called this method. switch (((Button)sender).Text) { case "Point": creationMode = SketchCreationMode.Point; Status.Text = "Tap to add a point."; break; case "Polyline": creationMode = SketchCreationMode.Polyline; Status.Text = "Tap to add a vertex."; break; case "Polygon": creationMode = SketchCreationMode.Polygon; Status.Text = "Tap to add a vertex."; break; default: return; } // Get the user-drawn geometry. Geometry geometry = await MyMapView.SketchEditor.StartAsync(creationMode, true); // Project the geometry to WGS84 (WGS84 is required by the KML standard). Geometry projectedGeometry = GeometryEngine.Project(geometry, SpatialReferences.Wgs84); // Create a KmlGeometry using the new geometry. KmlGeometry kmlGeometry = new KmlGeometry(projectedGeometry, KmlAltitudeMode.ClampToGround); // Create a new placemark. _currentPlacemark = new KmlPlacemark(kmlGeometry); // Add the placemark to the KmlDocument. _kmlDocument.ChildNodes.Add(_currentPlacemark); // Choose whether to enable the icon picker or color picker. IconPicker.IsVisible = creationMode == SketchCreationMode.Point; ColorPicker.IsVisible = creationMode != SketchCreationMode.Point; // Enable the style editing UI. StyleUI.IsVisible = true; MainUI.IsVisible = false; } catch (ArgumentException) { await Application.Current.MainPage.DisplayAlert("Error", "Unsupported Geometry", "OK"); } finally { // Reset the UI. ShapeGrid.IsVisible = true; CompleteButton.IsVisible = false; Status.Text = "Select the type of feature you would like to add."; // Enable the save and reset buttons. SaveResetGrid.IsEnabled = true; } }
public static void ExportAsKMZ(Session session, string filename) { // Save session info as a KMZ file string kmzFile = filename; string kmlFile = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".kml"; string donutFile = CrashEnvironment.SettingsPath + Path.DirectorySeparatorChar + "donut.png"; using (XmlWriter writer = XmlWriter.Create(kmlFile)) { // Initialize KML document writer.WriteStartDocument(); writer.WriteStartElement("kml"); writer.WriteString("\n"); writer.WriteStartElement("Document"); writer.WriteString("\n"); // Store KML styles KmlStyle s = new KmlStyle(); string[] colors = { "FFF0B414", "FF00D214", "FF78FFF0", "FF1478FF", "FF1400FF" }; // IAEA color codes XmlSerializer serializer = new XmlSerializer(typeof(KmlStyle)); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); for(int i = 0; i < 5; i++) { s.ID = i.ToString(); s.IconStyle.Icon.Href = "files/donut.png"; s.IconStyle.Scale = "1.0"; s.IconStyle.Color = colors[i]; s.LabelStyle.Scale = "1.0"; serializer.Serialize(writer, s, ns); writer.WriteString("\n"); } // Store a KML placemark for each spectrum serializer = new XmlSerializer(typeof(KmlPlacemark)); KmlPlacemark p = new KmlPlacemark(); int styleID = 0; foreach (Spectrum spec in session.Spectrums) { double dose = spec.Doserate / 1000d; // Convert Doserate to micro // Calculate the style id for this sample if(dose <= 1d) styleID = 0; else if (dose <= 5) styleID = 1; else if (dose <= 10) styleID = 2; else if (dose <= 20) styleID = 3; else styleID = 4; p.Name = ""; p.StyleURL = "#" + styleID.ToString(); p.TimeStamp.When = spec.GpsTimeStart.ToString("yyyy-MM-ddTHH:mm:ss"); p.Point.Coordinates = spec.LongitudeStart.ToString(CultureInfo.InvariantCulture) + "," + spec.LatitudeStart.ToString(CultureInfo.InvariantCulture); p.Description = "Value: " + dose.ToString("e", CultureInfo.InvariantCulture) + " μSv/h" + "\nLatitude: " + spec.LatitudeStart.ToString(CultureInfo.InvariantCulture) + "\nLongitude: " + spec.LongitudeStart.ToString(CultureInfo.InvariantCulture) + "\nAltitude: " + spec.AltitudeStart.ToString(CultureInfo.InvariantCulture) + "\nTime: " + spec.GpsTimeStart.ToString("yyyy-MM-dd HH:mm:ss") + " UTC"; serializer.Serialize(writer, p, ns); writer.WriteString("\n"); } // Finish KML document writer.WriteEndElement(); writer.WriteString("\n"); writer.WriteEndElement(); writer.WriteEndDocument(); } // Create a icon file to use for placemarks Bitmap bmpDonut = new Bitmap(crash.Properties.Resources.donut); bmpDonut.Save(donutFile, ImageFormat.Png); // Zip the KML and icon files to create a KMZ file using (ZipFile zip = new ZipFile()) { zip.AddFile(kmlFile, ""); zip.AddFile(donutFile, "files"); zip.Save(kmzFile); } // Delete temporary files if (File.Exists(donutFile)) File.Delete(donutFile); if(File.Exists(kmlFile)) File.Delete(kmlFile); }
public static void ExportAsKMZ(ILog log, Session session, string filename) { // Save session info as a KMZ file string kmzFile = filename; string kmlFile = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".kml"; string donutFile = GAEnvironment.SettingsPath + Path.DirectorySeparatorChar + "donut.png"; using (XmlWriter writer = XmlWriter.Create(kmlFile)) { // Initialize KML document writer.WriteStartDocument(); writer.WriteStartElement("kml"); writer.WriteString("\n"); writer.WriteStartElement("Document"); writer.WriteString("\n"); // Store KML styles KmlStyle s = new KmlStyle(); string[] colors = { "FFF0B414", "FF00D214", "FF78FFF0", "FF1478FF", "FF1400FF" }; // IAEA color codes XmlSerializer serializer = new XmlSerializer(typeof(KmlStyle)); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); for (int i = 0; i < 5; i++) { s.ID = i.ToString(); s.IconStyle.Icon.Href = "files/donut.png"; s.IconStyle.Scale = "1.0"; s.IconStyle.Color = colors[i]; s.LabelStyle.Scale = "1.0"; serializer.Serialize(writer, s, ns); writer.WriteString("\n"); } // Store a KML placemark for each spectrum serializer = new XmlSerializer(typeof(KmlPlacemark)); KmlPlacemark p = new KmlPlacemark(); int styleID = 0; foreach (Spectrum spec in session.Spectrums) { double dose = spec.Doserate / 1000d; // Convert Doserate to micro // Calculate the style id for this sample if (dose <= 1d) { styleID = 0; } else if (dose <= 5) { styleID = 1; } else if (dose <= 10) { styleID = 2; } else if (dose <= 20) { styleID = 3; } else { styleID = 4; } p.Name = ""; p.StyleURL = "#" + styleID.ToString(); p.TimeStamp.When = spec.GpsTime.ToString("yyyy-MM-ddTHH:mm:ss"); p.Point.Coordinates = spec.Longitude.ToString(CultureInfo.InvariantCulture) + "," + spec.Latitude.ToString(CultureInfo.InvariantCulture); p.Description = "Value: " + dose.ToString("e", CultureInfo.InvariantCulture) + " μSv/h" + "\nLatitude: " + spec.Latitude.ToString(CultureInfo.InvariantCulture) + "\nLongitude: " + spec.Longitude.ToString(CultureInfo.InvariantCulture) + "\nAltitude: " + spec.Altitude.ToString(CultureInfo.InvariantCulture) + "\nTime: " + spec.GpsTime.ToString("yyyy-MM-dd HH:mm:ss") + " UTC"; serializer.Serialize(writer, p, ns); writer.WriteString("\n"); } // Finish KML document writer.WriteEndElement(); writer.WriteString("\n"); writer.WriteEndElement(); writer.WriteEndDocument(); } // Create a icon file to use for placemarks Bitmap bmpDonut = new Bitmap(crash.Properties.Resources.donut); bmpDonut.Save(donutFile, ImageFormat.Png); // Zip the KML and icon files to create a KMZ file using (ZipFile zip = new ZipFile()) { zip.AddFile(kmlFile, ""); zip.AddFile(donutFile, "files"); zip.Save(kmzFile); } // Delete temporary files if (File.Exists(donutFile)) { File.Delete(donutFile); } if (File.Exists(kmlFile)) { File.Delete(kmlFile); } }
private async void Edit_Click(object sender, RoutedEventArgs e) { try { // Hide the base UI and enable the complete button. ShapesPanel.Visibility = Visibility.Collapsed; CompleteButton.Visibility = Visibility.Visible; SaveResetGrid.Visibility = Visibility.Collapsed; // Create variables for the sketch creation mode and color. SketchCreationMode creationMode; // Set the creation mode and UI based on which button called this method. switch (((Button)sender).Name) { case nameof(PointButton): creationMode = SketchCreationMode.Point; InstructionsText.Text = "Tap to add a point."; StyleText.Text = "Select an icon for the placemark."; break; case nameof(PolylineButton): creationMode = SketchCreationMode.Polyline; InstructionsText.Text = "Tap to add a vertex."; StyleText.Text = "Select a color for the placemark."; break; case nameof(PolygonButton): creationMode = SketchCreationMode.Polygon; InstructionsText.Text = "Tap to add a vertex."; StyleText.Text = "Select a color for the placemark."; break; default: return; } // Get the user-drawn geometry. Geometry geometry = await MyMapView.SketchEditor.StartAsync(creationMode, true); // Project the geometry to WGS84 (WGS84 is required by the KML standard). Geometry projectedGeometry = GeometryEngine.Project(geometry, SpatialReferences.Wgs84); // Create a KmlGeometry using the new geometry. KmlGeometry kmlGeometry = new KmlGeometry(projectedGeometry, KmlAltitudeMode.ClampToGround); // Create a new placemark. _currentPlacemark = new KmlPlacemark(kmlGeometry); // Add the placemark to the KmlDocument. _kmlDocument.ChildNodes.Add(_currentPlacemark); // Enable the style editing UI. StyleBorder.Visibility = Visibility.Visible; MainUI.Visibility = Visibility.Collapsed; // Display the Icon picker or the color picker based on the creation mode. IconPicker.Visibility = creationMode == SketchCreationMode.Point ? Visibility.Visible : Visibility.Collapsed; ColorSelector.Visibility = creationMode != SketchCreationMode.Point ? Visibility.Visible : Visibility.Collapsed; } catch (ArgumentException) { await new MessageDialog("Unsupported Geometry", "Error").ShowAsync(); } finally { // Reset the UI. ShapesPanel.Visibility = Visibility.Visible; CompleteButton.Visibility = Visibility.Collapsed; InstructionsText.Text = "Select the type of feature you would like to add."; // Enable the save and reset buttons. SaveResetGrid.Visibility = Visibility; } }
private void AddFeatureToDisplay(KmlFeature feature, bool sky) { KmlDocument doc = feature as KmlDocument; if (doc != null) { sky = doc.sky; } if (!(feature is KmlNetworkLink)) { if (feature.visibility == false) { return; } else if (feature is KmlPlacemark) { KmlPlacemark placemark = (KmlPlacemark)feature; KmlStyle style = placemark.Style.GetStyle(placemark.Selected); Color lineColor = Color.White; if (style != null) { lineColor = style.LineStyle.Color; } if (placemark.geometry is KmlPoint) { placemark.Point = (KmlPoint)placemark.geometry; AddPlacemark(placemark); } else if (placemark.geometry is KmlMultiGeometry) { KmlMultiGeometry geo = (KmlMultiGeometry)placemark.geometry; AddMultiGeometry(sky, placemark, (float)style.LineStyle.Width, style.PolyStyle.Color, lineColor, geo); } else if (placemark.geometry is KmlPolygon) { KmlPolygon geo = (KmlPolygon)placemark.geometry; if (geo.OuterBoundary != null) { AddLines(sky, geo.OuterBoundary as KmlLineList, (float)style.LineStyle.Width, style.PolyStyle.Color, lineColor, geo.extrude); // to do 3d work and subtract inner rings } } else if (placemark.geometry is KmlLineString) { KmlLineString geo = (KmlLineString)placemark.geometry; List <Vector3d> vertexList = new List <Vector3d>(); for (int i = 0; i < (geo.PointList.Count); i++) { vertexList.Add(Coordinates.GeoTo3dDouble(geo.PointList[i].Lat, geo.PointList[i].Lng, 1 + (geo.PointList[i].Alt / geo.MeanRadius))); } for (int i = 0; i < (geo.PointList.Count - 1); i++) { if (sky) { lines.AddLine(Coordinates.RADecTo3d(-(180.0 - geo.PointList[i].Lng) / 15 + 12, geo.PointList[i].Lat, 1), Coordinates.RADecTo3d(-(180.0 - geo.PointList[i + 1].Lng) / 15 + 12, geo.PointList[i + 1].Lat, 1), lineColor, new Dates()); } else { lines.AddLine(vertexList[i], vertexList[i + 1], lineColor, new Dates()); } } } } if (feature is KmlGroundOverlay && feature.visibility) { AddGroundOverlay(feature as KmlGroundOverlay); } if (feature is KmlScreenOverlay && feature.visibility) { AddScreenOverlay(feature as KmlScreenOverlay); } } if (feature.visibility) { if (feature is KmlContainer) { KmlContainer container = (KmlContainer)feature; if (container.children != null) { foreach (KmlFeature child in container.children) { AddFeatureToDisplay(child, sky); } } } else { if (feature is KmlNetworkLink) { KmlNetworkLink netLink = (KmlNetworkLink)feature; if (netLink.LinkRoot != null) { foreach (KmlFeature child in netLink.LinkRoot.children) { AddFeatureToDisplay(child, sky); } } } } } }