急!急!急!GPS定位 跪求高手帮忙!
网上关于GPS定位的代码挺多,我在网上考了一段,在真机上测试总是报错(异常):System.IO.IOException,位置是: sp = new SerialPort();
.
.
.
sp = new SerialPort(); (就是这里报错)
代码挺简单就是找不到什么错,我的手机有GPS芯片,是windows mobile 6.1的.
具体代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
using System.Globalization;
namespace GolfAssistant
{
public class SerialPortGps
{
bool stop = false;
string portName = "COM7";
int baudRate = 4800;
SerialPort sp;
GpsMonitorForm. form;
/*GPS数据*/
public string longitude="0";//经度
public string latitude = "0";//纬度
public string altitude = "0";//海拔
public string altitudeUnit = "";//海拔单位
public string usedSatellite = "0";//应用卫星数
public string locatedSatellite = "0";//定位的卫星总数
public string signalSatellite = "0";//天空中收到讯号的卫星总数
public string totalSatellite = "0";//天空中卫星总数
public bool located = false;
public SerialPortGps(GpsMonitorForm. form)
{
this.form. = form;
}
public void open()
{
if (null != sp)
{
MessageBox.Show("GPS未停止");
}
sp = new SerialPort();
sp.PortName = portName;
sp.BaudRate = baudRate;
sp.ReadTimeout = 500;
sp.WriteTimeout = 500;
Thread readThread = new Thread(read);
sp.Open();
stop = false;
readThread.Start();
}
public void close()
{
stop = true;
}
public void read()
{
while (!stop)
{
try
{
string message = sp.ReadLine();
message = message.Substring(0,message.Length - sp.NewLine.Length);
if (message.StartsWith("$GPGGA"))
{
//模拟定位
//message = "$GPGGA,012440.00,2232.458380,N,11356.91024,E,1,05,2.7,40.2,M,0.5,M,,*6F";
//message = "$GPGGA,012440.00,2232.301654,N,11402.058366,E,1,05,2.7,40.2,M,0.5,M,,*6F";
parseGPGGA(message);
}
else if (message.StartsWith("$GPGSV"))
{
parseGPGSV(message);
}
form.Invoke(new MethodInvoker(form.addData), message);
}
catch (TimeoutException) { }
}
sp.Close();
sp = null;
MessageBox.Show("GPS已停止");
}
public static string toDecimalDegree(string s)
{
int idx = s.IndexOf(".");
string d1 = s.Substring(0,idx-2);
string d2 = s.Substring(idx - 2);
double degree = Double.Parse(d1) + Double.Parse(d2) / 60;
return degree.ToString("F8", CultureInfo.InvariantCulture);
}
delegate void MethodInvoker(string message);
private void parseGPGGA(string message)
{
char[] separator = { ','};
string[] data = message.Split(separator);
if (data[6].Equals("1"))
{
latitude=toDecimalDegree(data[2]);//纬度
longitude=toDecimalDegree(data[4]);//经度
altitude=data[9]+data[10];//海拔
altitudeUnit = data[10];//海拔单位
usedSatellite = data[7];//应用卫星数
located = true;
}
else
{
located = false;
}
}
private void parseGPGSV(string message)
{
char[] separator = { ',' };
string[] data = message.Split(separator);
locatedSatellite = data[2];//定位的卫星总数
signalSatellite = data[1];//天空中收到讯号的卫星总数
totalSatellite = data[3];//天空中卫星总数
}
private void smoothGPGGA()
{
}
}
}
端口和波特率都没错
拜托各位朋友帮帮忙,VS里自带的太长了看不懂,我是菜鸟,拜托啦~
[解决办法]
建议使用SDK里给的示例会很不错