Files
@ 0f22c89cdda0
Branch filter:
Location: seniordesign-ui/GMap.NET.Core/GMap.NET/GMaps.cs
0f22c89cdda0
22.0 KiB
text/x-csharp
further improvements and exception catches. also csv writing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 |
namespace GMap.NET
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
using GMap.NET.CacheProviders;
using GMap.NET.Internals;
using GMap.NET.MapProviders;
#if PocketPC
using OpenNETCF.ComponentModel;
using OpenNETCF.Threading;
using Thread=OpenNETCF.Threading.Thread2;
#endif
/// <summary>
/// maps manager
/// </summary>
public class GMaps : Singleton<GMaps>
{
/// <summary>
/// tile access mode
/// </summary>
public AccessMode Mode = AccessMode.ServerAndCache;
/// <summary>
/// is map ussing cache for routing
/// </summary>
public bool UseRouteCache = true;
/// <summary>
/// is map using cache for geocoder
/// </summary>
public bool UseGeocoderCache = true;
/// <summary>
/// is map using cache for directions
/// </summary>
public bool UseDirectionsCache = true;
/// <summary>
/// is map using cache for placemarks
/// </summary>
public bool UsePlacemarkCache = true;
/// <summary>
/// is map ussing cache for other url
/// </summary>
public bool UseUrlCache = true;
/// <summary>
/// is map using memory cache for tiles
/// </summary>
public bool UseMemoryCache = true;
/// <summary>
/// primary cache provider, by default: ultra fast SQLite!
/// </summary>
public PureImageCache PrimaryCache
{
get
{
return Cache.Instance.ImageCache;
}
set
{
Cache.Instance.ImageCache = value;
}
}
/// <summary>
/// secondary cache provider, by default: none,
/// use it if you have server in your local network
/// </summary>
public PureImageCache SecondaryCache
{
get
{
return Cache.Instance.ImageCacheSecond;
}
set
{
Cache.Instance.ImageCacheSecond = value;
}
}
/// <summary>
/// MemoryCache provider
/// </summary>
public readonly MemoryCache MemoryCache = new MemoryCache();
/// <summary>
/// load tiles in random sequence
/// </summary>
public bool ShuffleTilesOnLoad = false;
/// <summary>
/// tile queue to cache
/// </summary>
readonly Queue<CacheQueueItem> tileCacheQueue = new Queue<CacheQueueItem>();
bool? isRunningOnMono;
/// <summary>
/// return true if running on mono
/// </summary>
/// <returns></returns>
public bool IsRunningOnMono
{
get
{
if(!isRunningOnMono.HasValue)
{
try
{
isRunningOnMono = (Type.GetType("Mono.Runtime") != null);
return isRunningOnMono.Value;
}
catch
{
}
}
else
{
return isRunningOnMono.Value;
}
return false;
}
}
/// <summary>
/// cache worker
/// </summary>
Thread CacheEngine;
internal readonly AutoResetEvent WaitForCache = new AutoResetEvent(false);
public GMaps()
{
#region singleton check
if(Instance != null)
{
throw (new Exception("You have tried to create a new singleton class where you should have instanced it. Replace your \"new class()\" with \"class.Instance\""));
}
#endregion
ServicePointManager.DefaultConnectionLimit = 5;
}
#if !PocketPC
/// <summary>
/// triggers dynamic sqlite loading,
/// call this before you use sqlite for other reasons than caching maps
/// </summary>
public void SQLitePing()
{
#if SQLite
#if !MONO
SQLitePureImageCache.Ping();
#endif
#endif
}
#endif
#region -- Stuff --
#if !PocketPC
/// <summary>
/// exports current map cache to GMDB file
/// if file exsist only new records will be added
/// otherwise file will be created and all data exported
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public bool ExportToGMDB(string file)
{
#if SQLite
if(PrimaryCache is SQLitePureImageCache)
{
StringBuilder db = new StringBuilder((PrimaryCache as SQLitePureImageCache).GtileCache);
db.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}Data.gmdb", GMapProvider.LanguageStr, Path.DirectorySeparatorChar);
return SQLitePureImageCache.ExportMapDataToDB(db.ToString(), file);
}
#endif
return false;
}
/// <summary>
/// imports GMDB file to current map cache
/// only new records will be added
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public bool ImportFromGMDB(string file)
{
#if SQLite
if(PrimaryCache is GMap.NET.CacheProviders.SQLitePureImageCache)
{
StringBuilder db = new StringBuilder((PrimaryCache as SQLitePureImageCache).GtileCache);
db.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}Data.gmdb", GMapProvider.LanguageStr, Path.DirectorySeparatorChar);
return SQLitePureImageCache.ExportMapDataToDB(file, db.ToString());
}
#endif
return false;
}
#if SQLite
/// <summary>
/// optimizes map database, *.gmdb
/// </summary>
/// <param name="file">database file name or null to optimize current user db</param>
/// <returns></returns>
public bool OptimizeMapDb(string file)
{
if(PrimaryCache is GMap.NET.CacheProviders.SQLitePureImageCache)
{
if(string.IsNullOrEmpty(file))
{
StringBuilder db = new StringBuilder((PrimaryCache as SQLitePureImageCache).GtileCache);
db.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}Data.gmdb", GMapProvider.LanguageStr, Path.DirectorySeparatorChar);
return SQLitePureImageCache.VacuumDb(db.ToString());
}
else
{
return SQLitePureImageCache.VacuumDb(file);
}
}
return false;
}
#endif
#endif
/// <summary>
/// enqueueens tile to cache
/// </summary>
/// <param name="task"></param>
void EnqueueCacheTask(CacheQueueItem task)
{
lock(tileCacheQueue)
{
if(!tileCacheQueue.Contains(task))
{
Debug.WriteLine("EnqueueCacheTask: " + task);
tileCacheQueue.Enqueue(task);
if(CacheEngine != null && CacheEngine.IsAlive)
{
WaitForCache.Set();
}
#if PocketPC
else if(CacheEngine == null || CacheEngine.State == ThreadState.Stopped || CacheEngine.State == ThreadState.Unstarted)
#else
else if(CacheEngine == null || CacheEngine.ThreadState == System.Threading.ThreadState.Stopped || CacheEngine.ThreadState == System.Threading.ThreadState.Unstarted)
#endif
{
CacheEngine = null;
CacheEngine = new Thread(new ThreadStart(CacheEngineLoop));
CacheEngine.Name = "CacheEngine";
CacheEngine.IsBackground = false;
CacheEngine.Priority = ThreadPriority.Lowest;
abortCacheLoop = false;
CacheEngine.Start();
}
}
}
}
volatile bool abortCacheLoop = false;
internal volatile bool noMapInstances = false;
public TileCacheComplete OnTileCacheComplete;
public TileCacheStart OnTileCacheStart;
public TileCacheProgress OnTileCacheProgress;
/// <summary>
/// immediately stops background tile caching, call it if you want fast exit the process
/// </summary>
public void CancelTileCaching()
{
Debug.WriteLine("CancelTileCaching...");
abortCacheLoop = true;
lock(tileCacheQueue)
{
tileCacheQueue.Clear();
WaitForCache.Set();
}
}
int readingCache = 0;
/// <summary>
/// delays writing tiles to cache while performing reads
/// </summary>
public volatile bool CacheOnIdleRead = true;
/// <summary>
/// disables delay between saving tiles into database/cache
/// </summary>
public volatile bool BoostCacheEngine = false;
/// <summary>
/// live for cache ;}
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void CacheEngineLoop()
{
Debug.WriteLine("CacheEngine: start");
int left = 0;
if(OnTileCacheStart != null)
{
OnTileCacheStart();
}
bool startEvent = false;
while(!abortCacheLoop)
{
try
{
CacheQueueItem? task = null;
lock(tileCacheQueue)
{
left = tileCacheQueue.Count;
if(left > 0)
{
task = tileCacheQueue.Dequeue();
}
}
if(task.HasValue)
{
if(startEvent)
{
startEvent = false;
if(OnTileCacheStart != null)
{
OnTileCacheStart();
}
}
if(OnTileCacheProgress != null)
{
OnTileCacheProgress(left);
}
#region -- save --
// check if stream wasn't disposed somehow
if(task.Value.Img != null)
{
Debug.WriteLine("CacheEngine[" + left + "]: storing tile " + task.Value + ", " + task.Value.Img.Length / 1024 + "kB...");
if((task.Value.CacheType & CacheUsage.First) == CacheUsage.First && PrimaryCache != null)
{
if(CacheOnIdleRead)
{
while(Interlocked.Decrement(ref readingCache) > 0)
{
Thread.Sleep(1000);
}
}
PrimaryCache.PutImageToCache(task.Value.Img, task.Value.Tile.Type, task.Value.Tile.Pos, task.Value.Tile.Zoom);
}
if((task.Value.CacheType & CacheUsage.Second) == CacheUsage.Second && SecondaryCache != null)
{
if(CacheOnIdleRead)
{
while(Interlocked.Decrement(ref readingCache) > 0)
{
Thread.Sleep(1000);
}
}
SecondaryCache.PutImageToCache(task.Value.Img, task.Value.Tile.Type, task.Value.Tile.Pos, task.Value.Tile.Zoom);
}
task.Value.Clear();
if(!BoostCacheEngine)
{
#if PocketPC
Thread.Sleep(3333);
#else
Thread.Sleep(333);
#endif
}
}
else
{
Debug.WriteLine("CacheEngineLoop: skip, tile disposed to early -> " + task.Value);
}
task = null;
#endregion
}
else
{
if(!startEvent)
{
startEvent = true;
if(OnTileCacheComplete != null)
{
OnTileCacheComplete();
}
}
if(abortCacheLoop || noMapInstances || !WaitForCache.WaitOne(33333, false) || noMapInstances)
{
break;
}
}
}
#if !PocketPC
catch(AbandonedMutexException)
{
break;
}
#endif
catch(Exception ex)
{
Debug.WriteLine("CacheEngineLoop: " + ex.ToString());
}
}
Debug.WriteLine("CacheEngine: stop");
if(!startEvent)
{
if(OnTileCacheComplete != null)
{
OnTileCacheComplete();
}
}
}
class StringWriterExt : StringWriter
{
public StringWriterExt(IFormatProvider info)
: base(info)
{
}
public override Encoding Encoding
{
get
{
return Encoding.UTF8;
}
}
}
public string SerializeGPX(gpxType targetInstance)
{
string retVal = string.Empty;
using(StringWriterExt writer = new StringWriterExt(CultureInfo.InvariantCulture))
{
XmlSerializer serializer = new XmlSerializer(targetInstance.GetType());
serializer.Serialize(writer, targetInstance);
retVal = writer.ToString();
}
return retVal;
}
public gpxType DeserializeGPX(string objectXml)
{
gpxType retVal = null;
using(StringReader stringReader = new StringReader(objectXml))
{
XmlTextReader xmlReader = new XmlTextReader(stringReader);
XmlSerializer serializer = new XmlSerializer(typeof(gpxType));
retVal = serializer.Deserialize(xmlReader) as gpxType;
xmlReader.Close();
}
return retVal;
}
/// <summary>
/// exports gps data to gpx file
/// </summary>
/// <param name="log">gps data</param>
/// <param name="gpxFile">file to export</param>
/// <returns>true if success</returns>
public bool ExportGPX(IEnumerable<List<GpsLog>> log, string gpxFile)
{
try
{
gpxType gpx = new gpxType();
{
gpx.creator = "GMap.NET - http://greatmaps.codeplex.com";
gpx.trk = new trkType[1];
gpx.trk[0] = new trkType();
}
var sessions = new List<List<GpsLog>>(log);
gpx.trk[0].trkseg = new trksegType[sessions.Count];
int sesid = 0;
foreach(var session in sessions)
{
trksegType seg = new trksegType();
{
seg.trkpt = new wptType[session.Count];
}
gpx.trk[0].trkseg[sesid++] = seg;
for(int i = 0; i < session.Count; i++)
{
var point = session[i];
wptType t = new wptType();
{
#region -- set values --
t.lat = new decimal(point.Position.Lat);
t.lon = new decimal(point.Position.Lng);
t.time = point.TimeUTC;
t.timeSpecified = true;
if(point.FixType != FixType.Unknown)
{
t.fix = (point.FixType == FixType.XyD ? fixType.Item2d : fixType.Item3d);
t.fixSpecified = true;
}
if(point.SeaLevelAltitude.HasValue)
{
t.ele = new decimal(point.SeaLevelAltitude.Value);
t.eleSpecified = true;
}
if(point.EllipsoidAltitude.HasValue)
{
t.geoidheight = new decimal(point.EllipsoidAltitude.Value);
t.geoidheightSpecified = true;
}
if(point.VerticalDilutionOfPrecision.HasValue)
{
t.vdopSpecified = true;
t.vdop = new decimal(point.VerticalDilutionOfPrecision.Value);
}
if(point.HorizontalDilutionOfPrecision.HasValue)
{
t.hdopSpecified = true;
t.hdop = new decimal(point.HorizontalDilutionOfPrecision.Value);
}
if(point.PositionDilutionOfPrecision.HasValue)
{
t.pdopSpecified = true;
t.pdop = new decimal(point.PositionDilutionOfPrecision.Value);
}
if(point.SatelliteCount.HasValue)
{
t.sat = point.SatelliteCount.Value.ToString();
}
#endregion
}
seg.trkpt[i] = t;
}
}
sessions.Clear();
#if !PocketPC
File.WriteAllText(gpxFile, SerializeGPX(gpx), Encoding.UTF8);
#else
using(StreamWriter w = File.CreateText(gpxFile))
{
w.Write(SerializeGPX(gpx));
w.Close();
}
#endif
}
catch(Exception ex)
{
Debug.WriteLine("ExportGPX: " + ex.ToString());
return false;
}
return true;
}
#endregion
/// <summary>
/// gets image from tile server
/// </summary>
/// <param name="provider"></param>
/// <param name="pos"></param>
/// <param name="zoom"></param>
/// <returns></returns>
public PureImage GetImageFrom(GMapProvider provider, GPoint pos, int zoom, out Exception result)
{
PureImage ret = null;
result = null;
try
{
var rtile = new RawTile(provider.DbId, pos, zoom);
// let't check memmory first
if(UseMemoryCache)
{
var m = MemoryCache.GetTileFromMemoryCache(rtile);
if(m != null)
{
if(GMapProvider.TileImageProxy != null)
{
ret = GMapProvider.TileImageProxy.FromArray(m);
if(ret == null)
{
#if DEBUG
Debug.WriteLine("Image disposed in MemoryCache o.O, should never happen ;} " + new RawTile(provider.DbId, pos, zoom));
if(Debugger.IsAttached)
{
Debugger.Break();
}
#endif
m = null;
}
}
}
}
if(ret == null)
{
if(Mode != AccessMode.ServerOnly)
{
if(PrimaryCache != null)
{
// hold writer for 5s
if(CacheOnIdleRead)
{
Interlocked.Exchange(ref readingCache, 5);
}
ret = PrimaryCache.GetImageFromCache(provider.DbId, pos, zoom);
if(ret != null)
{
if(UseMemoryCache)
{
MemoryCache.AddTileToMemoryCache(rtile, ret.Data.GetBuffer());
}
return ret;
}
}
if(SecondaryCache != null)
{
// hold writer for 5s
if(CacheOnIdleRead)
{
Interlocked.Exchange(ref readingCache, 5);
}
ret = SecondaryCache.GetImageFromCache(provider.DbId, pos, zoom);
if(ret != null)
{
if(UseMemoryCache)
{
MemoryCache.AddTileToMemoryCache(rtile, ret.Data.GetBuffer());
}
EnqueueCacheTask(new CacheQueueItem(rtile, ret.Data.GetBuffer(), CacheUsage.First));
return ret;
}
}
}
if(Mode != AccessMode.CacheOnly)
{
ret = provider.GetTileImage(pos, zoom);
{
// Enqueue Cache
if(ret != null)
{
if(UseMemoryCache)
{
MemoryCache.AddTileToMemoryCache(rtile, ret.Data.GetBuffer());
}
if(Mode != AccessMode.ServerOnly)
{
EnqueueCacheTask(new CacheQueueItem(rtile, ret.Data.GetBuffer(), CacheUsage.Both));
}
}
}
}
else
{
result = noDataException;
}
}
}
catch(Exception ex)
{
result = ex;
ret = null;
Debug.WriteLine("GetImageFrom: " + ex.ToString());
}
return ret;
}
readonly Exception noDataException = new Exception("No data in local tile cache...");
}
}
|