本文示範如何以 ArcGIS Runtime for Windows Phone SDK 開發手機地圖應用,在定位所在位置的同時,把多個定位點匯出成 GPX 檔,供 ArcMap、Google Earth 等軟體後續使用。
Windows Phone SDK 提供了 GeoCoordinateWatcher 類別處理定位,使用前需引用 System.Device.dll,並引入 System.Device.Location 命名空間。
if (_watcher == null)
{
_watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // 高定位精度
_watcher.MovementThreshold = 50; // 最小移動間距(公尺),超過才觸發 PositionChanged
_watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
_watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
}
MovementThreshold 是很實用的參數:設為 50 代表每移動 50 公尺才記錄一次,能有效減少靜止不動時的大量重複點,也降低耗電。
_watcher.Start();
void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
if (_watcher.Permission == GeoPositionPermission.Denied)
txtStatus.Text = "應用程式無權存取定位服務";
else
txtStatus.Text = "裝置不支援定位服務";
break;
case GeoPositionStatus.Initializing:
break;
case GeoPositionStatus.NoData:
txtStatus.Text = "取得定位資料失敗";
break;
case GeoPositionStatus.Ready:
txtStatus.Text = "GPS 已經就緒";
break;
}
}
把 Disabled 拆成「權限被拒」與「裝置不支援」兩種訊息很重要,前者使用者能自行到設定中開啟,後者則只能放棄功能。
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
try
{
txtStatus.Text = "";
MapPoint point = new MapPoint(e.Position.Location.Longitude,
e.Position.Location.Latitude);
// WGS84 經緯度 → Web Mercator 投影
ESRI.ArcGIS.Client.Projection.WebMercator mercator =
new ESRI.ArcGIS.Client.Projection.WebMercator();
MapPoint ptCurrent = mercator.FromGeographic(point) as MapPoint;
_gLocation.Geometry = ptCurrent; // 更新定位標記
// 更新軌跡線
if (_gpsPoints == null)
{
_gpsPoints = new PointCollection();
_gpsPoints.Add(ptCurrent);
}
else
{
_gpsPoints.Add(ptCurrent);
Polyline line = new Polyline();
line.Paths.Add(_gpsPoints);
_gTrackLine.Geometry = line;
}
// 記錄單筆 GPS 資訊
GpsInfo gpsInfo = new GpsInfo();
gpsInfo.Altitude = e.Position.Location.Altitude;
gpsInfo.Course = e.Position.Location.Course;
gpsInfo.HorizontalAccuracy = e.Position.Location.HorizontalAccuracy;
gpsInfo.Latitude = e.Position.Location.Latitude;
gpsInfo.Longitude = e.Position.Location.Longitude;
gpsInfo.Speed = e.Position.Location.Speed;
gpsInfo.VerticalAccuracy = e.Position.Location.VerticalAccuracy;
gpsInfo.Time = e.Position.Timestamp.DateTime;
_gpxWriter.AddGpsInfo(gpsInfo);
_gpsLayer.Refresh();
map.ZoomToResolution(2.38865713397468, ptCurrent); // 定位到 16 級比例尺
}
catch (Exception ex)
{
MessageBox.Show("顯示定位資訊錯誤");
}
}
WebMercator.FromGeographic 負責把 GPS 提供的 WGS 84 經緯度轉為 Web Mercator 投影座標。這個步驟要不要做,取決於地圖本身的座標系:
if (_watcher != null)
{
_watcher.Stop();
txtStatus.Text = "";
_gpsLayer.Graphics.Clear();
}
這是一個單純的屬性集合,用來統一記錄 GPS 裝置回傳的欄位:
public class GpsInfo
{
private double _longitude = 0;
public double Longitude { get { return _longitude; } set { _longitude = value; } }
private double _latitude = 0;
public double Latitude { get { return _latitude; } set { _latitude = value; } }
private double _altitude = 0;
public double Altitude { get { return _altitude; } set { _altitude = value; } }
private double _speed = 0;
public double Speed { get { return _speed; } set { _speed = value; } }
private double _course = 0;
public double Course { get { return _course; } set { _course = value; } }
private double _horizontalAccuracy = 0;
public double HorizontalAccuracy { get { return _horizontalAccuracy; } set { _horizontalAccuracy = value; } }
private double _verticalAccuracy = 0;
public double VerticalAccuracy { get { return _verticalAccuracy; } set { _verticalAccuracy = value; } }
private DateTime _time = new DateTime();
public DateTime Time { get { return _time; } set { _time = value; } }
}
public class GpxWriter
{
private string _gpxFile = "";
private IList<GpsInfo> _lstGpsInfo = null;
private XmlWriterSettings _settings = null;
public GpxWriter(string gpxFile)
{
_settings = new XmlWriterSettings();
_settings.Indent = true;
_settings.Encoding = new UTF8Encoding(false); // 不寫入 BOM
_settings.NewLineChars = Environment.NewLine;
_lstGpsInfo = new List<GpsInfo>();
_gpxFile = gpxFile;
}
public void AddGpsInfo(GpsInfo gpsInfo)
{
_lstGpsInfo.Add(gpsInfo);
}
public void WriteToGpx()
{
try
{
if (_lstGpsInfo == null || _lstGpsInfo.Count == 0) return;
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (myIsolatedStorage.FileExists(_gpxFile))
myIsolatedStorage.DeleteFile(_gpxFile);
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile(_gpxFile, FileMode.CreateNew))
using (XmlWriter xmlWriter = XmlWriter.Create(stream, _settings))
{
xmlWriter.WriteStartDocument();
// 根節點 gpx,帶入 GPX 1.0 命名空間與相關 schema
xmlWriter.WriteStartElement("gpx", "https://www.topografix.com/GPX/1/0");
xmlWriter.WriteAttributeString("xmlns", "xsi", null,
"https://www.w3.org/2001/XMLSchema-instance");
xmlWriter.WriteAttributeString("xmlns", "mbx", null,
"https://www.motionbased.net/mbx");
xmlWriter.WriteAttributeString("xsi", "schemaLocation", null,
"https://www.topografix.com/GPX/1/0 https://www.topografix.com/GPX/1/0/gpx.xsd "
+ "https://www.motionbased.net/mbx https://www.motionbased.net/site/schemas/mbx/0.0.1/mbx.xsd");
xmlWriter.WriteAttributeString("creator", "YELLOW EAST https://weibo.com/yelloweast");
xmlWriter.WriteAttributeString("version", "1.0");
// trk → trkseg
xmlWriter.WriteStartElement("trk");
xmlWriter.WriteStartElement("trkseg");
foreach (GpsInfo gpsInfo in _lstGpsInfo)
{
xmlWriter.WriteStartElement("trkpt");
xmlWriter.WriteAttributeString("lat", gpsInfo.Latitude.ToString());
xmlWriter.WriteAttributeString("lon", gpsInfo.Longitude.ToString());
xmlWriter.WriteElementString("ele", gpsInfo.Altitude.ToString());
xmlWriter.WriteElementString("time", gpsInfo.Time.ToShortDateString()
+ " " + gpsInfo.Time.ToLongTimeString());
xmlWriter.WriteElementString("course", gpsInfo.Course.ToString());
xmlWriter.WriteElementString("speed", gpsInfo.Speed.ToString());
xmlWriter.WriteEndElement(); // trkpt
}
xmlWriter.WriteEndElement(); // trkseg
xmlWriter.WriteEndElement(); // trk
xmlWriter.WriteEndDocument();
xmlWriter.WriteEndElement(); // gpx
}
_lstGpsInfo.Clear(); // 清空歷史記錄
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("寫 GPX 檔錯誤:" + ex.Message);
}
}
}
實作時有兩處要修正:一是 WriteEndDocument() 已經會關閉所有開啟的元素,之後再呼叫 WriteEndElement() 關 gpx 會造成順序異常,建議把 gpx 的關閉移到 WriteEndDocument 之前;二是 GPX 規範要求 time 使用 ISO 8601 格式,ToShortDateString() 這種地區性格式在 Google Earth 中會解析失敗,應改用 gpsInfo.Time.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")。
private GpxWriter _gpxWriter = null;
// 以時間戳命名,方便區分每次的軌跡
DateTime now = DateTime.Now;
string gpxName = String.Format("{0}-{1}-{2}_{3}-{4}-{5}.gpx",
now.Year, now.Month, now.Day,
now.Hour, now.Minute, now.Second);
_gpxWriter = new GpxWriter(gpxName);
// 匯出
_gpxWriter.WriteToGpx();
Windows Phone 應用若要使用定位,記得在 WMAppManifest.xml 中宣告 ID_CAP_LOCATION 能力,否則執行期會直接收到權限錯誤。另外,IsoStore 寫入的檔案需透過應用程式的檔案選擇器或分享任務才能讓使用者取得,單純寫入後使用者是看不到的。