Per utilizzarla, si deve fornire il contenuto dell'Uri al quale si vuole accedere e poi chiamare il metodo DownloadStringAsync o il metodo OpenReadAsync per scaricare i dati.
Nel caso che vediamo, stiamo usando OpenReadAsync. Utilizzando questi metodi dobbiamo impostare una funzione di callback per prendere i dati restituiti. Quando il trasferimento dei dati è terminato, viene chiamata la nostra funzione client_OpenReadCompleted che riceve un oggetto (argomento: OpenReadCompletedEventArgs) che contiene una proprietà di nome Result che contiene l'oggetto restituito.
In questo esempio, facciamo una chiamata al locator EU degli ArcGIS Online con una risposta di tipo JSON.
Esempio di risposta:
{
"address" :
{
"Address" : "VIA LUCIANO MANARA 48",
"City" : "MONZA",
"Postcode" : "20052",
"Country" : "",
"Loc_name" : "ITASMRVATGeoco"
},
"location" :
{
"x" : 9.25588354543629,
"y" : 45.5901805291887,
"spatialReference" : {
"wkid" : 4326
}
}
}
Nello XAML utilizzeremo una nostra classe (JSONFormatter) che implementa IvalueConverter per il binding.
public partial class Page : UserControl
{
JsonObject results;
WebClient client;
public Page()
{
InitializeComponent();
// Send HTTP request to the JSON search API
client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
}
private void MyMap_MouseClick(object sender, ESRI.ArcGIS.Map.MouseEventArgs e)
{
ESRI.ArcGIS.Geometry.MapPoint pt = e.MapPoint;
string xy = string.Format("{0},{1}", pt.X.ToString(NumberFormatInfo.InvariantInfo), pt.Y.ToString(NumberFormatInfo.InvariantInfo));
client.OpenReadAsync(new Uri("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Locators/ESRI_Geocode_EU/GeocodeServer/reverseGeocode?location=" + xy + "&distance=0&f=pjson"));
Canvas.SetLeft(ResultsPane,e.ScreenPoint.X + 10);
Canvas.SetTop(ResultsPane,e.ScreenPoint.Y + 10);
GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
Graphic graphic = new Graphic();
graphic.Symbol = DefaultMarkerSymbol;
graphic.Geometry = pt;
graphicsLayer.Graphics.Add(graphic);
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
// Parse results into a JsonObject
results = (JsonObject)JsonObject.Load(e.Result);
// Update LINQ query
UpdateQuery();
ResultsPane.Visibility = Visibility.Visible;
}
}
void UpdateQuery()
{
if (results != null)
{
// Generate LINQ query based on JsonObject and user settings
var members = from address in results
where address.Key == "address"
select address;
// Databind the results to a UI control
resultList.DataContext = members;
}
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
ResultsPane.Visibility = Visibility.Collapsed;
GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
graphicsLayer.ClearGraphics();
}
}
public class JsonFormatter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string valueString = ((System.Collections.Generic.KeyValuePair<string,JsonValue>)value).Value[(string)parameter];
// JsonObject doesn't strip quotes from strings, so do that and return the result
return valueString.Replace("\"", "");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML:
<UserControl x:Class="slWSJson.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:esri="clr-namespace:ESRI.ArcGIS;assembly=ESRI.ArcGIS"
xmlns:esriConverters="clr-namespace:ESRI.ArcGIS.ValueConverters;assembly=ESRI.ArcGIS"
xmlns:esriSymbols="clr-namespace:ESRI.ArcGIS.Symbols;assembly=ESRI.ArcGIS"
xmlns:local="clr-namespace:slWSJson">
<UserControl.Resources>
<local:JsonFormatter x:Key="jsonFormatter"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Grid.Resources>
<esriSymbols:SimpleMarkerSymbol x:Name="DefaultMarkerSymbol" Color="Red" Size="12" Style="Circle" />
</Grid.Resources>
<esri:Map x:Name="MyMap" Background="White" Extent="-7.732,35.69,27.021,56.346" MouseClick="MyMap_MouseClick">
<esri:Map.Layers>
<esri:ArcGISTiledMapServiceLayer ID="BaseMapLayer" Url="http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapServer" />
<esri:GraphicsLayer ID="MyGraphicsLayer">
</esri:GraphicsLayer>
</esri:Map.Layers>
</esri:Map>
<Canvas>
<StackPanel x:Name="ResultsPane" Visibility="Collapsed" Width="300" Height="150">
<Button x:Name="btnClose" Click="btnClose_Click" Content="Close">
</Button>
<ListBox x:Name="resultList" ItemsSource="{Binding}" Height="150">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock FontSize="18" TextWrapping="Wrap">
<TextBlock.Text>
<Binding Converter="{StaticResource jsonFormatter}" ConverterParameter="Address"></Binding>
</TextBlock.Text>
</TextBlock>
<TextBlock FontSize="14">
<TextBlock.Text>
<Binding Converter="{StaticResource jsonFormatter}" ConverterParameter="City"></Binding>
</TextBlock.Text>
</TextBlock>
<TextBlock FontSize="14">
<TextBlock.Text>
<Binding Converter="{StaticResource jsonFormatter}" ConverterParameter="Postcode"></Binding>
</TextBlock.Text>
</TextBlock>
<TextBlock FontSize="14">
<TextBlock.Text>
<Binding Converter="{StaticResource jsonFormatter}" ConverterParameter="Country"></Binding>
</TextBlock.Text>
</TextBlock>
<TextBlock FontSize="14">
<TextBlock.Text>
<Binding Converter="{StaticResource jsonFormatter}" ConverterParameter="Loc_name"></Binding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Canvas>
</Grid>
</UserControl>
Scarica qui la soluzione
Nessun commento:
Posta un commento