简体   繁体   中英

Windows phone 8 Geolocator Exception

Hi I am new to WP development. I want to find the users current zipcode or postal code. So I have the following code in place. Problem is this line d.zip = position.CivicAddress.PostalCode; always gives an object reference not set to an instance of an object exception.But I am able to get the latitude and longitude just fine. I have also tried position.CivicAddresss.City but still the same exception. Please help.

  async void Button_Click_1(object sender, RoutedEventArgs e)
           {
               Data d = new Data();
               Geolocator locator = new Geolocator();
               try
               {
                   Geoposition position = await locator.GetGeopositionAsync();
                   d.zip = position.CivicAddress.PostalCode;
                   d.Latitude = position.Coordinate.Latitude;
                   d.Longitude = position.Coordinate.Longitude;
                   MessageBox.Show(d.zip);
               }
               catch (Exception ex)
               {
                   MessageBox.Show(ex.Message);
               }
           }

    public class Data
    {
        public string zip { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
    }

I believe GeoPosition.CivicAddress is deprecated. You need to use the MapLocationFinder to get address information.

async void Button_Click_1(object sender, RoutedEventArgs e)
{
    Data d = new Data();
    Geolocator locator = new Geolocator();
    try
    {
        Geoposition position = await locator.GetGeopositionAsync();

        // Get address data with MapLocationFinder
        var result = await MapLocationFinder.FindLocationsAtAsync(position.Coordinate.Point);
        if (result.Status == MapLocationFinderStatus.Success)
        {
            var address = result.Locations[0].Address;
            var zip = address.PostCode;
            d.zip = zip;
        }

        // These are deprecated as well. 
        // Use position.Coordinate.Point.Position.Latitude and
        // position.Coordinate.Point.Position.Longitude

        d.Latitude = position.Coordinate.Latitude;
        d.Longitude = position.Coordinate.Longitude;
        MessageBox.Show(d.zip);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

public class Data
{
    public string zip { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM