private async void Location_SuggestionsRequested(SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args) { if (geocodeTcs != null) { geocodeTcs.Cancel(); } geocodeTcs = new CancellationTokenSource(); if (args.QueryText.Length > 3) { try { var geo = new OnlineLocatorTask(serviceUri); var deferral = args.Request.GetDeferral(); var result = await geo.FindAsync(new OnlineLocatorFindParameters(args.QueryText) { MaxLocations = 5, OutSpatialReference = SpatialReferences.Wgs84 }, geocodeTcs.Token); if (result.Any() && !args.Request.IsCanceled) { var imageSource = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/blank.png")); foreach (var item in result) { args.Request.SearchSuggestionCollection.AppendResultSuggestion(item.Name, "", item.Extent.ToJson(), imageSource, ""); } } deferral.Complete(); } catch { } } }
private async void Location_QuerySubmitted(SearchBox sender, SearchBoxQuerySubmittedEventArgs args) { if (geocodeTcs != null) { geocodeTcs.Cancel(); } geocodeTcs = new CancellationTokenSource(); try { var geo = new OnlineLocatorTask(serviceUri); var result = await geo.FindAsync(new OnlineLocatorFindParameters(args.QueryText) { MaxLocations = 5, OutSpatialReference = SpatialReferences.Wgs84 }, geocodeTcs.Token); if (result.Any()) { Location.QueryText = result.First().Name; if (LocationPicked != null) { LocationPicked(this, result.First().Extent); } } } catch { } }
public MainWindow() { InitializeComponent(); //住所検索用のジオコーディング タスクを初期化 onlineLocatorTask = new OnlineLocatorTask(new Uri(WORLD_GEOCODE_SERVICE_URL)); }
private static OnlineLocatorTask GetLocation() { var uri = new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"); var token = String.Empty; var locator = new OnlineLocatorTask(uri, token); return locator; }
private async void Location_SuggestionsRequested(SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args) { if (geocodeTcs != null) geocodeTcs.Cancel(); geocodeTcs = new CancellationTokenSource(); if (args.QueryText.Length > 3) { try { var geo = new OnlineLocatorTask(serviceUri); var deferral = args.Request.GetDeferral(); var result = await geo.FindAsync(new OnlineLocatorFindParameters(args.QueryText) { MaxLocations = 5, OutSpatialReference = SpatialReferences.Wgs84 }, geocodeTcs.Token); if (result.Any() && !args.Request.IsCanceled) { var imageSource = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/blank.png")); foreach (var item in result) args.Request.SearchSuggestionCollection.AppendResultSuggestion(item.Name, "", item.Extent.ToJson(), imageSource, ""); } deferral.Complete(); } catch { } } }
private OnlineLocatorTask onlineLocatorTask; //住所検索用のジオコーディング タスク /// <summary> /// コンストラクタ /// </summary> public MainWindow() { InitializeComponent(); //住所検索用のジオコーディング タスクを初期化 onlineLocatorTask = new OnlineLocatorTask(new Uri(WORLD_GEOCODE_SERVICE_URL)); }
private async void SingleLineAddressButton_Click(object sender, RoutedEventArgs e) { try { OnlineLocatorTask locatorTask = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer", UriKind.Absolute), ""); var text = SingleLineAddressText.Text; if (string.IsNullOrEmpty(text)) return; _locatorFindParameter = new OnlineLocatorFindParameters(text) { Text = text, Location = mapView1.Extent.GetCenter(), Distance = mapView1.Extent.Width / 2, MaxLocations = 5, OutSpatialReference = mapView1.SpatialReference, OutFields = new List<string>() { "*" } }; CancellationToken cancellationToken = new CancellationTokenSource().Token; var results = await locatorTask.FindAsync(_locatorFindParameter, cancellationToken); if (_candidateGraphicsLayer.Graphics != null && _candidateGraphicsLayer.Graphics.Count > 0) _candidateGraphicsLayer.Graphics.Clear(); if (results != null) { foreach (var result in results) { var geom = result.Feature.Geometry; Graphic graphic = new Graphic() { Geometry = geom }; graphic.Attributes.Add("Name", result.Feature.Attributes["Match_addr"]); if (geom.GeometryType == GeometryType.Point) { var pt = geom as MapPoint; string latlon = String.Format("{0}, {1}", pt.X, pt.Y); graphic.Attributes.Add("LatLon", latlon); } if (geom.SpatialReference == null) { geom.SpatialReference = mapView1.SpatialReference; } _candidateGraphicsLayer.Graphics.Add(graphic); } } } catch (Exception) { throw; } }
public GeocodeAddress() { InitializeComponent(); _addressOverlay = MyMapView.GraphicsOverlays[0]; _locatorTask = new OnlineLocatorTask(new Uri(OnlineLocatorUrl)); _locatorTask.AutoNormalize = true; SetSimpleRendererSymbols(); }
public async Task<MapPoint> Geocode(string address, CancellationToken cancellationToken) { OnlineLocatorTask locator = new OnlineLocatorTask(new Uri(locatorService), null); var result = await locator.FindAsync(new OnlineLocatorFindParameters(address), cancellationToken).ConfigureAwait(false); if (result != null && result.Count > 0) return result.First().Feature.Geometry as MapPoint; return null; }
private async void mapView_Tapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e) { var hitGraphic = await _locationGraphicsLayer.HitTestAsync(mapView1, e.Position); if (hitGraphic != null) { if (maptip.Visibility == Windows.UI.Xaml.Visibility.Collapsed) { MapTipGraphic = hitGraphic; RenderMapTip(); } else { maptip.Visibility = Windows.UI.Xaml.Visibility.Collapsed; maptip.DataContext = null; MapTipGraphic = null; } } else { maptip.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var mp = mapView1.ScreenToLocation(e.Position); Graphic g = new Graphic() { Geometry = mp }; var layer = mapView1.Map.Layers.OfType<GraphicsLayer>().First(); layer.Graphics.Add(g); var token = ""; var locatorTask = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer", UriKind.Absolute), token); try { var result = await locatorTask.ReverseGeocodeAsync(mp, 30, mapView1.SpatialReference, CancellationToken.None); Graphic graphic = new Graphic() { Geometry = mp }; string latlon = String.Format("{0}, {1}", result.Location.X, result.Location.Y); string address1 = result.AddressFields["Address"].ToString(); string address2 = String.Format("{0}, {1} {2}", result.AddressFields["City"], result.AddressFields["Region"], result.AddressFields["Postal"]); graphic.Attributes.Add("LatLon", latlon); graphic.Attributes.Add("Address1", address1); graphic.Attributes.Add("Address2", address2); _locationGraphicsLayer.Graphics.Add(graphic); MapTipGraphic = graphic; RenderMapTip(); } catch (Exception) { } } }
public GeocodeAddress() { InitializeComponent(); MyMapView.Map.InitialViewpoint = new Viewpoint(new Envelope(-74.2311, 4.47791, -73.964, 4.8648, SpatialReference.Create(4326))); _addressOverlay = MyMapView.GraphicsOverlays[0]; _locatorTask = new OnlineLocatorTask(new Uri(OnlineLocatorUrl)); _locatorTask.AutoNormalize = true; SetSimpleRendererSymbols(); }
private FeatureLayer buildingLayer; //物件フィーチャレイヤ /// <summary> /// コンストラクタ /// </summary> public MainWindow() { InitializeComponent(); //ArcGIS Online への認証方法の指定 IdentityManager.Current.ChallengeHandler = new ChallengeHandler(PortalSecurity.Challenge); //住所検索用のジオコーディング タスクを初期化 onlineLocatorTask = new OnlineLocatorTask(new Uri(WORLD_GEOCODE_SERVICE_URL)); }
/// <summary>Construct find place sample control</summary> public FindPlace() { InitializeComponent(); mapView.Map.InitialExtent = new Envelope(-13043302, 3856091, -13040394, 3857406, SpatialReferences.WebMercator); _locatorTask = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer")); _locatorTask.AutoNormalize = true; var task = SetSimpleRendererSymbols(); }
public async Task <MapPoint> Geocode(string address, CancellationToken cancellationToken) { OnlineLocatorTask locator = new OnlineLocatorTask(new Uri(locatorService), null); var result = await locator.FindAsync(new OnlineLocatorFindParameters(address), cancellationToken).ConfigureAwait(false); if (result != null && result.Count > 0) { return(result.First().Feature.Geometry as MapPoint); } return(null); }
public NetworkingToolController(MapView mapView, MapViewModel mapViewModel) { this._mapView = mapView; _networkingToolView = new NetworkingToolView { PlacementTarget = mapView, ViewModel = { mapView = mapView } }; var owner = Window.GetWindow(mapView); if (owner != null) { owner.LocationChanged += (sender, e) => { _networkingToolView.HorizontalOffset += 1; _networkingToolView.HorizontalOffset -= 1; }; } // hook mapview events mapView.MapViewTapped += mapView_MapViewTapped; mapView.MapViewDoubleTapped += mapView_MapViewDoubleTapped; // hook listDirections _networkingToolView.listDirections.SelectionChanged += listDirections_SelectionChanged; // hook view resources _directionPointSymbol = _networkingToolView.LayoutRoot.Resources["directionPointSymbol"] as Symbol; mapView.GraphicsOverlays.Add(new GraphicsOverlay { ID = "RoutesOverlay", Renderer = _networkingToolView.LayoutRoot.Resources["routesRenderer"] as Renderer }); mapView.GraphicsOverlays.Add(new GraphicsOverlay { ID = "StopsOverlay" }); mapView.GraphicsOverlays.Add(new GraphicsOverlay { ID = "DirectionsOverlay", Renderer = _networkingToolView.LayoutRoot.Resources["directionsRenderer"] as Renderer, SelectionColor = Colors.Red }); _stopsOverlay = mapView.GraphicsOverlays["StopsOverlay"]; _routesOverlay = mapView.GraphicsOverlays["RoutesOverlay"]; _directionsOverlay = mapView.GraphicsOverlays["DirectionsOverlay"]; _routeTask = new OnlineRouteTask(new Uri(OnlineRoutingService)); Mediator.Register(Constants.ACTION_ROUTING_GET_DIRECTIONS, DoGetDirections); _locatorTask = new OnlineLocatorTask(new Uri(OnlineLocatorUrl)) { AutoNormalize = true }; }
private Graphic serviceAreaGraphic; //到達圏グラフィック /// <summary> /// コンストラクタ /// </summary> public MainWindow() { InitializeComponent(); //ArcGIS Online への認証方法の指定 IdentityManager.Current.ChallengeHandler = new ChallengeHandler(PortalSecurity.Challenge); //住所検索用のジオコーディング タスクを初期化 onlineLocatorTask = new OnlineLocatorTask(new Uri(WORLD_GEOCODE_SERVICE_URL)); //到達圏解析用のジオプロセシング タスクを初期化 serviceAreaGp = new Geoprocessor(new Uri(SERVICE_AREA_GP_URL)); }
/// <summary>Construct find place sample control</summary> public FindPlace() { InitializeComponent(); _addressOverlay = MyMapView.GraphicsOverlays[0]; ; _locatorTask = new OnlineLocatorTask(new Uri(OnlineLocatorUrl)); _locatorTask.AutoNormalize = true; listResults.ItemsSource = _addressOverlay.Graphics; SetSimpleRendererSymbols(); }
/// <summary>Construct find place sample control</summary> public FindPlace() { InitializeComponent(); _addressOverlay = MyMapView.GraphicsOverlays[0];; _locatorTask = new OnlineLocatorTask(new Uri(OnlineLocatorUrl)); _locatorTask.AutoNormalize = true; listResults.ItemsSource = _addressOverlay.Graphics; SetSimpleRendererSymbols(); }
private async Task <Graphic> FindAddress(string address) { var uri = new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"); var locator = new OnlineLocatorTask(uri, string.Empty); var findParams = new OnlineLocatorFindParameters(address); findParams.OutSpatialReference = new SpatialReference(4326); Graphic matchGraphic = new Graphic(); var results = await locator.FindAsync(findParams, new System.Threading.CancellationToken()); if (results.Count > 0) { matchGraphic.Geometry = results[0].Feature.Geometry; matchGraphic.Attributes.Add("Name", address); } return(matchGraphic); }
private ObservableCollection <Feature> selectedFeatures; //選択されているフィーチャのコレクション /// <summary> /// コンストラクタ /// </summary> public MainWindow() { InitializeComponent(); //ArcGIS Online への認証方法の指定 IdentityManager.Current.ChallengeHandler = new ChallengeHandler(PortalSecurity.Challenge); //住所検索用のジオコーディング タスクを初期化 onlineLocatorTask = new OnlineLocatorTask(new Uri(WORLD_GEOCODE_SERVICE_URL)); //到達圏解析用のジオプロセシング タスクを初期化 serviceAreaGp = new Geoprocessor(new Uri(SERVICE_AREA_GP_URL)); //選択されているフィーチャのコレクションを初期化し選択リストのデータコンテキストに設定 selectedFeatures = new ObservableCollection <Feature>(); selectedBuildingListBox.DataContext = selectedFeatures; }
public MapPage() { this.InitializeComponent(); MyMapView.LocationDisplay.LocationProvider = new SystemLocationProvider(); MyMapView.LocationDisplay.LocationProvider.StartAsync(); HardwareButtons.BackPressed += HardwareButtons_BackPressed; MyMapView.Loaded += MyMapView_Loaded; _locatorTask = new OnlineLocatorTask(new Uri(OnlineLocatorUrl)); _locatorTask.AutoNormalize = true; _directionPointSymbol = LayoutRoot.Resources["directionPointSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol; _stopsOverlay = MyMapView.GraphicsOverlays["StopsOverlay"]; _routesOverlay = MyMapView.GraphicsOverlays["RoutesOverlay"]; _directionsOverlay = MyMapView.GraphicsOverlays["DirectionsOverlay"]; _myLocationOverlay = MyMapView.GraphicsOverlays["LocationOverlay"]; _routeTask = new OnlineRouteTask(new Uri(OnlineRoutingService)); _campos = new Dictionary <String, String>(); if (PortalSearch.GetSelectedItem().Map.Layers.Count() > 0) { foreach (Layer i in PortalSearch.GetSelectedItem().Map.Layers) { try { if (!((FeatureLayer)i).FeatureTable.IsReadOnly && ((FeatureLayer)i).FeatureTable.GeometryType == GeometryType.Point) { _layer = i as FeatureLayer; _table = (ArcGISFeatureTable)_layer.FeatureTable; MenuFlyoutAddButton.IsEnabled = true; } } catch { } } } }
private async void Location_QuerySubmitted(SearchBox sender, SearchBoxQuerySubmittedEventArgs args) { if (geocodeTcs != null) geocodeTcs.Cancel(); geocodeTcs = new CancellationTokenSource(); try { var geo = new OnlineLocatorTask(serviceUri); var result = await geo.FindAsync(new OnlineLocatorFindParameters(args.QueryText) { MaxLocations = 5, OutSpatialReference = SpatialReferences.Wgs84 }, geocodeTcs.Token); if (result.Any()) { Location.QueryText = result.First().Name; if (LocationPicked != null) LocationPicked(this, result.First().Extent); } } catch { } }
//------------------------------------------------------------------------------------ private async void doworkAsync(string txt) { try { LocatorTask myloc = new OnlineLocatorTask(new Uri("http://rsweb.eastus.cloudapp.azure.com/arcgis/rest/services/Egypt_Gaz_suggestions/GeocodeServer")); Dictionary <string, string> address = new Dictionary <string, string>(); address.Add("Address", txt); IList <LocatorGeocodeResult> candidateResults = await myloc.GeocodeAsync(address, new List <string> { "Address" }, new SpatialReference(102100), CancellationToken.None); foreach (var item in candidateResults) { TotalResults.Add(item); // Results.Text += item.Address + "\n"; } // Results.Text += "\n # End Of Text \n"; } catch (Exception ex) { Results.Text += "\n # " + ex.Message + "\n"; } }
private async System.Threading.Tasks.Task<Graphic> FindAddress(string address) { var uri = new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"); var locator = new OnlineLocatorTask(uri, string.Empty); var findParams = new OnlineLocatorFindParameters(address); findParams.OutSpatialReference = new SpatialReference(4326); Graphic matchGraphic = null; var results = await locator.FindAsync(findParams, new System.Threading.CancellationToken()); if (results.Count > 0) { var firstMatch = results[0].Feature; var matchLocation = firstMatch.Geometry as MapPoint; matchGraphic = new Graphic(); matchGraphic.Geometry = matchLocation; matchGraphic.Attributes.Add("Name", address); } return matchGraphic; }
private async void FindAddressButton_Click(object sender, RoutedEventArgs e) { try { progress.Visibility = Visibility.Visible; //The constructor takes two arguments: the URI for the geocode service and a token (required for secured services). var uri = new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"); var token = String.Empty; var locator = new OnlineLocatorTask(uri, token); // OnlineLocatorFindParameters object, which holds all relevant information for the address search. //var findParams = new OnlineLocatorFindParameters(AddressTextBox.Text); var findParams = new OnlineLocatorFindParameters(InputAddress.Text + " " + City.Text + " " + State.Text + " " + Zip.Text); findParams.OutSpatialReference = MyMapView.SpatialReference; findParams.SourceCountry = "US"; // var results = await locator.FindAsync(findParams, new System.Threading.CancellationToken()); if (results.Count > 0) { var firstMatch = results[0].Feature; var matchLocation = firstMatch.Geometry as MapPoint; //Add a point graphic at the address location var matchSym = new PictureMarkerSymbol(); var pictureUri = new Uri("http://static.arcgis.com/images/Symbols/Basic/GreenStickpin.png"); await matchSym.SetSourceAsync(pictureUri); var matchGraphic = new Graphic(matchLocation, matchSym); // Get a reference to the graphic layer you defined for the map, and add the new graphic. var graphicsLayer = MyMap.Layers["MyGraphics"] as GraphicsLayer; if (graphicsLayer.Graphics.Contains(oldGraphic)) { graphicsLayer.Graphics.Remove(oldGraphic); } graphicsLayer.Graphics.Add(matchGraphic); oldGraphic = matchGraphic; // _graphicsOverlay.Graphics.Add(matchGraphic); txtResult.Visibility = System.Windows.Visibility.Visible; txtResult.Text = ("Address Found: " + matchLocation.X +", " + matchLocation.Y); // zooms into pin point graphic: //The Envelope is created by subtracting 1000 meters from the location's //minimum X and Y values and adding 1000 meters to the maximum X and Y values. var matchExtent = new Envelope(matchLocation.X, matchLocation.Y, matchLocation.X, matchLocation.Y); await MyMapView.SetViewAsync(matchExtent); } else { MessageBox.Show("Unable to find address. "); return; } } catch (Exception ex) { MessageBox.Show("Unable to find address. ", ""); } }
private async void AddGraphics(string p_parameters, string p_textLabel ) { // check if there is a previous pinpoint //The constructor takes two arguments: the URI for the geocode service and a token (required for secured services). var uri = new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"); var token = String.Empty; var locator = new OnlineLocatorTask(uri, token); // OnlineLocatorFindParameters object, which holds all relevant information for the address search. var findParams = new OnlineLocatorFindParameters(p_parameters); findParams.OutSpatialReference = MyMapView.SpatialReference; findParams.SourceCountry = "US"; // var results = await locator.FindAsync(findParams, new System.Threading.CancellationToken()); if (results.Count > 0) { var firstMatch = results[0].Feature; var matchLocation = firstMatch.Geometry as MapPoint; //Add a point graphic at the address location var matchSym = new PictureMarkerSymbol(); var pictureUri = new Uri("http://static.arcgis.com/images/Symbols/Animated/EnlargeGradientSymbol.png"); await matchSym.SetSourceAsync(pictureUri); var matchGraphic = new Graphic(matchLocation, matchSym); // Get a reference to the graphic layer you defined for the map, and add the new graphic. var graphicsLayer = MyMap.Layers["MyGraphics"] as GraphicsLayer; graphicsLayer.Graphics.Add(matchGraphic); // create a text symbol: define color, font, size, and text for the label var textSym = new Esri.ArcGISRuntime.Symbology.TextSymbol(); textSym.Color = Colors.DarkRed; textSym.Font = new Esri.ArcGISRuntime.Symbology.SymbolFont("Arial", 12); textSym.BackgroundColor = Colors.White; textSym.Text = p_textLabel; //textSym.Angle = -60; // create a graphic for the text (apply TextSymbol) var textGraphic = new Esri.ArcGISRuntime.Layers.Graphic(matchLocation, textSym); graphicsLayer.Graphics.Add(textGraphic); } }
public NetworkingToolController(MapView mapView, MapViewModel mapViewModel) { this._mapView = mapView; _networkingToolView = new NetworkingToolView { ViewModel = { mapView = mapView } }; var owner = Window.GetWindow(mapView); if (owner != null) { _networkingToolView.Owner = owner; } // hook mapview events mapView.MapViewTapped += mapView_MapViewTapped; mapView.MapViewDoubleTapped += mapView_MapViewDoubleTapped; // hook listDirections _networkingToolView.listDirections.SelectionChanged += listDirections_SelectionChanged; // hook view resources _directionPointSymbol = _networkingToolView.LayoutRoot.Resources["directionPointSymbol"] as Symbol; mapView.GraphicsOverlays.Add(new GraphicsOverlay { ID = "RoutesOverlay", Renderer = _networkingToolView.LayoutRoot.Resources["routesRenderer"] as Renderer }); mapView.GraphicsOverlays.Add(new GraphicsOverlay { ID = "StopsOverlay" }); mapView.GraphicsOverlays.Add(new GraphicsOverlay { ID = "DirectionsOverlay", Renderer = _networkingToolView.LayoutRoot.Resources["directionsRenderer"] as Renderer, SelectionColor = Colors.Red }); _stopsOverlay = mapView.GraphicsOverlays["StopsOverlay"]; _routesOverlay = mapView.GraphicsOverlays["RoutesOverlay"]; _directionsOverlay = mapView.GraphicsOverlays["DirectionsOverlay"]; _routeTask = new OnlineRouteTask(new Uri(OnlineRoutingService)); Mediator.Register(Constants.ACTION_ROUTING_GET_DIRECTIONS, DoGetDirections); _locatorTask = new OnlineLocatorTask(new Uri(OnlineLocatorUrl)) { AutoNormalize = true }; }
public async Task Query(string text) { try { if (Controller == null) { return; } IsLoadingSearchResults = true; text = text.Trim(); if (_searchCancellationTokenSource != null) { if (_currentSearchString != null && _currentSearchString == text) { return; } _searchCancellationTokenSource.Cancel(); } _searchCancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _searchCancellationTokenSource.Token; Envelope boundingBox = Controller.Extent; if (string.IsNullOrWhiteSpace(text)) { return; } if (_currentSearchString != null && _currentSearchString != text) { if (!cancellationToken.IsCancellationRequested) { _searchCancellationTokenSource.Cancel(); } } _searchResultLayer.Graphics.Clear(); var geo = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer", UriKind.Absolute), ""); boundingBox = boundingBox.Expand(1.2); _currentSearchString = text; SearchResultStatus = string.Format("Searching for '{0}'...", text.Trim()); var result = await geo.FindAsync(new OnlineLocatorFindParameters(text) { MaxLocations = 50, OutSpatialReference = WebMapVM.SpatialReference, Location = (MapPoint)GeometryEngine.NormalizeCentralMeridianOfGeometry(boundingBox.GetCenter()), Distance = GetDistance(boundingBox), }, cancellationToken); int retries = 3; while (result.Count == 0 && --retries > 0) //Try again with larger and larger extent { if (cancellationToken.IsCancellationRequested) { return; } boundingBox = boundingBox.Expand(2); result = await geo.FindAsync(new OnlineLocatorFindParameters(text) { MaxLocations = 50, OutSpatialReference = WebMapVM.SpatialReference, Location = (MapPoint)GeometryEngine.NormalizeCentralMeridianOfGeometry(boundingBox.GetCenter()), Distance = GetDistance(boundingBox), }, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return; } if (result.Count == 0) //Try again unbounded { result = await geo.FindAsync(new OnlineLocatorFindParameters(text) { MaxLocations = 50, OutSpatialReference = WebMapVM.SpatialReference }, cancellationToken); } if (result.Count == 0) { SearchResultStatus = string.Format("No results for '{0}' found", text); if (Locations != null) { Locations.Clear(); } //await new Windows.UI.Popups.MessageDialog(string.Format("No results for '{0}' found", text)).ShowAsync(); } else { SearchResultStatus = string.Format("Found {0} results for '{1}'", result.Count.ToString(), text); Envelope extent = null; var color = (App.Current.Resources["AppAccentBrush"] as SolidColorBrush).Color; var color2 = (App.Current.Resources["AppAccentForegroundBrush"] as SolidColorBrush).Color; SimpleMarkerSymbol symbol = new SimpleMarkerSymbol() { Color = Colors.Black, Outline = new SimpleLineSymbol() { Color = Colors.Black, Width = 2 }, Size = 16, Style = SimpleMarkerStyle.Square }; // set the picture marker symbol used in the search result composite symbol. var imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Icons/SearchResult.png")); var imageSource = await imageFile.OpenReadAsync(); var pictureMarkerSymbol = new PictureMarkerSymbol(); await pictureMarkerSymbol.SetSourceAsync(imageSource); // apply an x and y offsets so that the tip of of the pin points to the correct location. pictureMarkerSymbol.XOffset = SearchResultPinXOffset; pictureMarkerSymbol.YOffset = SearchResultPinYOffset; int ID = 1; foreach (var r in result) { if (extent == null) { extent = r.Extent; } else if (r.Extent != null) { extent = extent.Union(r.Extent); } var textSymbol = new TextSymbol() { Text = ID.ToString(), Font = new SymbolFont() { FontFamily = "Verdena", FontSize = 10, FontWeight = SymbolFontWeight.Bold }, Color = color2, BorderLineColor = color2, HorizontalTextAlignment = Esri.ArcGISRuntime.Symbology.HorizontalTextAlignment.Center, VerticalTextAlignment = Esri.ArcGISRuntime.Symbology.VerticalTextAlignment.Bottom, XOffset = SearchResultPinXOffset, YOffset = SearchResultPinYOffset }; //Looks like Top and Bottom are switched - potential CR // a compsite symbol for both the PictureMarkerSymbol and the TextSymbol could be used, but we // wanted to higlight the pin without the text; therefore, we will add them separately. // add the PictureMarkerSymbol to _searchResultLayer Graphic pin = new Graphic() { Geometry = r.Extent.GetCenter(), Symbol = pictureMarkerSymbol, }; pin.Attributes["ID"] = ID; pin.Attributes["Name"] = r.Name; _searchResultLayer.Graphics.Add(pin); // add the text to _searchResultLayer Graphic pinText = new Graphic() { Geometry = r.Extent.GetCenter(), Symbol = textSymbol, }; pinText.Attributes["ID"] = ID; pinText.Attributes["Name"] = r.Name; _searchResultLayer.Graphics.Add(pinText); ID++; } SetResult(result); base.RaisePropertyChanged("IsClearGraphicsVisible"); if (extent != null) { var _ = SetViewAsync(extent, 50); } } } finally { IsLoadingSearchResults = false; _searchCancellationTokenSource = null; _currentSearchString = null; } }
public async Task Query(string text) { try { if (Controller == null) return; IsLoadingSearchResults = true; text = text.Trim(); if (_searchCancellationTokenSource != null) { if (_currentSearchString != null && _currentSearchString == text) return; _searchCancellationTokenSource.Cancel(); } _searchCancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _searchCancellationTokenSource.Token; Envelope boundingBox = Controller.Extent; if (string.IsNullOrWhiteSpace(text)) return; if (_currentSearchString != null && _currentSearchString != text) { if (!cancellationToken.IsCancellationRequested) _searchCancellationTokenSource.Cancel(); } _searchResultLayer.Graphics.Clear(); var geo = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer", UriKind.Absolute), ""); boundingBox = boundingBox.Expand(1.2); _currentSearchString = text; SearchResultStatus = string.Format("Searching for '{0}'...", text.Trim()); var result = await geo.FindAsync(new OnlineLocatorFindParameters(text) { MaxLocations = 25, OutSpatialReference = WebMapVM.SpatialReference, SearchExtent = boundingBox, Location = (MapPoint)GeometryEngine.NormalizeCentralMeridian(boundingBox.GetCenter()), Distance = GetDistance(boundingBox), OutFields = new List<string>() { "PlaceName", "Type", "City", "Country" } }, cancellationToken); // if no results, try again with larger and larger extent var retries = 3; while (result.Count == 0 && --retries > 0) { if (cancellationToken.IsCancellationRequested) return; boundingBox = boundingBox.Expand(2); result = await geo.FindAsync(new OnlineLocatorFindParameters(text) { MaxLocations = 25, OutSpatialReference = WebMapVM.SpatialReference, SearchExtent = boundingBox, Location = (MapPoint)GeometryEngine.NormalizeCentralMeridian(boundingBox.GetCenter()), Distance = GetDistance(boundingBox), OutFields = new List<string>() { "PlaceName", "Type", "City", "Country"} }, cancellationToken); } if (cancellationToken.IsCancellationRequested) return; if (result.Count == 0) { // atfer trying to expand the bounding box several times and finding no results, // let us try finding results without the spatial bound. result = await geo.FindAsync(new OnlineLocatorFindParameters(text) { MaxLocations = 25, OutSpatialReference = WebMapVM.SpatialReference, OutFields = new List<string>() { "PlaceName", "Type", "City", "Country"} }, cancellationToken); if (result.Any()) { // since the results are not bound by any spatial filter, let us show well known administrative // places e.g. countries and cities, and filter out other results e.g. restaurents and business names. var typesToInclude = new List<string>() { "", "city", "community", "continent", "country", "county", "district", "locality", "municipality", "national capital", "neighborhood", "other populated place", "state capital", "state or province", "territory", "village"}; for (var i = result.Count - 1; i >= 0; --i) { // get the result type var resultType = ((string)result[i].Feature.Attributes["Type"]).Trim().ToLower(); // if the result type exists in the inclusion list above, keep it in the list of results if (typesToInclude.Contains(resultType)) continue; // otherwise, remove it from the list of results result.RemoveAt(i); } } } if (result.Count == 0) { SearchResultStatus = string.Format("No results for '{0}' found", text); if (Locations != null) Locations.Clear(); //await new Windows.UI.Popups.MessageDialog(string.Format("No results for '{0}' found", text)).ShowAsync(); } else { SearchResultStatus = string.Format("Found {0} results for '{1}'", result.Count.ToString(), text); Envelope extent = null; var color = (App.Current.Resources["AppAccentBrush"] as SolidColorBrush).Color; var color2 = (App.Current.Resources["AppAccentForegroundBrush"] as SolidColorBrush).Color; SimpleMarkerSymbol symbol = new SimpleMarkerSymbol() { Color = Colors.Black, Outline = new SimpleLineSymbol() { Color = Colors.Black, Width = 2 }, Size = 16, Style = SimpleMarkerStyle.Square }; // set the picture marker symbol used in the search result composite symbol. var imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Icons/SearchResult.png")); var imageSource = await imageFile.OpenReadAsync(); var pictureMarkerSymbol = new PictureMarkerSymbol(); await pictureMarkerSymbol.SetSourceAsync(imageSource); // apply an x and y offsets so that the tip of of the pin points to the correct location. pictureMarkerSymbol.XOffset = SearchResultPinXOffset; pictureMarkerSymbol.YOffset = SearchResultPinYOffset; int ID = 1; foreach (var r in result) { if (extent == null) extent = r.Extent; else if (r.Extent != null) extent = extent.Union(r.Extent); var textSymbol = new TextSymbol() { Text = ID.ToString(), Font = new SymbolFont() { FontFamily = "Verdena", FontSize = 10, FontWeight = SymbolFontWeight.Bold }, Color = color2, BorderLineColor = color2, HorizontalTextAlignment = Esri.ArcGISRuntime.Symbology.HorizontalTextAlignment.Center, VerticalTextAlignment = Esri.ArcGISRuntime.Symbology.VerticalTextAlignment.Bottom, XOffset = SearchResultPinXOffset, YOffset = SearchResultPinYOffset }; //Looks like Top and Bottom are switched - potential CR // a compsite symbol for both the PictureMarkerSymbol and the TextSymbol could be used, but we // wanted to higlight the pin without the text; therefore, we will add them separately. // add the PictureMarkerSymbol to _searchResultLayer Graphic pin = new Graphic() { Geometry = r.Extent.GetCenter(), Symbol = pictureMarkerSymbol, }; pin.Attributes["ID"] = ID; pin.Attributes["Name"] = r.Name; _searchResultLayer.Graphics.Add(pin); // add the text to _searchResultLayer Graphic pinText = new Graphic() { Geometry = r.Extent.GetCenter(), Symbol = textSymbol, }; pinText.Attributes["ID"] = ID; pinText.Attributes["Name"] = r.Name; _searchResultLayer.Graphics.Add(pinText); ID++; } SetResult(result); base.RaisePropertyChanged("IsClearGraphicsVisible"); if (extent != null) { var _ = SetViewAsync(extent, 50); } } } finally { IsLoadingSearchResults = false; _searchCancellationTokenSource = null; _currentSearchString = null; } }
private async void SingleLineAddressButton_Click(object sender, RoutedEventArgs e) { try { OnlineLocatorTask locatorTask = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer", UriKind.Absolute), ""); var text = SingleLineAddressText.Text; if (string.IsNullOrEmpty(text)) { return; } _locatorFindParameter = new OnlineLocatorFindParameters(text) { Text = text, Location = mapView1.Extent.GetCenter(), Distance = mapView1.Extent.Width / 2, MaxLocations = 5, OutSpatialReference = mapView1.SpatialReference, OutFields = new List <string>() { "*" } }; CancellationToken cancellationToken = new CancellationTokenSource().Token; var results = await locatorTask.FindAsync(_locatorFindParameter, cancellationToken); if (_candidateGraphicsLayer.Graphics != null && _candidateGraphicsLayer.Graphics.Count > 0) { _candidateGraphicsLayer.Graphics.Clear(); } if (results != null) { foreach (var result in results) { var geom = result.Feature.Geometry; Graphic graphic = new Graphic() { Geometry = geom }; graphic.Attributes.Add("Name", result.Feature.Attributes["Match_addr"]); if (geom.GeometryType == GeometryType.Point) { var pt = geom as MapPoint; string latlon = String.Format("{0}, {1}", pt.X, pt.Y); graphic.Attributes.Add("LatLon", latlon); } if (geom.SpatialReference == null) { geom.SpatialReference = mapView1.SpatialReference; } _candidateGraphicsLayer.Graphics.Add(graphic); } } } catch (Exception) { throw; } }
private async void GetDirections_Click(object sender, RoutedEventArgs e) { //Reset DirectionsStackPanel.Children.Clear(); var _stops = new List<Graphic>(); var _locator = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"), ""); var routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Clear(); try { var fields = new List<string> { "Loc_name" }; //Geocode from address var fromLocation = await _locator.GeocodeAsync(ParseAddress(FromTextBox.Text), fields, CancellationToken.None); if (fromLocation != null && fromLocation.Count > 0) { var result = fromLocation.FirstOrDefault(); Graphic graphicLocation = new Graphic() { Geometry = result.Location, Symbol = LayoutRoot.Resources["FromSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol }; graphicLocation.Attributes["address"] = result.Address; graphicLocation.Attributes["score"] = result.Score; _stops.Add(graphicLocation); routeLayer.Graphics.Add(graphicLocation); } //Geocode to address var toLocation = await _locator.GeocodeAsync(ParseAddress(ToTextBox.Text), fields, CancellationToken.None); if (toLocation != null && toLocation.Count > 0) { var result = toLocation.FirstOrDefault(); Graphic graphicLocation = new Graphic() { Geometry = result.Location, Symbol = LayoutRoot.Resources["ToSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol }; graphicLocation.Attributes["address"] = result.Address; graphicLocation.Attributes["score"] = result.Score; _stops.Add(graphicLocation); routeLayer.Graphics.Add(graphicLocation); } var routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route")); RouteParameters routeParams = await routeTask.GetDefaultParametersAsync(); routeParams.ReturnRoutes = true; routeParams.ReturnDirections = true; routeParams.DirectionsLengthUnit = LinearUnits.Miles; routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = mapView1.SpatialReference; routeParams.Stops = new FeaturesAsFeature(routeLayer.Graphics); var routeTaskResult = await routeTask.SolveAsync(routeParams); _directionsFeatureSet = routeTaskResult.Routes.FirstOrDefault(); _directionsFeatureSet.RouteGraphic.Symbol = LayoutRoot.Resources["RouteSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol; routeLayer.Graphics.Add(_directionsFeatureSet.RouteGraphic); var totalLength = _directionsFeatureSet.GetTotalLength(LinearUnits.Miles); var calculatedLength = _directionsFeatureSet.RouteDirections.Sum(x => x.GetLength(LinearUnits.Miles)); TotalDistanceTextBlock.Text = string.Format("Total Distance: {0:N3} miles", totalLength); TotalTimeTextBlock.Text = string.Format("Total Time: {0}", FormatTime(_directionsFeatureSet.TotalTime.TotalMinutes)); TitleTextBlock.Text = _directionsFeatureSet.RouteName; int i = 1; foreach (var item in _directionsFeatureSet.RouteDirections) { TextBlock textBlock = new TextBlock() { Text = string.Format("{0:00} - {1}", i, item.Text), Tag = item.Geometry, Margin = new Thickness(0, 15,0,0), FontSize = 20 }; textBlock.Tapped += TextBlock_Tapped; DirectionsStackPanel.Children.Add(textBlock); var secondarySP = new StackPanel() { Orientation = Orientation.Horizontal }; if (item.Time.TotalMinutes > 0) { var timeTb = new TextBlock { Text = string.Format("Time : {0:N2} minutes", item.Time.TotalMinutes), Margin= new Thickness(45,0,0,0) }; secondarySP.Children.Add(timeTb); var distTb = new TextBlock { Text = string.Format("Distance : {0:N2} miles", item.GetLength(LinearUnits.Miles)), Margin = new Thickness(25, 0, 0, 0) }; secondarySP.Children.Add(distTb); DirectionsStackPanel.Children.Add(secondarySP); } i++; } mapView1.SetView(_directionsFeatureSet.RouteGraphic.Geometry.Extent.Expand(1.2)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
private async void mapView_Tapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e) { var hitGraphic = await _locationGraphicsLayer.HitTestAsync(mapView1, e.Position); if (hitGraphic != null) { if (maptip.Visibility == Windows.UI.Xaml.Visibility.Collapsed) { MapTipGraphic = hitGraphic; RenderMapTip(); } else { maptip.Visibility = Windows.UI.Xaml.Visibility.Collapsed; maptip.DataContext = null; MapTipGraphic = null; } } else { maptip.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var mp = mapView1.ScreenToLocation(e.Position); Graphic g = new Graphic() { Geometry = mp }; var layer = mapView1.Map.Layers.OfType <GraphicsLayer>().First(); layer.Graphics.Add(g); var token = ""; var locatorTask = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer", UriKind.Absolute), token); try { var result = await locatorTask.ReverseGeocodeAsync(mp, 30, mapView1.SpatialReference, CancellationToken.None); Graphic graphic = new Graphic() { Geometry = mp }; string latlon = String.Format("{0}, {1}", result.Location.X, result.Location.Y); string address1 = result.AddressFields["Address"].ToString(); string address2 = String.Format("{0}, {1} {2}", result.AddressFields["City"], result.AddressFields["Region"], result.AddressFields["Postal"]); graphic.Attributes.Add("LatLon", latlon); graphic.Attributes.Add("Address1", address1); graphic.Attributes.Add("Address2", address2); _locationGraphicsLayer.Graphics.Add(graphic); MapTipGraphic = graphic; RenderMapTip(); } catch (Exception) { } } }
private async void GetDirections_Click(object sender, RoutedEventArgs e) { //Reset DirectionsStackPanel.Children.Clear(); var _stops = new List <Graphic>(); var _locator = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"), ""); var routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Clear(); try { var fields = new List <string> { "Loc_name" }; //Geocode from address var fromLocation = await _locator.GeocodeAsync(ParseAddress(FromTextBox.Text), fields, CancellationToken.None); if (fromLocation != null && fromLocation.Count > 0) { var result = fromLocation.FirstOrDefault(); Graphic graphicLocation = new Graphic() { Geometry = result.Location, Symbol = LayoutRoot.Resources["FromSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol }; graphicLocation.Attributes["address"] = result.Address; graphicLocation.Attributes["score"] = result.Score; _stops.Add(graphicLocation); routeLayer.Graphics.Add(graphicLocation); } //Geocode to address var toLocation = await _locator.GeocodeAsync(ParseAddress(ToTextBox.Text), fields, CancellationToken.None); if (toLocation != null && toLocation.Count > 0) { var result = toLocation.FirstOrDefault(); Graphic graphicLocation = new Graphic() { Geometry = result.Location, Symbol = LayoutRoot.Resources["ToSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol }; graphicLocation.Attributes["address"] = result.Address; graphicLocation.Attributes["score"] = result.Score; _stops.Add(graphicLocation); routeLayer.Graphics.Add(graphicLocation); } var routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route")); RouteParameters routeParams = await routeTask.GetDefaultParametersAsync(); routeParams.ReturnRoutes = true; routeParams.ReturnDirections = true; routeParams.DirectionsLengthUnit = LinearUnits.Miles; routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = mapView1.SpatialReference; routeParams.Stops = new FeaturesAsFeature(routeLayer.Graphics); var routeTaskResult = await routeTask.SolveAsync(routeParams); _directionsFeatureSet = routeTaskResult.Routes.FirstOrDefault(); _directionsFeatureSet.RouteGraphic.Symbol = LayoutRoot.Resources["RouteSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol; routeLayer.Graphics.Add(_directionsFeatureSet.RouteGraphic); var totalLength = _directionsFeatureSet.GetTotalLength(LinearUnits.Miles); var calculatedLength = _directionsFeatureSet.RouteDirections.Sum(x => x.GetLength(LinearUnits.Miles)); TotalDistanceTextBlock.Text = string.Format("Total Distance: {0:N3} miles", totalLength); TotalTimeTextBlock.Text = string.Format("Total Time: {0}", FormatTime(_directionsFeatureSet.TotalTime.TotalMinutes)); TitleTextBlock.Text = _directionsFeatureSet.RouteName; int i = 1; foreach (var item in _directionsFeatureSet.RouteDirections) { TextBlock textBlock = new TextBlock() { Text = string.Format("{0:00} - {1}", i, item.Text), Tag = item.Geometry, Margin = new Thickness(0, 15, 0, 0), FontSize = 20 }; textBlock.Tapped += TextBlock_Tapped; DirectionsStackPanel.Children.Add(textBlock); var secondarySP = new StackPanel() { Orientation = Orientation.Horizontal }; if (item.Time.TotalMinutes > 0) { var timeTb = new TextBlock { Text = string.Format("Time : {0:N2} minutes", item.Time.TotalMinutes), Margin = new Thickness(45, 0, 0, 0) }; secondarySP.Children.Add(timeTb); var distTb = new TextBlock { Text = string.Format("Distance : {0:N2} miles", item.GetLength(LinearUnits.Miles)), Margin = new Thickness(25, 0, 0, 0) }; secondarySP.Children.Add(distTb); DirectionsStackPanel.Children.Add(secondarySP); } i++; } mapView1.SetView(_directionsFeatureSet.RouteGraphic.Geometry.Extent.Expand(1.2)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }