using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Device.Location;
namespace Location
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
GetLocation();
}
static void GetLocation()
{
GeoCoordinateWatcher GEOWatcher = new GeoCoordinateWatcher();
GEOWatcher.TryStart(false, TimeSpan.FromMilliseconds(1000));
GeoCoordinate Coordinates = GEOWatcher.Position.Location;
if (Coordinates.IsUnknown != true)
{
Console.WriteLine("Latitude: " + Coordinates.Latitude + ", Longitude: " + Coordinates.Longitude);
Console.WriteLine("https://www.google.co.uk/#q=" + Coordinates.Latitude + "," + Coordinates.Longitude);
GEOWatcher.Dispose();
}
else
{
Console.WriteLine("Location currently unavaliable");
}
}
}
}
任何帮助都是适用的,如果您对我的代码有任何提示或改进,请发表评论,谢谢
答案 0 :(得分:1)
当您指明它时,#34;不起作用"你在说什么?
您是说您收到了消息"位置目前不可用"?如果是这样,这可能是因为设备中的GPS单元需要一些时间来锁定卫星。
在下面编辑以解释我的评论:
GeoCoordinateWatcher需要一些时间来锁定卫星并提供一致的结果。将GeoCoordinateWatcher移动到类本身(因此它不会在按钮单击事件结束时收集垃圾)将提供一些缓解,但它仍然无法在您启动应用程序时立即给出结果。像这样:
public partial class Form1 : Form
{
GeoCoordinateWatcher GEOWatcher;
public Form1()
{
InitializeComponent();
// this will start the GeoCoordinateWatcher when the app starts
GEOWatcher = new GeoCoordinateWatcher();
GEOWatcher.TryStart(false, TimeSpan.FromMilliseconds(1000));
}
private void button1_Click(object sender, EventArgs e)
{
GetLocation();
}
static void GetLocation()
{
GeoCoordinate Coordinates = GEOWatcher.Position.Location;
if (Coordinates.IsUnknown != true)
{
Console.WriteLine("Latitude: " + Coordinates.Latitude + ", Longitude: " + Coordinates.Longitude);
Console.WriteLine("https://www.google.co.uk/#q=" + Coordinates.Latitude + "," + Coordinates.Longitude);
}
else
{
Console.WriteLine("Location currently unavaliable");
}
}
}