public PopupUserControl(Feature feature) { InitializeComponent(); string speed = feature.ColumnValues["Speed"]; string name = feature.ColumnValues["VehicleName"]; string latitude = feature.ColumnValues["Latitude"]; string dateTime = feature.ColumnValues["DateTime"]; string longitude = feature.ColumnValues["Longitude"]; txtName.Text = name; double x, y; if (double.TryParse(longitude, out x) && double.TryParse(latitude, out y)) { Proj4Projection proj4 = new Proj4Projection(); proj4.InternalProjectionParametersString = Proj4Projection.GetDecimalDegreesParametersString(); proj4.ExternalProjectionParametersString = Proj4Projection.GetGoogleMapParametersString(); proj4.Open(); Vertex vertex = proj4.ConvertToInternalProjection(x, y); txtLongitude.Text = vertex.X.ToString("N6", CultureInfo.InvariantCulture); txtLatitude.Text = vertex.Y.ToString("N6", CultureInfo.InvariantCulture); proj4.Close(); } else { txtLongitude.Text = longitude; txtLatitude.Text = latitude; } txtSpeed.Text = speed + " mph"; txtTime.Text = dateTime; }
private void UseCurrentExtentClick(object sender, RoutedEventArgs e) { if (Application.Current != null && Application.Current.MainWindow.Tag is Dictionary <string, string> ) { var tmpSettings = Application.Current.MainWindow.Tag as Dictionary <string, string>; RectangleShape currentExtent = GisEditor.ActiveMap.CurrentExtent; Proj4Projection projection = new Proj4Projection(GisEditor.ActiveMap.DisplayProjectionParameters, Proj4Projection.GetWgs84ParametersString()); //projection.Open(); //RectangleShape extent = projection.ConvertToExternalProjection(currentExtent); //projection.Close(); RectangleShape extent = currentExtent; projection.SyncProjectionParametersString(); if (projection.CanProject()) { try { projection.Open(); extent = projection.ConvertToExternalProjection(extent); } finally { projection.Close(); } } tmpSettings["CurrentExtent"] = extent.ToString(); } }
private void FilterEarthquake() { QueryResultItemsDataGridView.Rows.Clear(); Proj4Projection mercatorToWgs84Projection = new Proj4Projection(); mercatorToWgs84Projection.InternalProjectionParametersString = Proj4Projection.GetSphericalMercatorParametersString(); mercatorToWgs84Projection.ExternalProjectionParametersString = Proj4Projection.GetDecimalDegreesParametersString(); mercatorToWgs84Projection.Open(); Collection <EarthquakeItem> items = new Collection <EarthquakeItem>(); for (int i = earthquakeItems.Count - 1; i >= 0; i--) { EarthquakeItem resultItem = earthquakeItems[i]; double latitude, longitude; if (double.TryParse(resultItem.LatitudeCell.Value.ToString(), out latitude) && double.TryParse(resultItem.LongitudeCell.Value.ToString(), out longitude)) { PointShape point = new PointShape(longitude, latitude); point = (PointShape)mercatorToWgs84Projection.ConvertToExternalProjection(point); EarthquakeItem newResultItem = new EarthquakeItem(resultItem.EpicenterFeature); newResultItem.LatitudeCell = new DataGridViewTextBoxCell { Value = point.Y.ToString("f3") }; newResultItem.LongitudeCell = new DataGridViewTextBoxCell { Value = point.X.ToString("f3") }; double year, depth, magnitude; double.TryParse(newResultItem.MagnitudeCell.Value.ToString(), out magnitude); double.TryParse(newResultItem.DepthInKilometerCell.Value.ToString(), out depth); double.TryParse(newResultItem.YearCell.Value.ToString(), out year); if ((magnitude >= MagnitudeSelectionRangeSlider.ValueLeft && magnitude <= MagnitudeSelectionRangeSlider.ValueRight || newResultItem.MagnitudeCell.Value.ToString() == Resources.UnknownString) && (depth <= DepthSelectionRangeSlider.ValueRight && depth >= DepthSelectionRangeSlider.ValueLeft || newResultItem.DepthInKilometerCell.Value.ToString() == Resources.UnknownString) && (year >= DateSelectionRangeSlider.ValueLeft && year <= DateSelectionRangeSlider.ValueRight) || newResultItem.YearCell.Value.ToString() == Resources.UnknownString) { DataGridViewRow newRow = new DataGridViewRow(); newRow.Cells.Add(newResultItem.ImageButtonCell); newRow.Cells.Add(newResultItem.YearCell); newRow.Cells.Add(newResultItem.LongitudeCell); newRow.Cells.Add(newResultItem.LatitudeCell); newRow.Cells.Add(newResultItem.DepthInKilometerCell); newRow.Cells.Add(newResultItem.MagnitudeCell); newRow.Cells.Add(newResultItem.LocationPointCell); QueryResultItemsDataGridView.Rows.Add(newRow); items.Add(newResultItem); } } } mercatorToWgs84Projection.Close(); RefreshMarkersByFeatures(items.Select(f => f.EpicenterFeature)); }
private void ConvertCoordinates() { Proj4Projection proj4 = new Proj4Projection(); proj4.InternalProjectionParametersString = Proj4Projection.GetEpsgParametersString(4326); proj4.ExternalProjectionParametersString = GisEditor.ActiveMap.DisplayProjectionParameters; double x = 0; double y = 0; switch (SelectedCoordinateFormat) { case CoordinateType.DegreesMinutes: case CoordinateType.DegreesMinutesSeconds: if (String.IsNullOrEmpty(LatitudeSeconds)) { LatitudeSeconds = "0"; } if (String.IsNullOrEmpty(LongitudeSeconds)) { LongitudeSeconds = "0"; } double yDegrees, yMinutes, xDegrees, xMinutes, ySeconds, xSeconds; if (double.TryParse(LatitudeDegrees, out yDegrees) && double.TryParse(LatitudeMinutes, out yMinutes) && double.TryParse(LatitudeSeconds, out ySeconds) && double.TryParse(LongitudeDegrees, out xDegrees) && double.TryParse(LongitudeMinutes, out xMinutes) && double.TryParse(LongitudeSeconds, out xSeconds) ) { double actualXMinutes = xMinutes + (xDegrees - (int)xDegrees) * 60; double actualXSeconds = xSeconds + (actualXMinutes - (int)actualXMinutes) * 60; double actualYMinutes = yMinutes + (yDegrees - (int)yDegrees) * 60; double actualYSeconds = ySeconds + (actualYMinutes - (int)actualYMinutes) * 60; x = DecimalDegreesHelper.GetDecimalDegreeFromDegreesMinutesSeconds((int)xDegrees, (int)actualXMinutes, actualXSeconds); y = DecimalDegreesHelper.GetDecimalDegreeFromDegreesMinutesSeconds((int)yDegrees, (int)actualYMinutes, actualYSeconds); x = LongitudeType == "E" ? x : -x; y = LatitudeType == "N" ? y : -y; } else { throw new Exception(errorMessage); } break; case CoordinateType.XY: case CoordinateType.DecimalDegrees: default: if (!(double.TryParse(Longitude, out x) && double.TryParse(Latitude, out y))) { throw new Exception(errorMessage); } break; } proj4.Open(); ResultVertex = SelectedCoordinateFormat == CoordinateType.XY ? new Vertex(x, y) : proj4.ConvertToExternalProjection(x, y); proj4.Close(); }
private void RefreshQueryResultList() { TextView title = FindViewById <TextView>(Resource.Id.queryResultTitleTextView); ListView view = FindViewById <ListView>(Resource.Id.resultListView); EarthquakeListAdapter adapter = view.Adapter == null ? new EarthquakeListAdapter(this) : (EarthquakeListAdapter)view.Adapter; adapter.Data.Clear(); Proj4Projection mercatorToWgs84Projection = Global.GetWgs84ToMercatorProjection(); mercatorToWgs84Projection.Open(); try { Global.FilterSelectedEarthquakeFeatures(Global.GetBackupQueriedFeatures()); LayerOverlay highLightOverlay = Global.MapView.Overlays[Global.HighlightOverlayKey] as LayerOverlay; InMemoryFeatureLayer selectMarkerLayer = highLightOverlay.Layers[Global.SelectMarkerLayerKey] as InMemoryFeatureLayer; foreach (var feature in selectMarkerLayer.InternalFeatures) { double longitude = 0, latitude = 0; if (double.TryParse(feature.ColumnValues["LONGITUDE"], out longitude) && double.TryParse(feature.ColumnValues["LATITIUDE"], out latitude)) { PointShape point = new PointShape(longitude, latitude); point = (PointShape)mercatorToWgs84Projection.ConvertToInternalProjection(point); longitude = point.X; latitude = point.Y; } double year, depth, magnitude; double.TryParse(feature.ColumnValues["MAGNITUDE"], out magnitude); double.TryParse(feature.ColumnValues["DEPTH_KM"], out depth); double.TryParse(feature.ColumnValues["YEAR"], out year); Dictionary <String, Object> result = new Dictionary <string, object>(); result["yearValue"] = year != -9999 ? year.ToString(CultureInfo.InvariantCulture) : UnknownString; result["longitudeValue"] = longitude.ToString("f2", CultureInfo.InvariantCulture); result["latitudeValue"] = latitude.ToString("f2", CultureInfo.InvariantCulture); result["depthValue"] = depth != -9999 ? depth.ToString(CultureInfo.InvariantCulture) : UnknownString; result["magnitudeValue"] = magnitude != -9999 ? magnitude.ToString(CultureInfo.InvariantCulture) : UnknownString; result["locationValue"] = feature.ColumnValues["LOCATION"]; adapter.Data.Add(result); } view.Adapter = adapter; title.Text = String.Format("Query Result (Find {0} results)", adapter.Data.Count); } finally { mercatorToWgs84Projection.Close(); } }
private static Vertex ConvertCurrentCoordinatesTo4326Coordinates(double lon, double lat, string displayProj4) { Proj4Projection proj4Projection = new Proj4Projection(); proj4Projection.InternalProjectionParametersString = displayProj4; proj4Projection.ExternalProjectionParametersString = Proj4Projection.GetEpsgParametersString(4326); proj4Projection.Open(); Vertex vertex = proj4Projection.ConvertToExternalProjection(lon, lat); proj4Projection.Close(); return(vertex); }
protected override Vertex[] ConvertToExternalProjectionCore(double[] x, double[] y) { //First, converts to the external projection Vertex[] projVertices = new Vertex[x.Length]; proj4.Open(); for (int i = 0; i < projVertices.Length; i++) { projVertices[i] = proj4.ConvertToExternalProjection(x[i], y[i]); } proj4.Close(); Vertex[] rotateVertices = new Vertex[x.Length]; //Second, rotates based on angle and pivot point. for (int i = 0; i < rotateVertices.Length; i++) { rotateVertices[i] = RotateVertex(projVertices[i].X, projVertices[i].Y, angle); } return(rotateVertices); }
private static RectangleShape GetDrawingExtentInWgs84() { Proj4Projection proj = new Proj4Projection(); proj.InternalProjectionParametersString = GisEditor.ActiveMap.DisplayProjectionParameters; proj.ExternalProjectionParametersString = Proj4Projection.GetDecimalDegreesParametersString(); proj.Open(); RectangleShape drawingExtent = proj.ConvertToExternalProjection(GisEditor.ActiveMap.CurrentExtent); proj.Close(); return(drawingExtent); }
private static Feature ConvertToWgs84Projection(Feature feature) { Feature featureInDecimalDegree = feature; Proj4Projection projection = new Proj4Projection(); projection.InternalProjectionParametersString = Proj4Projection.GetEpsgParametersString(4326); projection.ExternalProjectionParametersString = GisEditor.ActiveMap.DisplayProjectionParameters; projection.SyncProjectionParametersString(); if (projection.CanProject()) { projection.Open(); featureInDecimalDegree = projection.ConvertToInternalProjection(featureInDecimalDegree); projection.Close(); } return(featureInDecimalDegree); }
private static Feature ConvertToWgs84Projection(Feature feature, string displayProjectionParameters) { Feature featureInDecimalDegree = feature; Proj4Projection projection = new Proj4Projection(); projection.InternalProjectionParametersString = Proj4Projection.GetEpsgParametersString(4326); projection.ExternalProjectionParametersString = displayProjectionParameters; SyncProjectionParametersString(projection); if (CanProject(projection)) { projection.Open(); featureInDecimalDegree = projection.ConvertToInternalProjection(featureInDecimalDegree); projection.Close(); } return(featureInDecimalDegree); }
private static Feature GetProjectedFeature(Feature feature) { Proj4Projection projection = new Proj4Projection(); projection.InternalProjectionParametersString = Proj4Projection.GetEpsgParametersString(4326); projection.ExternalProjectionParametersString = GisEditor.ActiveMap.DisplayProjectionParameters; projection.SyncProjectionParametersString(); Feature tmpFeature = new Feature(feature.GetWellKnownBinary()); if (projection.CanProject()) { projection.Open(); tmpFeature = projection.ConvertToInternalProjection(tmpFeature); projection.Close(); } return(tmpFeature); }
private void winformsMap1_MouseMove(object sender, MouseEventArgs e) { //Displays the X and Y in screen coordinates. statusStrip1.Items["toolStripStatusLabelScreen"].Text = "X:" + e.X + " Y:" + e.Y; //Gets the PointShape in world coordinates from screen coordinates. PointShape pointShape = ExtentHelper.ToWorldCoordinate(winformsMap1.CurrentExtent, new ScreenPointF(e.X, e.Y), winformsMap1.Width, winformsMap1.Height); Proj4Projection proj4 = new Proj4Projection(); proj4.InternalProjectionParametersString = Proj4Projection.GetGoogleMapParametersString(); proj4.ExternalProjectionParametersString = Proj4Projection.GetEpsgParametersString(4326); proj4.Open(); PointShape projPointShape = (PointShape)proj4.ConvertToExternalProjection(pointShape); proj4.Close(); //Displays world coordinates in decimal degrees from the OSM Mercator projection statusStrip1.Items["toolStripStatusLabelWorld"].Text = "(world) X:" + Math.Round(projPointShape.X, 4) + " Y:" + Math.Round(projPointShape.Y, 4); }
private void FilterEarthquake() { FilteredQueryResults.Clear(); Proj4Projection mercatorToWgs84Projection = new Proj4Projection(); mercatorToWgs84Projection.InternalProjectionParametersString = Proj4Projection.GetSphericalMercatorParametersString(); mercatorToWgs84Projection.ExternalProjectionParametersString = Proj4Projection.GetDecimalDegreesParametersString(); mercatorToWgs84Projection.Open(); for (int i = queryResults.Count - 1; i >= 0; i--) { EarthquakeViewModel resultItem = queryResults[i]; double latitude, longitude; if (double.TryParse(resultItem.Latitude, out latitude) && double.TryParse(resultItem.Longitude, out longitude)) { PointShape point = new PointShape(longitude, latitude); point = (PointShape)mercatorToWgs84Projection.ConvertToExternalProjection(point); EarthquakeViewModel newResultItem = new EarthquakeViewModel(resultItem.EpicenterFeature); newResultItem.Latitude = point.Y.ToString("f3", CultureInfo.InvariantCulture); newResultItem.Longitude = point.X.ToString("f3", CultureInfo.InvariantCulture); double year, depth, magnitude; double.TryParse(newResultItem.Magnitude, out magnitude); double.TryParse(newResultItem.DepthInKilometer, out depth); double.TryParse(newResultItem.Year, out year); if ((magnitude >= queryFilter.StartMagnitudeRange && magnitude <= queryFilter.EndMagnitudeRange || newResultItem.Magnitude == Resources.UnknownString) && (depth <= queryFilter.EndDepthRange && depth >= queryFilter.StartDepthRange || newResultItem.DepthInKilometer == Resources.UnknownString) && (year >= queryFilter.StartYearRange && year <= queryFilter.EndYearRange) || newResultItem.Year == Resources.UnknownString) { FilteredQueryResults.Add(newResultItem); } } } mercatorToWgs84Projection.Close(); mapModel.RefreshMarkersByFeatures(FilteredQueryResults.Select(f => f.EpicenterFeature)); }
public static string GetFormattedWorldCoordinate(this GisEditorWpfMap map, ScreenPointF screenPoint, MouseCoordinateType mouseCoordinateType) { PointShape lonlat = map.ToWorldCoordinate(screenPoint.X, screenPoint.Y); double xInCurrentProjection = lonlat.X; double yInCurrentProjection = lonlat.Y; string projectionFullName = "Unknown"; if (map.DisplayProjectionParameters != null) { string projectionShortName = map.DisplayProjectionParameters.Split(' ')[0].Replace("+proj=", string.Empty); projectionFullName = projectionAbbreviations[projectionShortName]; } GeographyUnit mapUnit = GisEditorWpfMap.GetGeographyUnit(map.DisplayProjectionParameters); if (projectionFullName == "Unknown" && mapUnit == GeographyUnit.Unknown) { return(String.Format("X:{0}, Y:{1}", lonlat.X.ToString("N4", CultureInfo.InvariantCulture), lonlat.Y.ToString("N4", CultureInfo.InvariantCulture))); } else { if (mapUnit != GeographyUnit.DecimalDegree) { try { Proj4Projection proj = new Proj4Projection(); proj.InternalProjectionParametersString = map.DisplayProjectionParameters; proj.ExternalProjectionParametersString = Proj4Projection.GetDecimalDegreesParametersString(); proj.Open(); lonlat = proj.ConvertToExternalProjection(lonlat) as PointShape; proj.Close(); } catch { lonlat = new PointShape(); } } return(GetMouseCoordinates(lonlat.X, lonlat.Y, mouseCoordinateType, map.DisplayProjectionParameters, xInCurrentProjection, yInCurrentProjection)); } }
private void RefreshQueryResultData() { if (queryResultView.Hidden) { queryResultView.AnimatedShow(); } DataTableSource earthquakeSource; if (tbvQueryResult.Source == null) { earthquakeSource = new DataTableSource(); earthquakeSource.RowClick = EarthquakeRowClicked; } else { earthquakeSource = (DataTableSource)tbvQueryResult.Source; } earthquakeSource.Sections.Clear(); Proj4Projection mercatorToWgs84Projection = Global.GetWgs84ToMercatorProjection(); mercatorToWgs84Projection.Open(); try { Global.FilterSelectedEarthquakeFeatures(); InMemoryFeatureLayer selectMarkerLayer = (InMemoryFeatureLayer)Global.HighLightOverlay.Layers["SelectMarkerLayer"]; GeoCollection <Feature> selectFeatures = selectMarkerLayer.InternalFeatures; SectionModel detailSection = new SectionModel("Queried Count: " + selectFeatures.Count); detailSection.HeaderHeight = 50; foreach (var feature in selectFeatures) { double longitude, latitude = 0; if (double.TryParse(feature.ColumnValues["LONGITUDE"], out longitude) && double.TryParse(feature.ColumnValues["LATITIUDE"], out latitude)) { PointShape point = new PointShape(longitude, latitude); point = (PointShape)mercatorToWgs84Projection.ConvertToInternalProjection(point); longitude = point.X; latitude = point.Y; } double year, depth, magnitude; double.TryParse(feature.ColumnValues["MAGNITUDE"], out magnitude); double.TryParse(feature.ColumnValues["DEPTH_KM"], out depth); double.TryParse(feature.ColumnValues["YEAR"], out year); EarthquakeRow result = new EarthquakeRow(); result.YearValue = year != -9999 ? year.ToString(CultureInfo.InvariantCulture) : "Unknown"; result.LocationValue = longitude.ToString("f2", CultureInfo.InvariantCulture); result.LatitudeValue = latitude.ToString("f2", CultureInfo.InvariantCulture); result.DepthValue = depth != -9999 ? depth.ToString(CultureInfo.InvariantCulture) : "Unknown"; result.MagnitudeValue = magnitude != -9999 ? magnitude.ToString(CultureInfo.InvariantCulture) : "Unknown"; result.LocationValue = feature.ColumnValues["LOCATION"]; detailSection.Rows.Add(new RowModel(result.ToString(), new UIImageView(UIImage.FromBundle("location")))); } earthquakeSource.Sections.Add(detailSection); tbvQueryResult.Source = earthquakeSource; tbvQueryResult.ReloadData(); } finally { mercatorToWgs84Projection.Close(); } }
private void TestForm_Load(object sender, EventArgs e) { winformsMap1.MapUnit = GeographyUnit.Meter; winformsMap1.BackgroundOverlay.BackgroundBrush = new GeoSolidBrush(GeoColor.FromArgb(255, 198, 255, 255)); GoogleMapsOverlay googleOverlay = new GoogleMapsOverlay(); //(@"Insert your key here!", @"C:\GoogleCache"); googleOverlay.MapType = GoogleMapsMapType.Terrain; winformsMap1.Overlays.Add(googleOverlay); // This sets the zoom levels to map to Googles. We next make sure we snap to the zoomlevels winformsMap1.ZoomLevelSet = new GoogleMapsZoomLevelSet(); InMemoryFeatureLayer pointLayer = new InMemoryFeatureLayer(); pointLayer.Open(); pointLayer.Columns.Add(new FeatureSourceColumn("Text")); pointLayer.Close(); //Sets the projection parameters to go from Geodetic (EPSG 4326) or decimal degrees to Google Map projection (Spherical Mercator). Proj4Projection proj4 = new Proj4Projection(); proj4.InternalProjectionParametersString = Proj4Projection.GetEpsgParametersString(4326); proj4.ExternalProjectionParametersString = Proj4Projection.GetGoogleMapParametersString(); //Applies the projection to the InMemoryFeatureLayer so that the point in decimal degrees (Longitude/Latitude) can be //match the projection of Google Map. pointLayer.FeatureSource.Projection = proj4; //Values in Longitude and Latitude. double Longitude = -95.2809; double Latitude = 38.9543; //Creates the feature made of a PointShape with the Longitude and Latitude values. Feature GPSFeature = new Feature(new PointShape(Longitude, Latitude)); //Format the Longitude and Latitude into a nice string as Degrees Minutes and Seconds string LongLat = DecimalDegreesHelper.GetDegreesMinutesSecondsStringFromDecimalDegreePoint(GPSFeature); //Sets the InMemoryFeatureLayer to have it displayed with Square symbol and with text. GPSFeature.ColumnValues.Add("Text", LongLat); pointLayer.InternalFeatures.Add(GPSFeature); pointLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimplePointStyle(PointSymbolType.Square, GeoColor.StandardColors.Red, GeoColor.StandardColors.Black, 2, 12); pointLayer.ZoomLevelSet.ZoomLevel01.DefaultTextStyle = TextStyles.CreateSimpleTextStyle("Text", "Arial", 12, DrawingFontStyles.Bold, GeoColor.StandardColors.Black, GeoColor.StandardColors.White, 3, -10, 10); pointLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; LayerOverlay pointOverlay = new LayerOverlay(); pointOverlay.Layers.Add("PointLayer", pointLayer); winformsMap1.Overlays.Add("PointOverlay", pointOverlay); //Sets the extend of the map based on the GPS point. proj4.Open(); Vertex projVertex = proj4.ConvertToExternalProjection(Longitude, Latitude); proj4.Close(); double extendWidth = 2300; double extendHeight = 1200; winformsMap1.CurrentExtent = new RectangleShape((projVertex.X - extendWidth), (projVertex.Y + extendHeight), (projVertex.X + extendWidth), (projVertex.Y - extendHeight)); winformsMap1.Refresh(); }
private void btnSearch_Click(object sender, RoutedEventArgs e) { string address = txtAddressName.Text.Trim(); if (string.IsNullOrEmpty(address)) { MessageBox.Show("Please enter address."); return; } // Initialize geocoder Geocoder streetGeocoder = new Geocoder(); streetGeocoder.MatchingPlugIns.Add(new StreetMatchingPlugin(@"..\..\Data\GeoCoderIndex", MatchMode.ExactMatch)); try { streetGeocoder.Open(); // Get the ShapeFileFeatureLayer which includes the street data. FeatureLayer roadFeatureLayer = ((LayerOverlay)Map1.Overlays[roadOverlayName]).Layers[0] as FeatureLayer; roadFeatureLayer.Open(); // Get the marker overlay to display the searched results. SimpleMarkerOverlay markerOverlay = Map1.Overlays[markerOverlayName] as SimpleMarkerOverlay; markerOverlay.Markers.Clear(); Collection <SearchResult> searchedResult = new Collection <SearchResult>(); // Geocoder the address input, such as "6701 PECAN". Collection <GeocoderMatch> matchedRoads = streetGeocoder.Match(address); Proj4Projection projection = new Proj4Projection(); projection.InternalProjectionParametersString = Proj4Projection.GetWgs84ParametersString(); projection.ExternalProjectionParametersString = "+proj=lcc +lat_1=32.1333333333333 +lat_2=33.9666666666667 +lat_0=31.6666666666667 +lon_0=-98.5 +x_0=600000 +y_0=2000000 +ellps=GRS80 +datum=NAD83 +units=us-ft +no_defs"; projection.Open(); foreach (GeocoderMatch geocoderMatched in matchedRoads) { // Display the searched result as marker. BaseShape streetCenter = new Feature(geocoderMatched.NameValuePairs["CentroidPoint"]).GetShape(); PointShape center = projection.ConvertToExternalProjection(streetCenter) as PointShape; markerOverlay.Markers.Add(new Marker(center) { ImageSource = new BitmapImage(new Uri("/Resources/AQUA.png", UriKind.RelativeOrAbsolute)), Width = 20, Height = 34, YOffset = -17, ToolTip = geocoderMatched.NameValuePairs["Street"] }); // Get the feature id of the street where the searched result locates. string featureId = geocoderMatched.NameValuePairs["UID"]; // Get the street where the searched result locates. Feature feature = roadFeatureLayer.QueryTools.GetFeatureById(featureId, new[] { "ROAD_NAME" }); searchedResult.Add(GetSearchResult(feature, geocoderMatched)); } projection.Close(); roadFeatureLayer.Close(); searchResults.ItemsSource = searchedResult; // Set the highlight layer into the current extent. InMemoryFeatureLayer highlightRoadLayer = ((LayerOverlay)Map1.Overlays[roadHighlightOverlayName]).Layers[0] as InMemoryFeatureLayer; if (highlightRoadLayer.InternalFeatures.Count > 0) { Map1.CurrentExtent = highlightRoadLayer.GetBoundingBox(); Map1.ZoomOut(); } Map1.Refresh(); } finally { streetGeocoder.Close(); } }
public void RegisterMessenger(BookmarkRibbonGroupViewModel viewModel) { Messenger.Default.Register <string>(this, viewModel, msg => { switch (msg) { case BookmarkRibbonGroupViewModel.AddBookmarkMessage: if (!viewModel.Bookmarks.ContainsKey(GisEditor.ActiveMap.Name)) { viewModel.Bookmarks.Add(GisEditor.ActiveMap.Name, new ObservableCollection <BookmarkViewModel>()); } var displayBookmarks = viewModel.DisaplayBookmarks; BookmarkNamePromptWindow bookmarkNameWindow = new BookmarkNamePromptWindow(null, viewModel.Bookmarks[GisEditor.ActiveMap.Name].Select(tmpBookmark => tmpBookmark.Name)); if (bookmarkNameWindow.ShowDialog().GetValueOrDefault()) { BookmarkViewModel bookmark = new BookmarkViewModel(); bookmark.Name = bookmarkNameWindow.BookmarkName; bookmark.IsGlobal = bookmarkNameWindow.IsGlobal; if (bookmark.IsGlobal) { bookmark.ImageUri = "/GisEditorPluginCore;component/Images/bookmark_global.png"; } else { bookmark.ImageUri = "/GisEditorPluginCore;component/Images/bookmark project.png"; } bookmark.Center = GisEditor.ActiveMap.CurrentExtent.GetCenterPoint(); bookmark.Scale = GisEditor.ActiveMap.CurrentScale; bookmark.InternalProj4Projection = GisEditor.ActiveMap.DisplayProjectionParameters; displayBookmarks.Add(bookmark); if (bookmark.IsGlobal) { viewModel.SaveGlobalBookmarks(); } viewModel.SyncBookmarkMenuItems(); } break; case BookmarkRibbonGroupViewModel.OpenBookmarkMessage: var dockWindow = GisEditor.DockWindowManager.DockWindows.FirstOrDefault(d => d.Title.Equals("BookmarksPluginTitle", StringComparison.Ordinal)); if (dockWindow != null) { dockWindow.Show(DockWindowPosition.Right); } break; case BookmarkRibbonGroupViewModel.DeleteBookmarkMessage: if (viewModel.DisaplayBookmarks != null && viewModel.DisaplayBookmarks.Contains(viewModel.SelectedBookmark)) { viewModel.DisaplayBookmarks.Remove(viewModel.SelectedBookmark); viewModel.SyncBookmarkMenuItems(); } break; case BookmarkRibbonGroupViewModel.GotoBookmarkMessage: if (viewModel.DisaplayBookmarks != null && viewModel.DisaplayBookmarks.Contains(viewModel.SelectedBookmark)) { var targetCenter = viewModel.SelectedBookmark.Center; if (!viewModel.SelectedBookmark.InternalProj4Projection.Equals(GisEditor.ActiveMap.DisplayProjectionParameters)) { Proj4Projection projection = new Proj4Projection(); projection.InternalProjectionParametersString = viewModel.SelectedBookmark.InternalProj4Projection; projection.ExternalProjectionParametersString = GisEditor.ActiveMap.DisplayProjectionParameters; projection.Open(); targetCenter = (PointShape)projection.ConvertToExternalProjection(targetCenter); projection.Close(); } GisEditor.ActiveMap.ZoomTo(targetCenter, viewModel.SelectedBookmark.Scale); } break; } }); }
public static void SaveToKmlMenuitemClick(object sender, RoutedEventArgs e) { Collection <Feature> features = GisEditor.SelectionManager.GetSelectedFeatures(); if (features.All(i => !GisEditor.ActiveMap.CurrentExtent.Intersects(i))) { ShowOptionsIfNoSelectedFeatureInCurrentExtent(features); return; } Collection <FeatureLayer> featureLayers = new Collection <FeatureLayer>(); var featuresGroup = GisEditor.SelectionManager.GetSelectionOverlay().GetSelectedFeaturesGroup(); Proj4Projection tempProjection = new Proj4Projection(); tempProjection.InternalProjectionParametersString = GisEditor.ActiveMap.DisplayProjectionParameters; tempProjection.ExternalProjectionParametersString = Proj4Projection.GetWgs84ParametersString(); tempProjection.SyncProjectionParametersString(); try { tempProjection.Open(); foreach (var item in featuresGroup) { if (item.Value.Count > 0) { InMemoryFeatureLayer layer = new InMemoryFeatureLayer(); ZoomLevelSet sourceZoomLevelSet = item.Key.ZoomLevelSet; try { string tempXml = GisEditor.Serializer.Serialize(sourceZoomLevelSet); ZoomLevelSet targetZoomLevelSet = (ZoomLevelSet)GisEditor.Serializer.Deserialize(tempXml); layer.ZoomLevelSet = targetZoomLevelSet; layer.Open(); layer.EditTools.BeginTransaction(); foreach (var feature in item.Value) { Feature newFeature = tempProjection.ConvertToExternalProjection(feature); layer.EditTools.Add(newFeature); } layer.EditTools.CommitTransaction(); if (!item.Key.IsOpen) { item.Key.Open(); } foreach (var column in item.Key.QueryTools.GetColumns()) { layer.Columns.Add(column); } featureLayers.Add(layer); } catch (Exception ex) { GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex)); } } } } catch (Exception ex) { GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex)); } finally { tempProjection.Close(); } KmlParameter parameter = GetKmlParameter(); //System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog(); //sf.Filter = "(*.kml)|*.kml|(*.kmz)|*.kmz"; //sf.FileName = string.Format("{0}-{1}", "KmlExportFile", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")); if (parameter != null) { if (Path.GetExtension(parameter.PathFileName).ToUpper() == ".KML") { SaveKmlData(featureLayers, parameter); } else if (Path.GetExtension(parameter.PathFileName).ToUpper() == ".KMZ") { StringBuilder builder = GetKmlDataBuilder(featureLayers); PlatformGeoCanvas canvas = new PlatformGeoCanvas(); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)GisEditor.ActiveMap.ActualWidth, (int)GisEditor.ActiveMap.ActualHeight); RectangleShape drawingExtent = GetDrawingExtentInWgs84(); canvas.BeginDrawing(bitmap, drawingExtent, GeographyUnit.DecimalDegree); featureLayers.ForEach(l => { Proj4ProjectionInfo projectionInfo = l.GetProj4ProjectionInfo(); if (projectionInfo != null) { projectionInfo.ExternalProjectionParametersString = Proj4Projection.GetWgs84ParametersString(); projectionInfo.SyncProjectionParametersString(); } l.Open(); l.Draw(canvas, new Collection <SimpleCandidate>()); }); canvas.EndDrawing(); string kmlPath = Path.ChangeExtension(parameter.PathFileName, ".kml"); string pngPath = Path.ChangeExtension(parameter.PathFileName, ".png"); if (File.Exists(kmlPath)) { File.Delete(kmlPath); } if (File.Exists(pngPath)) { File.Delete(pngPath); } MemoryStream stream = new MemoryStream(); bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); byte[] bitmapArray = stream.GetBuffer(); File.WriteAllText(kmlPath, builder.ToString()); File.WriteAllBytes(pngPath, bitmapArray); var zipFileAdapter = ZipFileAdapterManager.CreateInstance(); zipFileAdapter.AddFileToZipFile(kmlPath, ""); zipFileAdapter.AddFileToZipFile(pngPath, ""); zipFileAdapter.Save(Path.ChangeExtension(parameter.PathFileName, ".kmz")); File.Delete(kmlPath); File.Delete(pngPath); } string mentionedString = GisEditor.LanguageManager.GetStringResource("KMLFileHasSavedSuccessText"); if (MessageBox.Show(mentionedString, "Open in Google Earth", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { string proInstalledPath = GetGoogleEarthProInstalledPath(); OpenKmlFileWithGoogleEarth(string.IsNullOrEmpty(proInstalledPath) ? GetGoogleEarthInstalledPath() : proInstalledPath , parameter.PathFileName); } } }
protected override void RunCore() { //if (FeatureLayer != null && FeatureLayer.FeatureSource.LinkSources.Count > 0) //{ // hasLinkSource = true; //} if (FeaturesForExporting.Count == 0 && FeatureIdsForExporting.Count > 0 && FeatureLayer != null) { FeatureLayer.CloseAll(); FeatureLayer.SafeProcess(() => { //if (FeatureLayer.FeatureSource.LinkSources.Count > 0) //{ // featuresForExporting = FeatureLayer.FeatureSource.GetFeaturesByIds(FeatureIdsForExporting, FeatureLayer.GetDistinctColumnNames()); // hasLinkSource = true; //} //else //{ // featuresForExporting = FeatureLayer.QueryTools.GetFeaturesByIds(FeatureIdsForExporting, FeatureLayer.GetDistinctColumnNames()); // hasLinkSource = false; //} featuresForExporting = FeatureLayer.QueryTools.GetFeaturesByIds(FeatureIdsForExporting, FeatureLayer.GetDistinctColumnNames()); hasLinkSource = false; }); } Proj4Projection proj4 = new Proj4Projection(); proj4.InternalProjectionParametersString = InternalPrj4Projection; proj4.ExternalProjectionParametersString = Proj4Projection.ConvertPrjToProj4(ProjectionWkt); proj4.SyncProjectionParametersString(); proj4.Open(); Collection <Feature> exportFeatures = FeaturesForExporting; if (proj4.CanProject()) { exportFeatures = new Collection <Feature>(); foreach (var item in FeaturesForExporting) { Feature newFeature = item; newFeature = proj4.ConvertToExternalProjection(item); exportFeatures.Add(newFeature); } } proj4.Close(); #region This is a trick to fix that fox pro columns cannot write to dbf, convert all fox pro columns to character column type. if (hasLinkSource) { Collection <string> dateTimeColumns = new Collection <string>(); Collection <string> dateColumns = new Collection <string>(); foreach (var item in FeatureSourceColumns) { string doubleInBinary = DbfColumnType.DoubleInBinary.ToString(); string integerInBinary = DbfColumnType.IntegerInBinary.ToString(); string dateTime = DbfColumnType.DateTime.ToString(); string date = DbfColumnType.Date.ToString(); string logical = DbfColumnType.Logical.ToString(); if (item.TypeName.Equals(doubleInBinary, StringComparison.OrdinalIgnoreCase) || item.TypeName.Equals(integerInBinary, StringComparison.OrdinalIgnoreCase) || item.TypeName.Equals(dateTime, StringComparison.OrdinalIgnoreCase) || item.TypeName.Equals(date, StringComparison.OrdinalIgnoreCase) || item.TypeName.Equals(logical, StringComparison.OrdinalIgnoreCase)) { item.TypeName = DbfColumnType.Character.ToString(); } } Dictionary <string, int> longLengthColumnNames = new Dictionary <string, int>(); //foreach (var feature in exportFeatures) //{ // // Fill link column values into column values. // foreach (var item in feature.LinkColumnValues) // { // string key = item.Key; // string value = string.Join("\r\n", item.Value.Select(v => v.Value)); // feature.ColumnValues[key] = value; // longLengthColumnNames[key] = value.Length; // } //} // fix too long column value foreach (var key in longLengthColumnNames.Keys) { FeatureSourceColumn column = FeatureSourceColumns.FirstOrDefault(f => f.ColumnName.Equals(key, StringComparison.OrdinalIgnoreCase)); if (column != null) { int length = longLengthColumnNames[key]; if (length > column.MaxLength) { column.MaxLength = length; } } } } #endregion This is a trick to fix that fox pro columns cannot write to dbf. if (NeedConvertMemoToCharacter) { foreach (var feature in exportFeatures) { foreach (var item in FeatureSourceColumns) { if (item.TypeName.Equals(DbfColumnType.Memo.ToString(), StringComparison.OrdinalIgnoreCase)) { item.TypeName = DbfColumnType.Character.ToString(); item.MaxLength = 254; } else if (item.TypeName.Equals(DbfColumnType.Character.ToString(), StringComparison.OrdinalIgnoreCase) && item.MaxLength > 254) { item.MaxLength = 254; } //if (feature.ColumnValues.ContainsKey(item.ColumnName) && feature.ColumnValues[item.ColumnName].Length > 254) //{ // feature.ColumnValues[item.ColumnName] = feature.ColumnValues[item.ColumnName].Substring(0, 254); //} } } } var info = new FileExportInfo(exportFeatures, FeatureSourceColumns, OutputPathFileName, ProjectionWkt); foreach (var item in CostomizedColumnNames) { info.CostomizedColumnNames.Add(item.Key, item.Value); } Export(info); }
private static void SetExtent(GisEditorWpfMap map) { if (map.Overlays.Count == 1) { RectangleShape extent = map.Overlays[0].GetBoundingBox(); if (map.Overlays[0] is WorldMapKitMapOverlay) { extent = new RectangleShape(-152.941811131969, 73.3011270968869, -63.395569383504, 4.88674180823698); } if (extent == null) { extent = new RectangleShape(-130, 90, 130, -90); var proj = new Proj4Projection(); proj.InternalProjectionParametersString = Proj4Projection.GetEpsgParametersString(4326); proj.ExternalProjectionParametersString = map.DisplayProjectionParameters; proj.SyncProjectionParametersString(); proj.Open(); extent = proj.ConvertToExternalProjection(extent); } map.CurrentExtent = extent; } if (map.Overlays.Count <= 1 && System.Windows.Application.Current != null && System.Windows.Application.Current.MainWindow.Tag is Dictionary <string, string> ) { var tmpSettings = System.Windows.Application.Current.MainWindow.Tag as Dictionary <string, string>; var currentExtentStrings = tmpSettings["CurrentExtent"].Split(','); if (currentExtentStrings.Length > 3) { double minX = double.NaN; double maxY = double.NaN; double maxX = double.NaN; double minY = double.NaN; if (double.TryParse(currentExtentStrings[0], out minX) && double.TryParse(currentExtentStrings[1], out maxY) && double.TryParse(currentExtentStrings[2], out maxX) && double.TryParse(currentExtentStrings[3], out minY)) { RectangleShape extent = new RectangleShape(minX, maxY, maxX, minY); Proj4Projection projection = new Proj4Projection(Proj4Projection.GetWgs84ParametersString(), map.DisplayProjectionParameters); projection.SyncProjectionParametersString(); if (projection.CanProject()) { try { projection.Open(); extent = projection.ConvertToExternalProjection(extent); } catch (Exception ex) { GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex)); } finally { projection.Close(); } } map.CurrentExtent = extent; } } } }