【问题标题】:Binding data to ListView to display distance to nearby place using Google Places API with UWP使用带有 UWP 的 Google Places API 将数据绑定到 ListView 以显示到附近地点的距离
【发布时间】:2016-02-13 02:40:12
【问题描述】:

目前,我有一个使用 Google Places API 使用 UWP 显示附近地点的项目。我正在使用 ListView 显示附近地点的数量,并成功地将 API 提供的一些基本信息显示到我的 ListView 中。我有这样的数据模板

<DataTemplate x:Key="ResultPlaces">
        <StackPanel Orientation="Vertical">

            ...
                <Grid Grid.Column="2">
                    <TextBlock Text="{Binding placeDistance}" Foreground="#42424c" TextWrapping="Wrap" FontSize="12" Margin="10,0,0,0"/>

                </Grid>
            </Grid>


        </StackPanel>

我也有这样的 ListView

<ListView Name="listPlace"
                    ItemTemplate="{StaticResource ResultPlaces}">

                </ListView>

我已经在后面的代码中解析了 API 结果中的 JSON,并将其作为我的 ListView.ItemsSource。问题是 API 不提供距离对象。因此,我创建了一种方法来计算 2 个地点之间的距离,并使用它来计算 API 结果中的每个结果。我还在类 Result 中创建了名为 placeDistance 的 get set 属性,该属性提供了 API 项结果。

这是我的设置属性

  public class Result
    {
        ....
        public Review[] reviews { get; set; }
        public int user_ratings_total { get; set; }

        public string placeDistance { get; set; }
    }

这是我的代码来计算结果上的每一个距离

int lengthResult = placesList.results.Count();


                for (int i = 0; i < lengthResult; i++)
                {
                    double myLat = placesList.results[i].geometry.location.lat;
                    double myLong = placesList.results[i].geometry.location.lng;
                    double myCurrentLat = Convert.ToDouble(parameters.lat);
                    double myCurrentLong = Convert.ToDouble(parameters.longit);

                    var newDistance = new Result();
                    newDistance.placeDistance = DistanceBetweenPlaces(myCurrentLong, myCurrentLat, myLong, myLat);


                }

当我将它部署到手机中时,DataTemplate 中的其他项目正确显示。但我无法得到任何距离文本。我是不是做错了什么?

【问题讨论】:

    标签: c# windows windows-phone google-places-api win-universal-app


    【解决方案1】:

    如果没有看到完整的代码,很难确定,但我最好的猜测是,您不应该在循环中创建 Result 的新实例,您正在计算距离。

    从命名来看,我假设placesList.results 已经是Results 的列表以及您绑定到ListView 的所有其他项目。在这种情况下,您应该替换:

    var newDistance = new Result();
    newDistance.placeDistance =
        DistanceBetweenPlaces(myCurrentLong, myCurrentLat, myLong, myLat);
    

    与:

    placesList.results[i].placeDistance = 
        DistanceBetweenPlaces(myCurrentLong, myCurrentLat, myLong, myLat);
    

    【讨论】:

    • 啊,我的错。你说的对。我不应该创建一个新实例。你的回答让我很开心,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2013-06-27
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    相关资源
    最近更新 更多