网上关于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);