【发布时间】:2012-06-13 16:22:54
【问题描述】:
我想创建一个简单的应用程序,向我显示当前应用程序所在的城市。 当我尝试粘贴下面的代码时,城市返回空,国家=US返回,但我住在比利时。
据此link 它说: 定位服务提供对定位功能的访问,例如小区三角测量、WiFi(通过 IP 地址)和 GPS。此外,许多现代设备都支持以前面提到的某种方式解析位置,应用程序必须处理位置服务无法解析位置或用户从控制面板禁用位置服务的情况。
我的笔记本电脑没有GPS,但有了IP,它应该知道城市和国家。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Geolocation;
using System.Threading.Tasks;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace AlarmPro
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
//InitializeLocationServices();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
TextBlock txt = new TextBlock();
var location = await InitializeLocationServices();
txt.Text = location;
Grid.SetRow(txt, 0);
Grid.SetColumn(txt, 1);
}
private async Task<string> InitializeLocationServices()
{
//Initialize geolocator object
Geolocator geoLocator = new Geolocator();
try
{
//Try resolve the current location
var position = await geoLocator.GetGeopositionAsync();
if (position !=null)
{
string city = position.CivicAddress.City;
string country = position.CivicAddress.Country;
string state = position.CivicAddress.State;
string zip = position.CivicAddress.PostalCode;
string msg = "I am located in " + country;
if (city.Length > 0)
msg += ", city of " + city;
if (state.Length > 0)
msg += ", " + state;
if (zip.Length > 0)
msg += " near zip code " + zip;
return msg;
}
return string.Empty;
}
catch (Exception)
{
//Nothing to do - no GPS signal or some timeout occured.n .
return string.Empty;
}
}
}
}
【问题讨论】:
-
是的,在控制面板上启用了地理定位。但是在区域中,将位置更改为美国,我将其更改为比利时,现在我的代码显示我在国家/地区是 BE,但城市仍然是空的
-
我的家庭设置中没有任何代理,我在我的 ISP 下。
-
位置对象是否还有其他包含数据的属性?
-
另外,地理定位器的“LocationStatus”属性的值是多少?
-
经度和经度包含数据,来自CivicAddress的属性,都是空的
标签: c# location windows-8 microsoft-metro