Subversion Repositories Projects

Compare Revisions

Ignore whitespace Rev 2288 → Rev 2289

/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/AccessMode.cs
0,0 → 1,24

namespace GMap.NET
{
/// <summary>
/// tile access mode
/// </summary>
public enum AccessMode
{
/// <summary>
/// access only server
/// </summary>
ServerOnly,
 
/// <summary>
/// access first server and caches localy
/// </summary>
ServerAndCache,
 
/// <summary>
/// access only cache
/// </summary>
CacheOnly,
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/Delegates.cs
0,0 → 1,20

namespace GMap.NET
{
using GMap.NET.MapProviders;
 
public delegate void PositionChanged(PointLatLng point);
 
public delegate void TileLoadComplete(long ElapsedMilliseconds);
public delegate void TileLoadStart();
 
public delegate void TileCacheComplete();
public delegate void TileCacheStart();
public delegate void TileCacheProgress(int tilesLeft);
 
public delegate void MapDrag();
public delegate void MapZoomChanged();
public delegate void MapTypeChanged(GMapProvider type);
 
public delegate void EmptyTileError(int zoom, GPoint pos);
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/DirectionsProvider.cs
0,0 → 1,47

namespace GMap.NET
{
using System.Collections.Generic;
 
/// <summary>
/// directions interface
/// </summary>
interface DirectionsProvider
{
DirectionsStatusCode GetDirections(out GDirections direction, PointLatLng start, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric);
 
DirectionsStatusCode GetDirections(out GDirections direction, string start, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric);
 
/// <summary>
/// service may provide more than one route alternative in the response
/// </summary>
/// <param name="status"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="avoidHighways"></param>
/// <param name="avoidTolls"></param>
/// <param name="walkingMode"></param>
/// <param name="sensor"></param>
/// <param name="metric"></param>
/// <returns></returns>
IEnumerable<GDirections> GetDirections(out DirectionsStatusCode status, string start, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric);
 
/// <summary>
/// service may provide more than one route alternative in the response
/// </summary>
/// <param name="status"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="avoidHighways"></param>
/// <param name="avoidTolls"></param>
/// <param name="walkingMode"></param>
/// <param name="sensor"></param>
/// <param name="metric"></param>
/// <returns></returns>
IEnumerable<GDirections> GetDirections(out DirectionsStatusCode status, PointLatLng start, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric);
 
DirectionsStatusCode GetDirections(out GDirections direction, PointLatLng start, IEnumerable<PointLatLng> wayPoints, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric);
 
DirectionsStatusCode GetDirections(out GDirections direction, string start, IEnumerable<string> wayPoints, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric);
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/Extensions.cs
0,0 → 1,92

namespace GMap.NET
{
using System;
using System.Runtime.Serialization;
using System.Diagnostics;
 
public static class Extensions
{
/// <summary>
/// Retrieves a value from the SerializationInfo of the given type.
/// </summary>
/// <typeparam name="T">The Type that we are attempting to de-serialize.</typeparam>
/// <param name="info">The SerializationInfo.</param>
/// <param name="key">The key of the value we wish to retrieve.</param>
/// <returns>The value if found, otherwise null.</returns>
public static T GetValue<T>(SerializationInfo info, string key) where T : class
{
try
{
// Return the value from the SerializationInfo, casting it to type T.
return info.GetValue(key, typeof(T)) as T;
}
catch(Exception ex)
{
Debug.WriteLine("Extensions.GetValue: " + ex.Message);
return null;
}
}
 
/// <summary>
/// Retrieves a value from the SerializationInfo of the given type.
/// </summary>
/// <typeparam name="T">The Type that we are attempting to de-serialize.</typeparam>
/// <param name="info">The SerializationInfo.</param>
/// <param name="key">The key of the value we wish to retrieve.</param>
/// <param name="defaultValue">The default value if the de-serialized value was null.</param>
/// <returns>The value if found, otherwise the default value.</returns>
public static T GetValue<T>(SerializationInfo info, string key, T defaultValue) where T : class
{
T deserializedValue = GetValue<T>(info, key);
if(deserializedValue != null)
{
return deserializedValue;
}
 
return defaultValue;
}
 
/// <summary>
/// Retrieves a value from the SerializationInfo of the given type for structs.
/// </summary>
/// <typeparam name="T">The Type that we are attempting to de-serialize.</typeparam>
/// <param name="info">The SerializationInfo.</param>
/// <param name="key">The key of the value we wish to retrieve.</param>
/// <param name="defaultValue">The default value if the de-serialized value was null.</param>
/// <returns>The value if found, otherwise the default value.</returns>
public static T GetStruct<T>(SerializationInfo info, string key, T defaultValue) where T : struct
{
try
{
return (T)info.GetValue(key, typeof(T));
}
catch(Exception ex)
{
Debug.WriteLine("Extensions.GetStruct: " + ex.Message);
return defaultValue;
}
}
 
/// <summary>
/// Retrieves a value from the SerializationInfo of the given type for structs.
/// </summary>
/// <typeparam name="T">The Type that we are attempting to de-serialize.</typeparam>
/// <param name="info">The SerializationInfo.</param>
/// <param name="key">The key of the value we wish to retrieve.</param>
/// <param name="defaultValue">The default value if the de-serialized value was null.</param>
/// <returns>The value if found, otherwise the default value.</returns>
public static Nullable<T> GetStruct<T>(SerializationInfo info, string key, Nullable<T> defaultValue) where T : struct
{
try
{
return (Nullable<T>)info.GetValue(key, typeof(Nullable<T>));
}
catch(Exception ex)
{
Debug.WriteLine("Extensions.GetStruct: " + ex.Message);
return defaultValue;
}
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/GDirections.cs
0,0 → 1,121

namespace GMap.NET
{
using System.Collections.Generic;
 
public class GDirections
{
/// <summary>
/// contains a short textual description for the route, suitable for naming and disambiguating the route from alternatives.
/// </summary>
public string Summary;
 
/// <summary>
/// contains a human-readable representation of the duration.
/// </summary>
public string Duration;
 
/// <summary>
/// contains a value of the duration.
/// </summary>
public uint DurationValue;
 
/// <summary>
/// contains a human-readable representation of the distance, displayed in units as used at the origin
/// (or as overridden within the units parameter in the request), in the language specified in the request.
/// (For example, miles and feet will be used for any origin within the United States.)
/// </summary>
public string Distance;
 
/// <summary>
/// contains a value of the distance.
/// </summary>
public uint DistanceValue;
 
/// <summary>
/// contains the latitude/longitude coordinates of the origin of this leg. Because the Directions API
/// calculates directions between locations by using the nearest transportation option (usually a road)
/// at the start and end points, start_location may be different than the provided origin of this leg if,
/// for example, a road is not near the origin.
/// </summary>
public PointLatLng StartLocation;
 
/// <summary>
/// contains the latitude/longitude coordinates of the given destination of this leg. Because the Directions
/// API calculates directions between locations by using the nearest transportation option (usually a road)
/// at the start and end points, end_location may be different than the provided destination of this leg if,
/// for example, a road is not near the destination.
/// </summary>
public PointLatLng EndLocation;
 
/// <summary>
/// contains the human-readable address (typically a street address) reflecting the start_location of this leg.
/// </summary>
public string StartAddress;
 
/// <summary>
/// contains the human-readable address (typically a street address) reflecting the end_location of this leg.
/// </summary>
public string EndAddress;
 
/// <summary>
/// contains the copyrights text to be displayed for this route. You must handle and display this information yourself.
/// </summary>
public string Copyrights;
 
/// <summary>
/// contains an array of steps denoting information about each separate step of the leg of the journey.
/// </summary>
public List<GDirectionStep> Steps;
 
/// <summary>
/// contains all points of the route
/// </summary>
public List<PointLatLng> Route;
 
public override string ToString()
{
return Summary + " | " + Distance + " | " + Duration;
}
}
 
public struct GDirectionStep
{
public string TravelMode;
 
/// <summary>
/// contains the location of the starting point of this step, as a single set of lat and lng fields.
/// </summary>
public PointLatLng StartLocation;
 
/// <summary>
/// contains the location of the ending point of this step, as a single set of lat and lng fields.
/// </summary>
public PointLatLng EndLocation;
 
/// <summary>
/// contains the typical time required to perform the step, until the next step. This field may be undefined if the duration is unknown.
/// </summary>
public string Duration;
 
/// <summary>
/// contains the distance covered by this step until the next step. This field may be undefined if the distance is unknown.
/// </summary>
public string Distance;
 
/// <summary>
/// contains formatted instructions for this step, presented as an HTML text string.
/// </summary>
public string HtmlInstructions;
 
/// <summary>
/// points of the step
/// </summary>
public List<PointLatLng> Points;
 
public override string ToString()
{
return TravelMode + " | " + Distance + " | " + Duration + " | " + HtmlInstructions;
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/GMaps.cs
0,0 → 1,849

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;
using System.Reflection;
 
#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);
 
#if !PocketPC
static GMaps()
{
if (GMapProvider.TileImageProxy == null)
{
try
{
AppDomain d = AppDomain.CurrentDomain;
var AssembliesLoaded = d.GetAssemblies();
 
Assembly l = null;
 
foreach (var a in AssembliesLoaded)
{
if (a.FullName.Contains("GMap.NET.WindowsForms") || a.FullName.Contains("GMap.NET.WindowsPresentation"))
{
l = a;
break;
}
}
 
if (l == null)
{
var jj = Assembly.GetExecutingAssembly().Location;
var hh = Path.GetDirectoryName(jj);
var f1 = hh + Path.DirectorySeparatorChar + "GMap.NET.WindowsForms.dll";
var f2 = hh + Path.DirectorySeparatorChar + "GMap.NET.WindowsPresentation.dll";
if (File.Exists(f1))
{
l = Assembly.LoadFile(f1);
}
else if (File.Exists(f2))
{
l = Assembly.LoadFile(f2);
}
}
 
if (l != null)
{
Type t = null;
 
if (l.FullName.Contains("GMap.NET.WindowsForms"))
{
t = l.GetType("GMap.NET.WindowsForms.GMapImageProxy");
}
else if (l.FullName.Contains("GMap.NET.WindowsPresentation"))
{
t = l.GetType("GMap.NET.WindowsPresentation.GMapImageProxy");
}
 
if (t != null)
{
t.InvokeMember("Enable", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, null);
}
}
}
catch (Exception ex)
{
Debug.WriteLine("GMaps, try set TileImageProxy failed: " + ex.Message);
}
}
}
#endif
 
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;
volatile bool cacheOnIdleRead = true;
 
/// <summary>
/// delays writing tiles to cache while performing reads
/// </summary>
public bool CacheOnIdleRead
{
get
{
return cacheOnIdleRead;
}
set
{
cacheOnIdleRead = value;
}
}
 
volatile bool boostCacheEngine = false;
 
/// <summary>
/// disables delay between saving tiles into database/cache
/// </summary>
public bool BoostCacheEngine
{
get
{
return boostCacheEngine;
}
set
{
boostCacheEngine = value;
}
}
 
/// <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 && !provider.BypassCache)
{
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 && !provider.BypassCache)
{
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...");
 
#if !PocketPC
TileHttpHost host;
 
/// <summary>
/// turns on tile host
/// </summary>
/// <param name="port"></param>
public void EnableTileHost(int port)
{
if(host == null)
{
host = new TileHttpHost();
}
host.Start(port);
}
 
/// <summary>
/// turns off tile host
/// </summary>
/// <param name="port"></param>
public void DisableTileHost()
{
if (host != null)
{
host.Stop();
}
}
#endif
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/GPoint.cs
0,0 → 1,160
 
namespace GMap.NET
{
using System.Globalization;
using System;
using System.Collections.Generic;
 
/// <summary>
/// the point ;}
/// </summary>
[Serializable]
public struct GPoint
{
public static readonly GPoint Empty = new GPoint();
 
private long x;
private long y;
 
public GPoint(long x, long y)
{
this.x = x;
this.y = y;
}
 
public GPoint(GSize sz)
{
this.x = sz.Width;
this.y = sz.Height;
}
 
//public GPoint(int dw)
//{
// this.x = (short) LOWORD(dw);
// this.y = (short) HIWORD(dw);
//}
 
public bool IsEmpty
{
get
{
return x == 0 && y == 0;
}
}
 
public long X
{
get
{
return x;
}
set
{
x = value;
}
}
 
public long Y
{
get
{
return y;
}
set
{
y = value;
}
}
 
public static explicit operator GSize(GPoint p)
{
return new GSize(p.X, p.Y);
}
 
public static GPoint operator+(GPoint pt, GSize sz)
{
return Add(pt, sz);
}
 
public static GPoint operator-(GPoint pt, GSize sz)
{
return Subtract(pt, sz);
}
 
public static bool operator==(GPoint left, GPoint right)
{
return left.X == right.X && left.Y == right.Y;
}
 
public static bool operator!=(GPoint left, GPoint right)
{
return !(left == right);
}
 
public static GPoint Add(GPoint pt, GSize sz)
{
return new GPoint(pt.X + sz.Width, pt.Y + sz.Height);
}
 
public static GPoint Subtract(GPoint pt, GSize sz)
{
return new GPoint(pt.X - sz.Width, pt.Y - sz.Height);
}
 
public override bool Equals(object obj)
{
if(!(obj is GPoint))
return false;
GPoint comp = (GPoint) obj;
return comp.X == this.X && comp.Y == this.Y;
}
 
public override int GetHashCode()
{
return (int)(x ^ y);
}
 
public void Offset(long dx, long dy)
{
X += dx;
Y += dy;
}
 
public void Offset(GPoint p)
{
Offset(p.X, p.Y);
}
public void OffsetNegative(GPoint p)
{
Offset(-p.X, -p.Y);
}
 
public override string ToString()
{
return "{X=" + X.ToString(CultureInfo.CurrentCulture) + ",Y=" + Y.ToString(CultureInfo.CurrentCulture) + "}";
}
 
//private static int HIWORD(int n)
//{
// return (n >> 16) & 0xffff;
//}
 
//private static int LOWORD(int n)
//{
// return n & 0xffff;
//}
}
 
internal class GPointComparer : IEqualityComparer<GPoint>
{
public bool Equals(GPoint x, GPoint y)
{
return x.X == y.X && x.Y == y.Y;
}
 
public int GetHashCode(GPoint obj)
{
return obj.GetHashCode();
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/GRect.cs
0,0 → 1,324
 
namespace GMap.NET
{
using System;
using System.Globalization;
 
/// <summary>
/// the rect
/// </summary>
public struct GRect
{
public static readonly GRect Empty = new GRect();
 
private long x;
private long y;
private long width;
private long height;
 
public GRect(long x, long y, long width, long height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
 
public GRect(GPoint location, GSize size)
{
this.x = location.X;
this.y = location.Y;
this.width = size.Width;
this.height = size.Height;
}
 
public static GRect FromLTRB(int left, int top, int right, int bottom)
{
return new GRect(left,
top,
right - left,
bottom - top);
}
 
public GPoint Location
{
get
{
return new GPoint(X, Y);
}
set
{
X = value.X;
Y = value.Y;
}
}
 
public GPoint RightBottom
{
get
{
return new GPoint(Right, Bottom);
}
}
 
public GPoint RightTop
{
get
{
return new GPoint(Right, Top);
}
}
 
public GPoint LeftBottom
{
get
{
return new GPoint(Left, Bottom);
}
}
 
public GSize Size
{
get
{
return new GSize(Width, Height);
}
set
{
this.Width = value.Width;
this.Height = value.Height;
}
}
 
public long X
{
get
{
return x;
}
set
{
x = value;
}
}
 
public long Y
{
get
{
return y;
}
set
{
y = value;
}
}
 
public long Width
{
get
{
return width;
}
set
{
width = value;
}
}
 
public long Height
{
get
{
return height;
}
set
{
height = value;
}
}
 
public long Left
{
get
{
return X;
}
}
 
public long Top
{
get
{
return Y;
}
}
 
public long Right
{
get
{
return X + Width;
}
}
 
public long Bottom
{
get
{
return Y + Height;
}
}
 
public bool IsEmpty
{
get
{
return height == 0 && width == 0 && x == 0 && y == 0;
}
}
 
public override bool Equals(object obj)
{
if(!(obj is GRect))
return false;
 
GRect comp = (GRect) obj;
 
return (comp.X == this.X) &&
(comp.Y == this.Y) &&
(comp.Width == this.Width) &&
(comp.Height == this.Height);
}
 
public static bool operator==(GRect left, GRect right)
{
return (left.X == right.X
&& left.Y == right.Y
&& left.Width == right.Width
&& left.Height == right.Height);
}
 
public static bool operator!=(GRect left, GRect right)
{
return !(left == right);
}
 
public bool Contains(long x, long y)
{
return this.X <= x &&
x < this.X + this.Width &&
this.Y <= y &&
y < this.Y + this.Height;
}
 
public bool Contains(GPoint pt)
{
return Contains(pt.X, pt.Y);
}
 
public bool Contains(GRect rect)
{
return (this.X <= rect.X) &&
((rect.X + rect.Width) <= (this.X + this.Width)) &&
(this.Y <= rect.Y) &&
((rect.Y + rect.Height) <= (this.Y + this.Height));
}
 
public override int GetHashCode()
{
if(this.IsEmpty)
{
return 0;
}
return (int)(((this.X ^ ((this.Y << 13) | (this.Y >> 0x13))) ^ ((this.Width << 0x1a) | (this.Width >> 6))) ^ ((this.Height << 7) | (this.Height >> 0x19)));
}
 
public void Inflate(long width, long height)
{
this.X -= width;
this.Y -= height;
this.Width += 2*width;
this.Height += 2*height;
}
 
public void Inflate(GSize size)
{
Inflate(size.Width, size.Height);
}
 
public static GRect Inflate(GRect rect, long x, long y)
{
GRect r = rect;
r.Inflate(x, y);
return r;
}
 
public void Intersect(GRect rect)
{
GRect result = GRect.Intersect(rect, this);
 
this.X = result.X;
this.Y = result.Y;
this.Width = result.Width;
this.Height = result.Height;
}
 
public static GRect Intersect(GRect a, GRect b)
{
long x1 = Math.Max(a.X, b.X);
long x2 = Math.Min(a.X + a.Width, b.X + b.Width);
long y1 = Math.Max(a.Y, b.Y);
long y2 = Math.Min(a.Y + a.Height, b.Y + b.Height);
 
if(x2 >= x1
&& y2 >= y1)
{
 
return new GRect(x1, y1, x2 - x1, y2 - y1);
}
return GRect.Empty;
}
 
public bool IntersectsWith(GRect rect)
{
return (rect.X < this.X + this.Width) &&
(this.X < (rect.X + rect.Width)) &&
(rect.Y < this.Y + this.Height) &&
(this.Y < rect.Y + rect.Height);
}
 
public static GRect Union(GRect a, GRect b)
{
long x1 = Math.Min(a.X, b.X);
long x2 = Math.Max(a.X + a.Width, b.X + b.Width);
long y1 = Math.Min(a.Y, b.Y);
long y2 = Math.Max(a.Y + a.Height, b.Y + b.Height);
 
return new GRect(x1, y1, x2 - x1, y2 - y1);
}
 
public void Offset(GPoint pos)
{
Offset(pos.X, pos.Y);
}
 
public void OffsetNegative(GPoint pos)
{
Offset(-pos.X, -pos.Y);
}
 
public void Offset(long x, long y)
{
this.X += x;
this.Y += y;
}
 
public override string ToString()
{
return "{X=" + X.ToString(CultureInfo.CurrentCulture) + ",Y=" + Y.ToString(CultureInfo.CurrentCulture) +
",Width=" + Width.ToString(CultureInfo.CurrentCulture) +
",Height=" + Height.ToString(CultureInfo.CurrentCulture) + "}";
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/GSize.cs
0,0 → 1,121
 
namespace GMap.NET
{
using System.Globalization;
 
/// <summary>
/// the size
/// </summary>
public struct GSize
{
public static readonly GSize Empty = new GSize();
 
private long width;
private long height;
 
public GSize(GPoint pt)
{
width = pt.X;
height = pt.Y;
}
 
public GSize(long width, long height)
{
this.width = width;
this.height = height;
}
 
public static GSize operator +(GSize sz1, GSize sz2)
{
return Add(sz1, sz2);
}
 
public static GSize operator -(GSize sz1, GSize sz2)
{
return Subtract(sz1, sz2);
}
 
public static bool operator ==(GSize sz1, GSize sz2)
{
return sz1.Width == sz2.Width && sz1.Height == sz2.Height;
}
 
public static bool operator !=(GSize sz1, GSize sz2)
{
return !(sz1 == sz2);
}
 
public static explicit operator GPoint(GSize size)
{
return new GPoint(size.Width, size.Height);
}
 
public bool IsEmpty
{
get
{
return width == 0 && height == 0;
}
}
 
public long Width
{
get
{
return width;
}
set
{
width = value;
}
}
 
public long Height
{
get
{
return height;
}
set
{
height = value;
}
}
 
public static GSize Add(GSize sz1, GSize sz2)
{
return new GSize(sz1.Width + sz2.Width, sz1.Height + sz2.Height);
}
 
public static GSize Subtract(GSize sz1, GSize sz2)
{
return new GSize(sz1.Width - sz2.Width, sz1.Height - sz2.Height);
}
 
public override bool Equals(object obj)
{
if(!(obj is GSize))
return false;
 
GSize comp = (GSize)obj;
// Note value types can't have derived classes, so we don't need to
//
return (comp.width == this.width) &&
(comp.height == this.height);
}
 
public override int GetHashCode()
{
if(this.IsEmpty)
{
return 0;
}
return (Width.GetHashCode() ^ Height.GetHashCode());
}
 
public override string ToString()
{
return "{Width=" + width.ToString(CultureInfo.CurrentCulture) + ", Height=" + height.ToString(CultureInfo.CurrentCulture) + "}";
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/GeocodingProvider.cs
0,0 → 1,25

namespace GMap.NET
{
using System.Collections.Generic;
 
/// <summary>
/// geocoding interface
/// </summary>
public interface GeocodingProvider
{
GeoCoderStatusCode GetPoints(string keywords, out List<PointLatLng> pointList);
 
PointLatLng? GetPoint(string keywords, out GeoCoderStatusCode status);
 
GeoCoderStatusCode GetPoints(Placemark placemark, out List<PointLatLng> pointList);
 
PointLatLng? GetPoint(Placemark placemark, out GeoCoderStatusCode status);
 
// ...
 
GeoCoderStatusCode GetPlacemarks(PointLatLng location, out List<Placemark> placemarkList);
 
Placemark ? GetPlacemark(PointLatLng location, out GeoCoderStatusCode status);
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/GpsLog.cs
0,0 → 1,49

namespace GMap.NET
{
using System;
 
public struct GpsLog
{
public DateTime TimeUTC;
public long SessionCounter;
public double? Delta;
public double? Speed;
public double? SeaLevelAltitude;
public double? EllipsoidAltitude;
public short? SatellitesInView;
public short? SatelliteCount;
public PointLatLng Position;
public double? PositionDilutionOfPrecision;
public double? HorizontalDilutionOfPrecision;
public double? VerticalDilutionOfPrecision;
public FixQuality FixQuality;
public FixType FixType;
public FixSelection FixSelection;
 
public override string ToString()
{
return string.Format("{0}: {1}", SessionCounter, TimeUTC);
}
}
 
public enum FixQuality : int
{
Unknown=0,
Gps,
DGps
}
public enum FixType : int
{
Unknown=0,
XyD,
XyzD
}
 
public enum FixSelection : int
{
Unknown=0,
Auto,
Manual
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/Interface.cs
0,0 → 1,72

namespace GMap.NET
{
using GMap.NET.MapProviders;
 
public interface Interface
{
PointLatLng Position
{
get;
set;
}
 
GPoint PositionPixel
{
get;
}
 
string CacheLocation
{
get;
set;
}
 
bool IsDragging
{
get;
}
 
RectLatLng ViewArea
{
get;
}
 
GMapProvider MapProvider
{
get;
set;
}
 
bool CanDragMap
{
get;
set;
}
 
RenderMode RenderMode
{
get;
}
 
// events
event PositionChanged OnPositionChanged;
event TileLoadComplete OnTileLoadComplete;
event TileLoadStart OnTileLoadStart;
event MapDrag OnMapDrag;
event MapZoomChanged OnMapZoomChanged;
event MapTypeChanged OnMapTypeChanged;
 
void ReloadMap();
 
PointLatLng FromLocalToLatLng(int x, int y);
GPoint FromLatLngToLocal(PointLatLng point);
 
#if !PocketPC
#if SQLite
bool ShowExportDialog();
bool ShowImportDialog();
#endif
#endif
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/LanguageType.cs
0,0 → 1,179

namespace GMap.NET
{
using System.ComponentModel;
 
/// <summary>
/// This enum contains all possible languages for the Google maps.
/// You can find latest information about supported languages in the:
/// http://tinyurl.com/yh4va36 <- http://spreadsheets.server.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1
/// </summary>
public enum LanguageType
{
[Description("ar")]
Arabic,
 
[Description("bg")]
Bulgarian,
 
[Description("bn")]
Bengali,
 
[Description("ca")]
Catalan,
 
[Description("cs")]
Czech,
 
[Description("da")]
Danish,
 
[Description("de")]
German,
 
[Description("el")]
Greek,
 
[Description("en")]
English,
 
[Description("en-AU")]
EnglishAustralian,
 
[Description("en-GB")]
EnglishGreatBritain,
 
[Description("es")]
Spanish,
 
[Description("eu")]
Basque,
 
[Description("fa")]
FARSI,
 
[Description("fi")]
Finnish,
 
[Description("fil")]
Filipino,
 
[Description("fr")]
French,
 
[Description("gl")]
Galician,
 
[Description("gu")]
Gujarati,
[Description("hi")]
Hindi,
 
[Description("hr")]
Croatian,
 
[Description("hu")]
Hungarian,
 
[Description("id")]
Indonesian,
 
[Description("it")]
Italian,
 
[Description("iw")]
Hebrew,
 
[Description("ja")]
Japanese,
 
[Description("kn")]
Kannada,
 
[Description("ko")]
Korean,
 
[Description("lt")]
Lithuanian,
 
[Description("lv")]
Latvian,
 
[Description("ml")]
Malayalam,
 
[Description("mr")]
Marathi,
 
[Description("nl")]
Dutch,
 
[Description("nn")]
NorwegianNynorsk,
 
[Description("no")]
Norwegian,
 
[Description("or")]
Oriya,
 
[Description("pl")]
Polish,
 
[Description("pt")]
Portuguese,
 
[Description("pt-BR")]
PortugueseBrazil,
 
[Description("pt-PT")]
PortuguesePortugal,
 
[Description("rm")]
Romansch,
[Description("ro")]
Romanian,
 
[Description("ru")]
Russian,
 
[Description("sk")]
Slovak,
 
[Description("sl")]
Slovenian,
 
[Description("sr")]
Serbian,
 
[Description("sv")]
Swedish,
 
[Description("tl")]
TAGALOG,
 
[Description("ta")]
Tamil,
 
[Description("te")]
Telugu,
 
[Description("th")]
Thai,
 
[Description("tr")]
Turkish,
 
[Description("uk")]
Ukrainian,
 
[Description("vi")]
Vietnamese,
 
[Description("zh-CN")]
ChineseSimplified,
 
[Description("zh-TW")]
ChineseTraditional,
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/MapRoute.cs
0,0 → 1,160

namespace GMap.NET
{
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using GMap.NET.MapProviders;
 
/// <summary>
/// represents route of map
/// </summary>
[Serializable]
#if !PocketPC
public class MapRoute : ISerializable, IDeserializationCallback
#else
public class MapRoute
#endif
{
/// <summary>
/// points of route
/// </summary>
public readonly List<PointLatLng> Points = new List<PointLatLng>();
 
/// <summary>
/// route info
/// </summary>
public string Name;
 
/// <summary>
/// custom object
/// </summary>
public object Tag;
 
/// <summary>
/// route start point
/// </summary>
public PointLatLng? From
{
get
{
if(Points.Count > 0)
{
return Points[0];
}
 
return null;
}
}
 
/// <summary>
/// route end point
/// </summary>
public PointLatLng? To
{
get
{
if(Points.Count > 1)
{
return Points[Points.Count - 1];
}
 
return null;
}
}
 
public MapRoute(string name)
{
Name = name;
}
 
public MapRoute(IEnumerable<PointLatLng> points, string name)
{
Points.AddRange(points);
Name = name;
}
 
/// <summary>
/// route distance (in km)
/// </summary>
public double Distance
{
get
{
double distance = 0.0;
 
if(From.HasValue && To.HasValue)
{
for(int i = 1; i < Points.Count; i++)
{
distance += GMapProviders.EmptyProvider.Projection.GetDistance(Points[i - 1], Points[i]);
}
}
 
return distance;
}
}
 
/// <summary>
/// clears points and sets tag and name to null
/// </summary>
public void Clear()
{
Points.Clear();
Tag = null;
Name = null;
}
 
#if !PocketPC
#region ISerializable Members
 
// Temp store for de-serialization.
private PointLatLng[] deserializedPoints;
 
/// <summary>
/// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> to populate with data.</param>
/// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for this serialization.</param>
/// <exception cref="T:System.Security.SecurityException">
/// The caller does not have the required permission.
/// </exception>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", this.Name);
info.AddValue("Tag", this.Tag);
info.AddValue("Points", this.Points.ToArray());
}
 
/// <summary>
/// Initializes a new instance of the <see cref="MapRoute"/> class.
/// </summary>
/// <param name="info">The info.</param>
/// <param name="context">The context.</param>
protected MapRoute(SerializationInfo info, StreamingContext context)
{
this.Name = info.GetString("Name");
this.Tag = Extensions.GetValue<object>(info, "Tag", null);
this.deserializedPoints = Extensions.GetValue<PointLatLng[]>(info, "Points");
this.Points = new List<PointLatLng>();
}
 
#endregion
 
#region IDeserializationCallback Members
 
/// <summary>
/// Runs when the entire object graph has been de-serialized.
/// </summary>
/// <param name="sender">The object that initiated the callback. The functionality for this parameter is not currently implemented.</param>
public virtual void OnDeserialization(object sender)
{
// Accounts for the de-serialization being breadth first rather than depth first.
Points.AddRange(deserializedPoints);
Points.TrimExcess();
}
 
#endregion
#endif
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/MapType.cs
0,0 → 1,127

namespace GMap.NET
{
using System;
 
/// <summary>
/// types of great maps, legacy, not used anymore,
/// left for old ids
/// </summary>
public enum MapType
{
None = 0, // displays no map
 
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleMap = 1,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleSatellite = 4,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleLabels = 8,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleTerrain = 16,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleHybrid = 20,
 
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleMapChina = 22,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleSatelliteChina = 24,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleLabelsChina = 26,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleTerrainChina = 28,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleHybridChina = 29,
 
OpenStreetMap = 32, //
OpenStreetOsm = 33, //
OpenStreetMapSurfer = 34, //
OpenStreetMapSurferTerrain = 35, //
OpenSeaMapLabels = 36, //
OpenSeaMapHybrid = 37, //
OpenCycleMap = 38, //
 
YahooMap = 64,
YahooSatellite = 128,
YahooLabels = 256,
YahooHybrid = 333,
 
BingMap = 444,
BingMap_New = 455,
BingSatellite = 555,
BingHybrid = 666,
 
ArcGIS_StreetMap_World_2D = 777,
ArcGIS_Imagery_World_2D = 788,
ArcGIS_ShadedRelief_World_2D = 799,
ArcGIS_Topo_US_2D = 811,
 
#region -- use these numbers to clean up old stuff --
//ArcGIS_MapsLT_Map_Old= 877,
//ArcGIS_MapsLT_OrtoFoto_Old = 888,
//ArcGIS_MapsLT_Map_Labels_Old = 890,
//ArcGIS_MapsLT_Map_Hybrid_Old = 899,
//ArcGIS_MapsLT_Map=977,
//ArcGIS_MapsLT_OrtoFoto=988,
//ArcGIS_MapsLT_Map_Labels=990,
//ArcGIS_MapsLT_Map_Hybrid=999,
//ArcGIS_MapsLT_Map=978,
//ArcGIS_MapsLT_OrtoFoto=989,
//ArcGIS_MapsLT_Map_Labels=991,
//ArcGIS_MapsLT_Map_Hybrid=998,
#endregion
 
ArcGIS_World_Physical_Map = 822,
ArcGIS_World_Shaded_Relief = 833,
ArcGIS_World_Street_Map = 844,
ArcGIS_World_Terrain_Base = 855,
ArcGIS_World_Topo_Map = 866,
 
MapsLT_Map = 1000,
MapsLT_OrtoFoto = 1001,
MapsLT_Map_Labels = 1002,
MapsLT_Map_Hybrid = 1003,
MapsLT_Map_2_5D = 1004, // 2.5D only for zoom 10 & 11
MapsLT_OrtoFoto_2010 = 1101, // new but only partial coverage
MapsLT_Map_Hybrid_2010 = 1103, // --..--
 
KarteLV_Map = 1500,
 
PergoTurkeyMap = 2001,
SigPacSpainMap = 3001,
 
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleMapKorea = 4001,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleSatelliteKorea = 4002,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleLabelsKorea = 4003,
[Obsolete("check http://greatmaps.codeplex.com/discussions/252531", false)]
GoogleHybridKorea = 4005,
 
YandexMapRu = 5000,
YandexMapRuSatellite = 5001,
YandexMapRuLabels = 5002,
YandexMapRuHybrid = 5003,
 
MapBenderWMS = 6000,
 
MapyCZ_Map = 7000,
MapyCZ_MapTurist = 7001,
MapyCZ_Satellite = 7002,
MapyCZ_Labels = 7003,
MapyCZ_Hybrid = 7004,
MapyCZ_History = 7005,
MapyCZ_HistoryHybrid = 7006,
 
NearMap = 8000,
NearMapSatellite = 8001,
NearMapLabels = 8002,
NearMapHybrid = 8003,
 
OviMap = 9000,
OviMapSatellite = 9001,
OviMapHybrid = 9002,
OviMapTerrain = 9003,
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/MouseWheelZoomType.cs
0,0 → 1,25

namespace GMap.NET
{
/// <summary>
/// map zooming type
/// </summary>
public enum MouseWheelZoomType
{
/// <summary>
/// zooms map to current mouse position and makes it map center
/// </summary>
MousePositionAndCenter,
 
/// <summary>
/// zooms to current mouse position, but doesn't make it map center,
/// google/bing style ;}
/// </summary>
MousePositionWithoutCenter,
 
/// <summary>
/// zooms map to current view center
/// </summary>
ViewCenter,
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/Placemark.cs
0,0 → 1,63

namespace GMap.NET
{
/// <summary>
/// represents place info
/// </summary>
public struct Placemark
{
string address;
 
/// <summary>
/// the address
/// </summary>
public string Address
{
get
{
return address;
}
internal set
{
address = value;
}
}
 
/// <summary>
/// the accuracy of address
/// </summary>
public int Accuracy;
 
// parsed values from address
public string ThoroughfareName;
public string LocalityName;
public string PostalCodeNumber;
public string CountryName;
public string AdministrativeAreaName;
public string DistrictName;
public string SubAdministrativeAreaName;
public string Neighborhood;
public string StreetNumber;
 
public string CountryNameCode;
public string HouseNo;
 
internal Placemark(string address)
{
this.address = address;
 
Accuracy = 0;
HouseNo = string.Empty;
ThoroughfareName = string.Empty;
DistrictName = string.Empty;
LocalityName = string.Empty;
PostalCodeNumber = string.Empty;
CountryName = string.Empty;
CountryNameCode = string.Empty;
AdministrativeAreaName = string.Empty;
SubAdministrativeAreaName = string.Empty;
Neighborhood = string.Empty;
StreetNumber = string.Empty;
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/PointLatLng.cs
0,0 → 1,129

namespace GMap.NET
{
using System;
using System.Globalization;
 
/// <summary>
/// the point of coordinates
/// </summary>
[Serializable]
public struct PointLatLng
{
public static readonly PointLatLng Empty = new PointLatLng();
private double lat;
private double lng;
 
bool NotEmpty;
 
public PointLatLng(double lat, double lng)
{
this.lat = lat;
this.lng = lng;
NotEmpty = true;
}
 
/// <summary>
/// returns true if coordinates wasn't assigned
/// </summary>
public bool IsEmpty
{
get
{
return !NotEmpty;
}
}
 
public double Lat
{
get
{
return this.lat;
}
set
{
this.lat = value;
NotEmpty = true;
}
}
 
public double Lng
{
get
{
return this.lng;
}
set
{
this.lng = value;
NotEmpty = true;
}
}
 
public static PointLatLng operator +(PointLatLng pt, SizeLatLng sz)
{
return Add(pt, sz);
}
 
public static PointLatLng operator -(PointLatLng pt, SizeLatLng sz)
{
return Subtract(pt, sz);
}
 
public static SizeLatLng operator -(PointLatLng pt1, PointLatLng pt2)
{
return new SizeLatLng(pt1.Lat - pt2.Lat, pt2.Lng - pt1.Lng);
}
 
public static bool operator ==(PointLatLng left, PointLatLng right)
{
return ((left.Lng == right.Lng) && (left.Lat == right.Lat));
}
 
public static bool operator !=(PointLatLng left, PointLatLng right)
{
return !(left == right);
}
 
public static PointLatLng Add(PointLatLng pt, SizeLatLng sz)
{
return new PointLatLng(pt.Lat - sz.HeightLat, pt.Lng + sz.WidthLng);
}
 
public static PointLatLng Subtract(PointLatLng pt, SizeLatLng sz)
{
return new PointLatLng(pt.Lat + sz.HeightLat, pt.Lng - sz.WidthLng);
}
 
public override bool Equals(object obj)
{
if(!(obj is PointLatLng))
{
return false;
}
PointLatLng tf = (PointLatLng)obj;
return (((tf.Lng == this.Lng) && (tf.Lat == this.Lat)) && tf.GetType().Equals(base.GetType()));
}
 
public void Offset(PointLatLng pos)
{
this.Offset(pos.Lat, pos.Lng);
}
 
public void Offset(double lat, double lng)
{
this.Lng += lng;
this.Lat -= lat;
}
 
public override int GetHashCode()
{
return (this.Lng.GetHashCode() ^ this.Lat.GetHashCode());
}
 
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "{{Lat={0}, Lng={1}}}", this.Lat, this.Lng);
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/PureImageCache.cs
0,0 → 1,39

namespace GMap.NET
{
using System.IO;
using System;
 
/// <summary>
/// pure abstraction for image cache
/// </summary>
public interface PureImageCache
{
/// <summary>
/// puts image to db
/// </summary>
/// <param name="tile"></param>
/// <param name="type"></param>
/// <param name="pos"></param>
/// <param name="zoom"></param>
/// <returns></returns>
bool PutImageToCache(byte[] tile, int type, GPoint pos, int zoom);
 
/// <summary>
/// gets image from db
/// </summary>
/// <param name="type"></param>
/// <param name="pos"></param>
/// <param name="zoom"></param>
/// <returns></returns>
PureImage GetImageFromCache(int type, GPoint pos, int zoom);
 
/// <summary>
/// delete old tiles beyond a supplied date
/// </summary>
/// <param name="date">Tiles older than this will be deleted.</param>
/// <param name="type">provider dbid or null to use all providers</param>
/// <returns>The number of deleted tiles.</returns>
int DeleteOlderThan(DateTime date, int ? type);
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/PureProjection.cs
0,0 → 1,512

namespace GMap.NET
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
 
/// <summary>
/// defines projection
/// </summary>
public abstract class PureProjection
{
readonly List<Dictionary<PointLatLng, GPoint>> FromLatLngToPixelCache = new List<Dictionary<PointLatLng, GPoint>>(33);
readonly List<Dictionary<GPoint, PointLatLng>> FromPixelToLatLngCache = new List<Dictionary<GPoint, PointLatLng>>(33);
 
public PureProjection()
{
for(int i = 0; i < FromLatLngToPixelCache.Capacity; i++)
{
FromLatLngToPixelCache.Add(new Dictionary<PointLatLng, GPoint>());
FromPixelToLatLngCache.Add(new Dictionary<GPoint, PointLatLng>());
}
}
 
/// <summary>
/// size of tile
/// </summary>
public abstract GSize TileSize
{
get;
}
 
/// <summary>
/// Semi-major axis of ellipsoid, in meters
/// </summary>
public abstract double Axis
{
get;
}
 
/// <summary>
/// Flattening of ellipsoid
/// </summary>
public abstract double Flattening
{
get;
}
 
/// <summary>
/// get pixel coordinates from lat/lng
/// </summary>
/// <param name="lat"></param>
/// <param name="lng"></param>
/// <param name="zoom"></param>
/// <returns></returns>
public abstract GPoint FromLatLngToPixel(double lat, double lng, int zoom);
 
/// <summary>
/// gets lat/lng coordinates from pixel coordinates
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="zoom"></param>
/// <returns></returns>
public abstract PointLatLng FromPixelToLatLng(long x, long y, int zoom);
 
public GPoint FromLatLngToPixel(PointLatLng p, int zoom)
{
return FromLatLngToPixel(p, zoom, false);
}
 
/// <summary>
/// get pixel coordinates from lat/lng
/// </summary>
/// <param name="p"></param>
/// <param name="zoom"></param>
/// <returns></returns>
public GPoint FromLatLngToPixel(PointLatLng p, int zoom, bool useCache)
{
if(useCache)
{
GPoint ret = GPoint.Empty;
if(!FromLatLngToPixelCache[zoom].TryGetValue(p, out ret))
{
ret = FromLatLngToPixel(p.Lat, p.Lng, zoom);
FromLatLngToPixelCache[zoom].Add(p, ret);
 
// for reverse cache
if(!FromPixelToLatLngCache[zoom].ContainsKey(ret))
{
FromPixelToLatLngCache[zoom].Add(ret, p);
}
 
Debug.WriteLine("FromLatLngToPixelCache[" + zoom + "] added " + p + " with " + ret);
}
return ret;
}
else
{
return FromLatLngToPixel(p.Lat, p.Lng, zoom);
}
}
 
public PointLatLng FromPixelToLatLng(GPoint p, int zoom)
{
return FromPixelToLatLng(p, zoom, false);
}
 
/// <summary>
/// gets lat/lng coordinates from pixel coordinates
/// </summary>
/// <param name="p"></param>
/// <param name="zoom"></param>
/// <returns></returns>
public PointLatLng FromPixelToLatLng(GPoint p, int zoom, bool useCache)
{
if(useCache)
{
PointLatLng ret = PointLatLng.Empty;
if(!FromPixelToLatLngCache[zoom].TryGetValue(p, out ret))
{
ret = FromPixelToLatLng(p.X, p.Y, zoom);
FromPixelToLatLngCache[zoom].Add(p, ret);
 
// for reverse cache
if(!FromLatLngToPixelCache[zoom].ContainsKey(ret))
{
FromLatLngToPixelCache[zoom].Add(ret, p);
}
 
Debug.WriteLine("FromPixelToLatLngCache[" + zoom + "] added " + p + " with " + ret);
}
return ret;
}
else
{
return FromPixelToLatLng(p.X, p.Y, zoom);
}
}
 
/// <summary>
/// gets tile coorddinate from pixel coordinates
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public virtual GPoint FromPixelToTileXY(GPoint p)
{
return new GPoint((long)(p.X / TileSize.Width), (long)(p.Y / TileSize.Height));
}
 
/// <summary>
/// gets pixel coordinate from tile coordinate
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public virtual GPoint FromTileXYToPixel(GPoint p)
{
return new GPoint((p.X * TileSize.Width), (p.Y * TileSize.Height));
}
 
/// <summary>
/// min. tile in tiles at custom zoom level
/// </summary>
/// <param name="zoom"></param>
/// <returns></returns>
public abstract GSize GetTileMatrixMinXY(int zoom);
 
/// <summary>
/// max. tile in tiles at custom zoom level
/// </summary>
/// <param name="zoom"></param>
/// <returns></returns>
public abstract GSize GetTileMatrixMaxXY(int zoom);
 
/// <summary>
/// gets matrix size in tiles
/// </summary>
/// <param name="zoom"></param>
/// <returns></returns>
public virtual GSize GetTileMatrixSizeXY(int zoom)
{
GSize sMin = GetTileMatrixMinXY(zoom);
GSize sMax = GetTileMatrixMaxXY(zoom);
 
return new GSize(sMax.Width - sMin.Width + 1, sMax.Height - sMin.Height + 1);
}
 
/// <summary>
/// tile matrix size in pixels at custom zoom level
/// </summary>
/// <param name="zoom"></param>
/// <returns></returns>
public long GetTileMatrixItemCount(int zoom)
{
GSize s = GetTileMatrixSizeXY(zoom);
return (s.Width * s.Height);
}
 
/// <summary>
/// gets matrix size in pixels
/// </summary>
/// <param name="zoom"></param>
/// <returns></returns>
public virtual GSize GetTileMatrixSizePixel(int zoom)
{
GSize s = GetTileMatrixSizeXY(zoom);
return new GSize(s.Width * TileSize.Width, s.Height * TileSize.Height);
}
 
/// <summary>
/// gets all tiles in rect at specific zoom
/// </summary>
public List<GPoint> GetAreaTileList(RectLatLng rect, int zoom, int padding)
{
List<GPoint> ret = new List<GPoint>();
 
GPoint topLeft = FromPixelToTileXY(FromLatLngToPixel(rect.LocationTopLeft, zoom));
GPoint rightBottom = FromPixelToTileXY(FromLatLngToPixel(rect.LocationRightBottom, zoom));
 
for(long x = (topLeft.X - padding); x <= (rightBottom.X + padding); x++)
{
for(long y = (topLeft.Y - padding); y <= (rightBottom.Y + padding); y++)
{
GPoint p = new GPoint(x, y);
if(!ret.Contains(p) && p.X >= 0 && p.Y >= 0)
{
ret.Add(p);
}
}
}
 
return ret;
}
 
/// <summary>
/// The ground resolution indicates the distance (in meters) on the ground that’s represented by a single pixel in the map.
/// For example, at a ground resolution of 10 meters/pixel, each pixel represents a ground distance of 10 meters.
/// </summary>
/// <param name="zoom"></param>
/// <param name="latitude"></param>
/// <returns></returns>
public virtual double GetGroundResolution(int zoom, double latitude)
{
return (Math.Cos(latitude * (Math.PI / 180)) * 2 * Math.PI * Axis) / GetTileMatrixSizePixel(zoom).Width;
}
 
/// <summary>
/// gets boundaries
/// </summary>
public virtual RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(-180, 90, 180, -90);
}
}
 
#region -- math functions --
 
/// <summary>
/// PI
/// </summary>
protected static readonly double PI = Math.PI;
 
/// <summary>
/// Half of PI
/// </summary>
protected static readonly double HALF_PI = (PI * 0.5);
 
/// <summary>
/// PI * 2
/// </summary>
protected static readonly double TWO_PI = (PI * 2.0);
 
/// <summary>
/// EPSLoN
/// </summary>
protected static readonly double EPSLoN = 1.0e-10;
 
/// <summary>
/// MAX_VAL
/// </summary>
protected const double MAX_VAL = 4;
 
/// <summary>
/// MAXLONG
/// </summary>
protected static readonly double MAXLONG = 2147483647;
 
/// <summary>
/// DBLLONG
/// </summary>
protected static readonly double DBLLONG = 4.61168601e18;
 
static readonly double R2D = 180 / Math.PI;
static readonly double D2R = Math.PI / 180;
 
public static double DegreesToRadians(double deg)
{
return (D2R * deg);
}
 
public static double RadiansToDegrees(double rad)
{
return (R2D * rad);
}
 
///<summary>
/// return the sign of an argument
///</summary>
protected static double Sign(double x)
{
if(x < 0.0)
return (-1);
else
return (1);
}
 
protected static double AdjustLongitude(double x)
{
long count = 0;
while(true)
{
if(Math.Abs(x) <= PI)
break;
else
if(((long)Math.Abs(x / Math.PI)) < 2)
x = x - (Sign(x) * TWO_PI);
else
if(((long)Math.Abs(x / TWO_PI)) < MAXLONG)
{
x = x - (((long)(x / TWO_PI)) * TWO_PI);
}
else
if(((long)Math.Abs(x / (MAXLONG * TWO_PI))) < MAXLONG)
{
x = x - (((long)(x / (MAXLONG * TWO_PI))) * (TWO_PI * MAXLONG));
}
else
if(((long)Math.Abs(x / (DBLLONG * TWO_PI))) < MAXLONG)
{
x = x - (((long)(x / (DBLLONG * TWO_PI))) * (TWO_PI * DBLLONG));
}
else
x = x - (Sign(x) * TWO_PI);
count++;
if(count > MAX_VAL)
break;
}
return (x);
}
 
/// <summary>
/// calculates the sine and cosine
/// </summary>
protected static void SinCos(double val, out double sin, out double cos)
{
sin = Math.Sin(val);
cos = Math.Cos(val);
}
 
/// <summary>
/// computes the constants e0, e1, e2, and e3 which are used
/// in a series for calculating the distance along a meridian.
/// </summary>
/// <param name="x">represents the eccentricity squared</param>
/// <returns></returns>
protected static double e0fn(double x)
{
return (1.0 - 0.25 * x * (1.0 + x / 16.0 * (3.0 + 1.25 * x)));
}
 
protected static double e1fn(double x)
{
return (0.375 * x * (1.0 + 0.25 * x * (1.0 + 0.46875 * x)));
}
 
protected static double e2fn(double x)
{
return (0.05859375 * x * x * (1.0 + 0.75 * x));
}
 
protected static double e3fn(double x)
{
return (x * x * x * (35.0 / 3072.0));
}
 
/// <summary>
/// computes the value of M which is the distance along a meridian
/// from the Equator to latitude phi.
/// </summary>
protected static double mlfn(double e0, double e1, double e2, double e3, double phi)
{
return (e0 * phi - e1 * Math.Sin(2.0 * phi) + e2 * Math.Sin(4.0 * phi) - e3 * Math.Sin(6.0 * phi));
}
 
/// <summary>
/// calculates UTM zone number
/// </summary>
/// <param name="lon">Longitude in degrees</param>
/// <returns></returns>
protected static long GetUTMzone(double lon)
{
return ((long)(((lon + 180.0) / 6.0) + 1.0));
}
 
/// <summary>
/// Clips a number to the specified minimum and maximum values.
/// </summary>
/// <param name="n">The number to clip.</param>
/// <param name="minValue">Minimum allowable value.</param>
/// <param name="maxValue">Maximum allowable value.</param>
/// <returns>The clipped value.</returns>
protected static double Clip(double n, double minValue, double maxValue)
{
return Math.Min(Math.Max(n, minValue), maxValue);
}
 
/// <summary>
/// distance (in km) between two points specified by latitude/longitude
/// The Haversine formula, http://www.movable-type.co.uk/scripts/latlong.html
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <returns></returns>
public double GetDistance(PointLatLng p1, PointLatLng p2)
{
double dLat1InRad = p1.Lat * (Math.PI / 180);
double dLong1InRad = p1.Lng * (Math.PI / 180);
double dLat2InRad = p2.Lat * (Math.PI / 180);
double dLong2InRad = p2.Lng * (Math.PI / 180);
double dLongitude = dLong2InRad - dLong1InRad;
double dLatitude = dLat2InRad - dLat1InRad;
double a = Math.Pow(Math.Sin(dLatitude / 2), 2) + Math.Cos(dLat1InRad) * Math.Cos(dLat2InRad) * Math.Pow(Math.Sin(dLongitude / 2), 2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
double dDistance = (Axis / 1000.0) * c;
return dDistance;
}
 
public double GetDistanceInPixels(GPoint point1, GPoint point2)
{
double a = (double)(point2.X - point1.X);
double b = (double)(point2.Y - point1.Y);
 
return Math.Sqrt(a * a + b * b);
}
 
/// <summary>
/// Accepts two coordinates in degrees.
/// </summary>
/// <returns>A double value in degrees. From 0 to 360.</returns>
public double GetBearing(PointLatLng p1, PointLatLng p2)
{
var latitude1 = DegreesToRadians(p1.Lat);
var latitude2 = DegreesToRadians(p2.Lat);
var longitudeDifference = DegreesToRadians(p2.Lng - p1.Lng);
 
var y = Math.Sin(longitudeDifference) * Math.Cos(latitude2);
var x = Math.Cos(latitude1) * Math.Sin(latitude2) - Math.Sin(latitude1) * Math.Cos(latitude2) * Math.Cos(longitudeDifference);
 
return (RadiansToDegrees(Math.Atan2(y, x)) + 360) % 360;
}
 
/// <summary>
/// Conversion from cartesian earth-sentered coordinates to geodetic coordinates in the given datum
/// </summary>
/// <param name="Lat"></param>
/// <param name="Lon"></param>
/// <param name="Height">Height above ellipsoid [m]</param>
/// <param name="X"></param>
/// <param name="Y"></param>
/// <param name="Z"></param>
public void FromGeodeticToCartesian(double Lat, double Lng, double Height, out double X, out double Y, out double Z)
{
Lat = (Math.PI / 180) * Lat;
Lng = (Math.PI / 180) * Lng;
 
double B = Axis * (1.0 - Flattening);
double ee = 1.0 - (B / Axis) * (B / Axis);
double N = (Axis / Math.Sqrt(1.0 - ee * Math.Sin(Lat) * Math.Sin(Lat)));
 
X = (N + Height) * Math.Cos(Lat) * Math.Cos(Lng);
Y = (N + Height) * Math.Cos(Lat) * Math.Sin(Lng);
Z = (N * (B / Axis) * (B / Axis) + Height) * Math.Sin(Lat);
}
 
/// <summary>
/// Conversion from cartesian earth-sentered coordinates to geodetic coordinates in the given datum
/// </summary>
/// <param name="X"></param>
/// <param name="Y"></param>
/// <param name="Z"></param>
/// <param name="Lat"></param>
/// <param name="Lon"></param>
public void FromCartesianTGeodetic(double X, double Y, double Z, out double Lat, out double Lng)
{
double E = Flattening * (2.0 - Flattening);
Lng = Math.Atan2(Y, X);
 
double P = Math.Sqrt(X * X + Y * Y);
double Theta = Math.Atan2(Z, (P * (1.0 - Flattening)));
double st = Math.Sin(Theta);
double ct = Math.Cos(Theta);
Lat = Math.Atan2(Z + E / (1.0 - Flattening) * Axis * st * st * st, P - E * Axis * ct * ct * ct);
 
Lat /= (Math.PI / 180);
Lng /= (Math.PI / 180);
}
 
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/RectLatLng.cs
0,0 → 1,318

namespace GMap.NET
{
using System;
using System.Globalization;
 
/// <summary>
/// the rect of coordinates
/// </summary>
public struct RectLatLng
{
public static readonly RectLatLng Empty;
private double lng;
private double lat;
private double widthLng;
private double heightLat;
 
public RectLatLng(double lat, double lng, double widthLng, double heightLat)
{
this.lng = lng;
this.lat = lat;
this.widthLng = widthLng;
this.heightLat = heightLat;
NotEmpty = true;
}
 
public RectLatLng(PointLatLng location, SizeLatLng size)
{
this.lng = location.Lng;
this.lat = location.Lat;
this.widthLng = size.WidthLng;
this.heightLat = size.HeightLat;
NotEmpty = true;
}
 
public static RectLatLng FromLTRB(double leftLng, double topLat, double rightLng, double bottomLat)
{
return new RectLatLng(topLat, leftLng, rightLng - leftLng, topLat - bottomLat);
}
 
public PointLatLng LocationTopLeft
{
get
{
return new PointLatLng(this.Lat, this.Lng);
}
set
{
this.Lng = value.Lng;
this.Lat = value.Lat;
}
}
 
public PointLatLng LocationRightBottom
{
get
{
PointLatLng ret = new PointLatLng(this.Lat, this.Lng);
ret.Offset(HeightLat, WidthLng);
return ret;
}
}
 
public PointLatLng LocationMiddle
{
get
{
PointLatLng ret = new PointLatLng(this.Lat, this.Lng);
ret.Offset(HeightLat / 2, WidthLng / 2);
return ret;
}
}
 
public SizeLatLng Size
{
get
{
return new SizeLatLng(this.HeightLat, this.WidthLng);
}
set
{
this.WidthLng = value.WidthLng;
this.HeightLat = value.HeightLat;
}
}
 
public double Lng
{
get
{
return this.lng;
}
set
{
this.lng = value;
}
}
 
public double Lat
{
get
{
return this.lat;
}
set
{
this.lat = value;
}
}
 
public double WidthLng
{
get
{
return this.widthLng;
}
set
{
this.widthLng = value;
}
}
 
public double HeightLat
{
get
{
return this.heightLat;
}
set
{
this.heightLat = value;
}
}
 
public double Left
{
get
{
return this.Lng;
}
}
 
public double Top
{
get
{
return this.Lat;
}
}
 
public double Right
{
get
{
return (this.Lng + this.WidthLng);
}
}
 
public double Bottom
{
get
{
return (this.Lat - this.HeightLat);
}
}
 
bool NotEmpty;
 
/// <summary>
/// returns true if coordinates wasn't assigned
/// </summary>
public bool IsEmpty
{
get
{
return !NotEmpty;
}
}
 
public override bool Equals(object obj)
{
if(!(obj is RectLatLng))
{
return false;
}
RectLatLng ef = (RectLatLng)obj;
return ((((ef.Lng == this.Lng) && (ef.Lat == this.Lat)) && (ef.WidthLng == this.WidthLng)) && (ef.HeightLat == this.HeightLat));
}
 
public static bool operator ==(RectLatLng left, RectLatLng right)
{
return ((((left.Lng == right.Lng) && (left.Lat == right.Lat)) && (left.WidthLng == right.WidthLng)) && (left.HeightLat == right.HeightLat));
}
 
public static bool operator !=(RectLatLng left, RectLatLng right)
{
return !(left == right);
}
 
public bool Contains(double lat, double lng)
{
return ((((this.Lng <= lng) && (lng < (this.Lng + this.WidthLng))) && (this.Lat >= lat)) && (lat > (this.Lat - this.HeightLat)));
}
 
public bool Contains(PointLatLng pt)
{
return this.Contains(pt.Lat, pt.Lng);
}
 
public bool Contains(RectLatLng rect)
{
return ((((this.Lng <= rect.Lng) && ((rect.Lng + rect.WidthLng) <= (this.Lng + this.WidthLng))) && (this.Lat >= rect.Lat)) && ((rect.Lat - rect.HeightLat) >= (this.Lat - this.HeightLat)));
}
 
public override int GetHashCode()
{
if(this.IsEmpty)
{
return 0;
}
return (((this.Lng.GetHashCode() ^ this.Lat.GetHashCode()) ^ this.WidthLng.GetHashCode()) ^ this.HeightLat.GetHashCode());
}
 
// from here down need to test each function to be sure they work good
// |
// .
 
#region -- unsure --
public void Inflate(double lat, double lng)
{
this.Lng -= lng;
this.Lat += lat;
this.WidthLng += 2d * lng;
this.HeightLat += 2d * lat;
}
 
public void Inflate(SizeLatLng size)
{
this.Inflate(size.HeightLat, size.WidthLng);
}
 
public static RectLatLng Inflate(RectLatLng rect, double lat, double lng)
{
RectLatLng ef = rect;
ef.Inflate(lat, lng);
return ef;
}
 
public void Intersect(RectLatLng rect)
{
RectLatLng ef = Intersect(rect, this);
this.Lng = ef.Lng;
this.Lat = ef.Lat;
this.WidthLng = ef.WidthLng;
this.HeightLat = ef.HeightLat;
}
 
// ok ???
public static RectLatLng Intersect(RectLatLng a, RectLatLng b)
{
double lng = Math.Max(a.Lng, b.Lng);
double num2 = Math.Min((double)(a.Lng + a.WidthLng), (double)(b.Lng + b.WidthLng));
 
double lat = Math.Max(a.Lat, b.Lat);
double num4 = Math.Min((double)(a.Lat + a.HeightLat), (double)(b.Lat + b.HeightLat));
 
if((num2 >= lng) && (num4 >= lat))
{
return new RectLatLng(lat, lng, num2 - lng, num4 - lat);
}
return Empty;
}
 
// ok ???
// http://greatmaps.codeplex.com/workitem/15981
public bool IntersectsWith(RectLatLng a)
{
return this.Left < a.Right && this.Top > a.Bottom && this.Right > a.Left && this.Bottom < a.Top;
}
 
// ok ???
// http://greatmaps.codeplex.com/workitem/15981
public static RectLatLng Union(RectLatLng a, RectLatLng b)
{
return RectLatLng.FromLTRB(
Math.Min(a.Left, b.Left),
Math.Max(a.Top, b.Top),
Math.Max(a.Right, b.Right),
Math.Min(a.Bottom, b.Bottom));
}
#endregion
 
// .
// |
// unsure ends here
 
public void Offset(PointLatLng pos)
{
this.Offset(pos.Lat, pos.Lng);
}
 
public void Offset(double lat, double lng)
{
this.Lng += lng;
this.Lat -= lat;
}
 
public override string ToString()
{
return ("{Lat=" + this.Lat.ToString(CultureInfo.CurrentCulture) + ",Lng=" + this.Lng.ToString(CultureInfo.CurrentCulture) + ",WidthLng=" + this.WidthLng.ToString(CultureInfo.CurrentCulture) + ",HeightLat=" + this.HeightLat.ToString(CultureInfo.CurrentCulture) + "}");
}
 
static RectLatLng()
{
Empty = new RectLatLng();
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/RenderMode.cs
0,0 → 1,19

namespace GMap.NET
{
/// <summary>
/// types of map rendering
/// </summary>
public enum RenderMode
{
/// <summary>
/// gdi+ should work anywhere on Windows Forms
/// </summary>
GDI_PLUS,
 
/// <summary>
/// only on Windows Presentation Foundation
/// </summary>
WPF,
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/RoutingProvider.cs
0,0 → 1,19

namespace GMap.NET
{
/// <summary>
/// routing interface
/// </summary>
public interface RoutingProvider
{
/// <summary>
/// get route between two points
/// </summary>
MapRoute GetRoute(PointLatLng start, PointLatLng end, bool avoidHighways, bool walkingMode, int Zoom);
 
/// <summary>
/// get route between two points
/// </summary>
MapRoute GetRoute(string start, string end, bool avoidHighways, bool walkingMode, int Zoom);
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/Singleton.cs
0,0 → 1,60

namespace GMap.NET
{
using System;
using System.Diagnostics;
using System.Reflection;
 
/// <summary>
/// generic for singletons
/// </summary>
/// <typeparam name="T"></typeparam>
public class Singleton<T> where T : new()
{
// ctor
protected Singleton()
{
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\""));
}
}
 
public static T Instance
{
get
{
if(SingletonCreator.exception != null)
{
throw SingletonCreator.exception;
}
return SingletonCreator.instance;
}
}
 
class SingletonCreator
{
static SingletonCreator()
{
try
{
instance = new T();
}
catch(Exception ex)
{
if(ex.InnerException != null)
{
exception = ex.InnerException;
}
else
{
exception = ex;
}
Trace.WriteLine("Singleton: " + exception);
}
}
internal static readonly T instance;
internal static readonly Exception exception;
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/SizeLatLng.cs
0,0 → 1,135

namespace GMap.NET
{
using System.Globalization;
 
/// <summary>
/// the size of coordinates
/// </summary>
public struct SizeLatLng
{
public static readonly SizeLatLng Empty;
 
private double heightLat;
private double widthLng;
 
public SizeLatLng(SizeLatLng size)
{
this.widthLng = size.widthLng;
this.heightLat = size.heightLat;
}
 
public SizeLatLng(PointLatLng pt)
{
this.heightLat = pt.Lat;
this.widthLng = pt.Lng;
}
 
public SizeLatLng(double heightLat, double widthLng)
{
this.heightLat = heightLat;
this.widthLng = widthLng;
}
 
public static SizeLatLng operator+(SizeLatLng sz1, SizeLatLng sz2)
{
return Add(sz1, sz2);
}
 
public static SizeLatLng operator-(SizeLatLng sz1, SizeLatLng sz2)
{
return Subtract(sz1, sz2);
}
 
public static bool operator==(SizeLatLng sz1, SizeLatLng sz2)
{
return ((sz1.WidthLng == sz2.WidthLng) && (sz1.HeightLat == sz2.HeightLat));
}
 
public static bool operator!=(SizeLatLng sz1, SizeLatLng sz2)
{
return !(sz1 == sz2);
}
 
public static explicit operator PointLatLng(SizeLatLng size)
{
return new PointLatLng(size.HeightLat, size.WidthLng);
}
 
public bool IsEmpty
{
get
{
return ((this.widthLng == 0d) && (this.heightLat == 0d));
}
}
 
public double WidthLng
{
get
{
return this.widthLng;
}
set
{
this.widthLng = value;
}
}
 
public double HeightLat
{
get
{
return this.heightLat;
}
set
{
this.heightLat = value;
}
}
 
public static SizeLatLng Add(SizeLatLng sz1, SizeLatLng sz2)
{
return new SizeLatLng(sz1.HeightLat + sz2.HeightLat, sz1.WidthLng + sz2.WidthLng);
}
 
public static SizeLatLng Subtract(SizeLatLng sz1, SizeLatLng sz2)
{
return new SizeLatLng(sz1.HeightLat - sz2.HeightLat, sz1.WidthLng - sz2.WidthLng);
}
 
public override bool Equals(object obj)
{
if(!(obj is SizeLatLng))
{
return false;
}
SizeLatLng ef = (SizeLatLng) obj;
return (((ef.WidthLng == this.WidthLng) && (ef.HeightLat == this.HeightLat)) && ef.GetType().Equals(base.GetType()));
}
 
public override int GetHashCode()
{
if(this.IsEmpty)
{
return 0;
}
return (this.WidthLng.GetHashCode() ^ this.HeightLat.GetHashCode());
}
 
public PointLatLng ToPointLatLng()
{
return (PointLatLng) this;
}
 
public override string ToString()
{
return ("{WidthLng=" + this.widthLng.ToString(CultureInfo.CurrentCulture) + ", HeightLng=" + this.heightLat.ToString(CultureInfo.CurrentCulture) + "}");
}
 
static SizeLatLng()
{
Empty = new SizeLatLng();
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/StatusCodes.cs
0,0 → 1,125

namespace GMap.NET
{
/// <summary>
/// GeoCoder StatusCode
/// </summary>
public enum GeoCoderStatusCode : int
{
/// <summary>
/// unknow response
/// </summary>
Unknow = -1,
 
/// <summary>
/// No errors occurred; the address was successfully parsed and its geocode has been returned.
/// </summary>
G_GEO_SUCCESS = 200,
 
/// <summary>
/// A directions request could not be successfully parsed.
/// For example, the request may have been rejected if it contained more than the maximum number of waypoints allowed.
/// </summary>
G_GEO_BAD_REQUEST = 400,
 
/// <summary>
/// A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.
/// </summary>
G_GEO_SERVER_ERROR = 500,
 
/// <summary>
/// The HTTP q parameter was either missing or had no value.
/// For geocoding requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.
/// </summary>
G_GEO_MISSING_QUERY = 601,
 
/// <summary>
/// Synonym for G_GEO_MISSING_QUERY.
/// </summary>
G_GEO_MISSING_ADDRESS = 601,
 
/// <summary>
/// No corresponding geographic location could be found for the specified address.
/// This may be due to the fact that the address is relatively new, or it may be incorrect.
/// </summary>
G_GEO_UNKNOWN_ADDRESS = 602,
 
/// <summary>
/// The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.
/// </summary>
G_GEO_UNAVAILABLE_ADDRESS = 603,
 
/// <summary>
/// The GDirections object could not compute directions between the points mentioned in the query.
/// This is usually because there is no route available between the two points, or because we do not have data for routing in that region.
/// </summary>
G_GEO_UNKNOWN_DIRECTIONS = 604,
 
/// <summary>
/// The given key is either invalid or does not match the domain for which it was given.
/// </summary>
G_GEO_BAD_KEY = 610,
 
/// <summary>
/// The given key has gone over the requests limit in the 24 hour period or has submitted too many requests in too short a period of time.
/// If you're sending multiple requests in parallel or in a tight loop, use a timer or pause in your code to make sure you don't send the requests too quickly.
/// </summary>
G_GEO_TOO_MANY_QUERIES = 620,
 
/// <summary>
/// indicates that exception occured during execution
/// </summary>
ExceptionInCode,
}
 
/// <summary>
/// Direction StatusCode
/// </summary>
public enum DirectionsStatusCode : int
{
/// <summary>
/// indicates the response contains a valid result.
/// </summary>
OK = 0,
 
/// <summary>
/// indicates at least one of the locations specified in the requests's origin, destination, or waypoints could not be geocoded.
/// </summary>
NOT_FOUND,
 
/// <summary>
/// indicates no route could be found between the origin and destination.
/// </summary>
ZERO_RESULTS,
 
/// <summary>
/// indicates that too many waypointss were provided in the request The maximum allowed waypoints is 8, plus the origin, and destination.
/// </summary>
MAX_WAYPOINTS_EXCEEDED,
 
/// <summary>
/// indicates that the provided request was invalid.
/// </summary>
INVALID_REQUEST,
 
/// <summary>
/// indicates the service has received too many requests from your application within the allowed time period.
/// </summary>
OVER_QUERY_LIMIT,
 
/// <summary>
/// indicates that the service denied use of the directions service by your application.
/// </summary>
REQUEST_DENIED,
 
/// <summary>
/// indicates a directions request could not be processed due to a server error. The request may succeed if you try again.
/// </summary>
UNKNOWN_ERROR,
 
/// <summary>
/// indicates that exception occured during execution
/// </summary>
ExceptionInCode,
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/ZipStorer.cs
0,0 → 1,748
// ZipStorer, by Jaime Olivares
// Website: zipstorer.codeplex.com
// Version: 2.35 (March 14, 2010)
 
using System.Collections.Generic;
using System.Text;
 
namespace System.IO.Compression
{
/// <summary>
/// Unique class for compression/decompression file. Represents a Zip file.
/// </summary>
public class ZipStorer : IDisposable
{
/// <summary>
/// Compression method enumeration
/// </summary>
public enum Compression : ushort {
/// <summary>Uncompressed storage</summary>
Store = 0,
/// <summary>Deflate compression method</summary>
Deflate = 8 }
 
/// <summary>
/// Represents an entry in Zip file directory
/// </summary>
public struct ZipFileEntry
{
/// <summary>Compression method</summary>
public Compression Method;
/// <summary>Full path and filename as stored in Zip</summary>
public string FilenameInZip;
/// <summary>Original file size</summary>
public uint FileSize;
/// <summary>Compressed file size</summary>
public uint CompressedSize;
/// <summary>Offset of header information inside Zip storage</summary>
public uint HeaderOffset;
/// <summary>Offset of file inside Zip storage</summary>
public uint FileOffset;
/// <summary>Size of header information</summary>
public uint HeaderSize;
/// <summary>32-bit checksum of entire file</summary>
public uint Crc32;
/// <summary>Last modification time of file</summary>
public DateTime ModifyTime;
/// <summary>User comment for file</summary>
public string Comment;
/// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary>
public bool EncodeUTF8;
 
/// <summary>Overriden method</summary>
/// <returns>Filename in Zip</returns>
public override string ToString()
{
return this.FilenameInZip;
}
}
 
#region Public fields
/// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary>
public bool EncodeUTF8 = false;
/// <summary>Force deflate algotithm even if it inflates the stored file. Off by default.</summary>
public bool ForceDeflating = false;
#endregion
 
#region Private fields
// List of files to store
private List<ZipFileEntry> Files = new List<ZipFileEntry>();
// Filename of storage file
private string FileName;
// Stream object of storage file
private Stream ZipFileStream;
// General comment
private string Comment = "";
// Central dir image
private byte[] CentralDirImage = null;
// Existing files in zip
private ushort ExistingFiles = 0;
// File access for Open method
private FileAccess Access;
// Static CRC32 Table
private static UInt32[] CrcTable = null;
// Default filename encoder
private static Encoding DefaultEncoding = Encoding.GetEncoding(437);
#endregion
 
#region Public methods
// Static constructor. Just invoked once in order to create the CRC32 lookup table.
static ZipStorer()
{
// Generate CRC32 table
CrcTable = new UInt32[256];
for (int i = 0; i < CrcTable.Length; i++)
{
UInt32 c = (UInt32)i;
for (int j = 0; j < 8; j++)
{
if ((c & 1) != 0)
c = 3988292384 ^ (c >> 1);
else
c >>= 1;
}
CrcTable[i] = c;
}
}
/// <summary>
/// Method to create a new storage file
/// </summary>
/// <param name="_filename">Full path of Zip file to create</param>
/// <param name="_comment">General comment for Zip file</param>
/// <returns>A valid ZipStorer object</returns>
public static ZipStorer Create(string _filename, string _comment)
{
Stream stream = new FileStream(_filename, FileMode.Create, FileAccess.ReadWrite);
 
ZipStorer zip = Create(stream, _comment);
zip.Comment = _comment;
zip.FileName = _filename;
 
return zip;
}
/// <summary>
/// Method to create a new zip storage in a stream
/// </summary>
/// <param name="_stream"></param>
/// <param name="_comment"></param>
/// <returns>A valid ZipStorer object</returns>
public static ZipStorer Create(Stream _stream, string _comment)
{
ZipStorer zip = new ZipStorer();
zip.Comment = _comment;
zip.ZipFileStream = _stream;
zip.Access = FileAccess.Write;
 
return zip;
}
/// <summary>
/// Method to open an existing storage file
/// </summary>
/// <param name="_filename">Full path of Zip file to open</param>
/// <param name="_access">File access mode as used in FileStream constructor</param>
/// <returns>A valid ZipStorer object</returns>
public static ZipStorer Open(string _filename, FileAccess _access)
{
Stream stream = (Stream)new FileStream(_filename, FileMode.Open, _access == FileAccess.Read ? FileAccess.Read : FileAccess.ReadWrite);
 
ZipStorer zip = Open(stream, _access);
zip.FileName = _filename;
 
return zip;
}
/// <summary>
/// Method to open an existing storage from stream
/// </summary>
/// <param name="_stream">Already opened stream with zip contents</param>
/// <param name="_access">File access mode for stream operations</param>
/// <returns>A valid ZipStorer object</returns>
public static ZipStorer Open(Stream _stream, FileAccess _access)
{
if (!_stream.CanSeek && _access != FileAccess.Read)
throw new InvalidOperationException("Stream cannot seek");
 
ZipStorer zip = new ZipStorer();
//zip.FileName = _filename;
zip.ZipFileStream = _stream;
zip.Access = _access;
 
if (zip.ReadFileInfo())
return zip;
 
throw new System.IO.InvalidDataException();
}
/// <summary>
/// Add full contents of a file into the Zip storage
/// </summary>
/// <param name="_method">Compression method</param>
/// <param name="_pathname">Full path of file to add to Zip storage</param>
/// <param name="_filenameInZip">Filename and path as desired in Zip directory</param>
/// <param name="_comment">Comment for stored file</param>
public void AddFile(Compression _method, string _pathname, string _filenameInZip, string _comment)
{
if (Access == FileAccess.Read)
throw new InvalidOperationException("Writing is not alowed");
 
FileStream stream = new FileStream(_pathname, FileMode.Open, FileAccess.Read);
AddStream(_method, _filenameInZip, stream, File.GetLastWriteTime(_pathname), _comment);
stream.Close();
}
/// <summary>
/// Add full contents of a stream into the Zip storage
/// </summary>
/// <param name="_method">Compression method</param>
/// <param name="_filenameInZip">Filename and path as desired in Zip directory</param>
/// <param name="_source">Stream object containing the data to store in Zip</param>
/// <param name="_modTime">Modification time of the data to store</param>
/// <param name="_comment">Comment for stored file</param>
public void AddStream(Compression _method, string _filenameInZip, Stream _source, DateTime _modTime, string _comment)
{
if (Access == FileAccess.Read)
throw new InvalidOperationException("Writing is not alowed");
 
long offset;
if (this.Files.Count==0)
offset = 0;
else
{
ZipFileEntry last = this.Files[this.Files.Count-1];
offset = last.HeaderOffset + last.HeaderSize;
}
 
// Prepare the fileinfo
ZipFileEntry zfe = new ZipFileEntry();
zfe.Method = _method;
zfe.EncodeUTF8 = this.EncodeUTF8;
zfe.FilenameInZip = NormalizedFilename(_filenameInZip);
zfe.Comment = (_comment == null ? "" : _comment);
 
// Even though we write the header now, it will have to be rewritten, since we don't know compressed size or crc.
zfe.Crc32 = 0; // to be updated later
zfe.HeaderOffset = (uint)this.ZipFileStream.Position; // offset within file of the start of this local record
zfe.ModifyTime = _modTime;
 
// Write local header
WriteLocalHeader(ref zfe);
zfe.FileOffset = (uint)this.ZipFileStream.Position;
 
// Write file to zip (store)
Store(ref zfe, _source);
_source.Close();
 
this.UpdateCrcAndSizes(ref zfe);
 
Files.Add(zfe);
}
/// <summary>
/// Updates central directory (if pertinent) and close the Zip storage
/// </summary>
/// <remarks>This is a required step, unless automatic dispose is used</remarks>
public void Close()
{
if(this.ZipFileStream == null)
return;
 
if (this.Access != FileAccess.Read)
{
uint centralOffset = (uint)this.ZipFileStream.Position;
uint centralSize = 0;
 
if (this.CentralDirImage != null)
this.ZipFileStream.Write(CentralDirImage, 0, CentralDirImage.Length);
 
for (int i = 0; i < Files.Count; i++)
{
long pos = this.ZipFileStream.Position;
this.WriteCentralDirRecord(Files[i]);
centralSize += (uint)(this.ZipFileStream.Position - pos);
}
 
if (this.CentralDirImage != null)
this.WriteEndRecord(centralSize + (uint)CentralDirImage.Length, centralOffset);
else
this.WriteEndRecord(centralSize, centralOffset);
}
 
if (this.ZipFileStream != null)
{
this.ZipFileStream.Flush();
this.ZipFileStream.Dispose();
this.ZipFileStream = null;
}
}
/// <summary>
/// Read all the file records in the central directory
/// </summary>
/// <returns>List of all entries in directory</returns>
public List<ZipFileEntry> ReadCentralDir()
{
if (this.CentralDirImage == null)
throw new InvalidOperationException("Central directory currently does not exist");
 
List<ZipFileEntry> result = new List<ZipFileEntry>();
 
for (int pointer = 0; pointer < this.CentralDirImage.Length; )
{
uint signature = BitConverter.ToUInt32(CentralDirImage, pointer);
if (signature != 0x02014b50)
break;
 
bool encodeUTF8 = (BitConverter.ToUInt16(CentralDirImage, pointer + 8) & 0x0800) != 0;
ushort method = BitConverter.ToUInt16(CentralDirImage, pointer + 10);
uint modifyTime = BitConverter.ToUInt32(CentralDirImage, pointer + 12);
uint crc32 = BitConverter.ToUInt32(CentralDirImage, pointer + 16);
uint comprSize = BitConverter.ToUInt32(CentralDirImage, pointer + 20);
uint fileSize = BitConverter.ToUInt32(CentralDirImage, pointer + 24);
ushort filenameSize = BitConverter.ToUInt16(CentralDirImage, pointer + 28);
ushort extraSize = BitConverter.ToUInt16(CentralDirImage, pointer + 30);
ushort commentSize = BitConverter.ToUInt16(CentralDirImage, pointer + 32);
uint headerOffset = BitConverter.ToUInt32(CentralDirImage, pointer + 42);
uint headerSize = (uint)( 46 + filenameSize + extraSize + commentSize);
 
Encoding encoder = encodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
 
ZipFileEntry zfe = new ZipFileEntry();
zfe.Method = (Compression)method;
zfe.FilenameInZip = encoder.GetString(CentralDirImage, pointer + 46, filenameSize);
zfe.FileOffset = GetFileOffset(headerOffset);
zfe.FileSize = fileSize;
zfe.CompressedSize = comprSize;
zfe.HeaderOffset = headerOffset;
zfe.HeaderSize = headerSize;
zfe.Crc32 = crc32;
zfe.ModifyTime = DosTimeToDateTime(modifyTime);
if (commentSize > 0)
zfe.Comment = encoder.GetString(CentralDirImage, pointer + 46 + filenameSize + extraSize, commentSize);
 
result.Add(zfe);
pointer += (46 + filenameSize + extraSize + commentSize);
}
 
return result;
}
/// <summary>
/// Copy the contents of a stored file into a physical file
/// </summary>
/// <param name="_zfe">Entry information of file to extract</param>
/// <param name="_filename">Name of file to store uncompressed data</param>
/// <returns>True if success, false if not.</returns>
/// <remarks>Unique compression methods are Store and Deflate</remarks>
public bool ExtractFile(ZipFileEntry _zfe, string _filename)
{
// Make sure the parent directory exist
string path = System.IO.Path.GetDirectoryName(_filename);
 
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
// Check it is directory. If so, do nothing
if (Directory.Exists(_filename))
return true;
 
Stream output = new FileStream(_filename, FileMode.Create, FileAccess.Write);
bool result = ExtractFile(_zfe, output);
if (result)
output.Close();
 
File.SetCreationTime(_filename, _zfe.ModifyTime);
File.SetLastWriteTime(_filename, _zfe.ModifyTime);
return result;
}
/// <summary>
/// Copy the contents of a stored file into an opened stream
/// </summary>
/// <param name="_zfe">Entry information of file to extract</param>
/// <param name="_stream">Stream to store the uncompressed data</param>
/// <returns>True if success, false if not.</returns>
/// <remarks>Unique compression methods are Store and Deflate</remarks>
public bool ExtractFile(ZipFileEntry _zfe, Stream _stream)
{
if (!_stream.CanWrite)
throw new InvalidOperationException("Stream cannot be written");
 
// check signature
byte[] signature = new byte[4];
this.ZipFileStream.Seek(_zfe.HeaderOffset, SeekOrigin.Begin);
this.ZipFileStream.Read(signature, 0, 4);
if (BitConverter.ToUInt32(signature, 0) != 0x04034b50)
return false;
 
// Select input stream for inflating or just reading
Stream inStream;
if (_zfe.Method == Compression.Store)
inStream = this.ZipFileStream;
else if (_zfe.Method == Compression.Deflate)
inStream = new DeflateStream(this.ZipFileStream, CompressionMode.Decompress, true);
else
return false;
 
// Buffered copy
byte[] buffer = new byte[16384];
this.ZipFileStream.Seek(_zfe.FileOffset, SeekOrigin.Begin);
uint bytesPending = _zfe.FileSize;
while (bytesPending > 0)
{
int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length));
_stream.Write(buffer, 0, bytesRead);
bytesPending -= (uint)bytesRead;
}
_stream.Flush();
 
if (_zfe.Method == Compression.Deflate)
inStream.Dispose();
return true;
}
/// <summary>
/// Removes one of many files in storage. It creates a new Zip file.
/// </summary>
/// <param name="_zip">Reference to the current Zip object</param>
/// <param name="_zfes">List of Entries to remove from storage</param>
/// <returns>True if success, false if not</returns>
/// <remarks>This method only works for storage of type FileStream</remarks>
public static bool RemoveEntries(ref ZipStorer _zip, List<ZipFileEntry> _zfes)
{
if (!(_zip.ZipFileStream is FileStream))
throw new InvalidOperationException("RemoveEntries is allowed just over streams of type FileStream");
 
 
//Get full list of entries
List<ZipFileEntry> fullList = _zip.ReadCentralDir();
 
//In order to delete we need to create a copy of the zip file excluding the selected items
string tempZipName = Path.GetTempFileName();
string tempEntryName = Path.GetTempFileName();
 
try
{
ZipStorer tempZip = ZipStorer.Create(tempZipName, string.Empty);
 
foreach (ZipFileEntry zfe in fullList)
{
if (!_zfes.Contains(zfe))
{
if (_zip.ExtractFile(zfe, tempEntryName))
{
tempZip.AddFile(zfe.Method, tempEntryName, zfe.FilenameInZip, zfe.Comment);
}
}
}
_zip.Close();
tempZip.Close();
 
File.Delete(_zip.FileName);
File.Move(tempZipName, _zip.FileName);
 
_zip = ZipStorer.Open(_zip.FileName, _zip.Access);
}
catch
{
return false;
}
finally
{
if (File.Exists(tempZipName))
File.Delete(tempZipName);
if (File.Exists(tempEntryName))
File.Delete(tempEntryName);
}
return true;
}
#endregion
 
#region Private methods
// Calculate the file offset by reading the corresponding local header
private uint GetFileOffset(uint _headerOffset)
{
byte[] buffer = new byte[2];
 
this.ZipFileStream.Seek(_headerOffset + 26, SeekOrigin.Begin);
this.ZipFileStream.Read(buffer, 0, 2);
ushort filenameSize = BitConverter.ToUInt16(buffer, 0);
this.ZipFileStream.Read(buffer, 0, 2);
ushort extraSize = BitConverter.ToUInt16(buffer, 0);
 
return (uint)(30 + filenameSize + extraSize + _headerOffset);
}
/* Local file header:
local file header signature 4 bytes (0x04034b50)
version needed to extract 2 bytes
general purpose bit flag 2 bytes
compression method 2 bytes
last mod file time 2 bytes
last mod file date 2 bytes
crc-32 4 bytes
compressed size 4 bytes
uncompressed size 4 bytes
filename length 2 bytes
extra field length 2 bytes
 
filename (variable size)
extra field (variable size)
*/
private void WriteLocalHeader(ref ZipFileEntry _zfe)
{
long pos = this.ZipFileStream.Position;
Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip);
 
this.ZipFileStream.Write(new byte[] { 80, 75, 3, 4, 20, 0}, 0, 6); // No extra header
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method
this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time
this.ZipFileStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 12); // unused CRC, un/compressed size, updated later
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // filename length
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length
 
this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length);
_zfe.HeaderSize = (uint)(this.ZipFileStream.Position - pos);
}
/* Central directory's File header:
central file header signature 4 bytes (0x02014b50)
version made by 2 bytes
version needed to extract 2 bytes
general purpose bit flag 2 bytes
compression method 2 bytes
last mod file time 2 bytes
last mod file date 2 bytes
crc-32 4 bytes
compressed size 4 bytes
uncompressed size 4 bytes
filename length 2 bytes
extra field length 2 bytes
file comment length 2 bytes
disk number start 2 bytes
internal file attributes 2 bytes
external file attributes 4 bytes
relative offset of local header 4 bytes
 
filename (variable size)
extra field (variable size)
file comment (variable size)
*/
private void WriteCentralDirRecord(ZipFileEntry _zfe)
{
Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip);
byte[] encodedComment = encoder.GetBytes(_zfe.Comment);
 
this.ZipFileStream.Write(new byte[] { 80, 75, 1, 2, 23, 0xB, 20, 0 }, 0, 8);
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method
this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // file CRC
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // compressed file size
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // uncompressed file size
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // Filename in zip
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2);
 
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // disk=0
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // file type: binary
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // Internal file attributes
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0x8100), 0, 2); // External file attributes (normal/readable)
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.HeaderOffset), 0, 4); // Offset of header
 
this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length);
this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length);
}
/* End of central dir record:
end of central dir signature 4 bytes (0x06054b50)
number of this disk 2 bytes
number of the disk with the
start of the central directory 2 bytes
total number of entries in
the central dir on this disk 2 bytes
total number of entries in
the central dir 2 bytes
size of the central directory 4 bytes
offset of start of central
directory with respect to
the starting disk number 4 bytes
zipfile comment length 2 bytes
zipfile comment (variable size)
*/
private void WriteEndRecord(uint _size, uint _offset)
{
Encoding encoder = this.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
byte[] encodedComment = encoder.GetBytes(this.Comment);
 
this.ZipFileStream.Write(new byte[] { 80, 75, 5, 6, 0, 0, 0, 0 }, 0, 8);
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count+ExistingFiles), 0, 2);
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count+ExistingFiles), 0, 2);
this.ZipFileStream.Write(BitConverter.GetBytes(_size), 0, 4);
this.ZipFileStream.Write(BitConverter.GetBytes(_offset), 0, 4);
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2);
this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length);
}
// Copies all source file into storage file
private void Store(ref ZipFileEntry _zfe, Stream _source)
{
byte[] buffer = new byte[16384];
int bytesRead;
uint totalRead = 0;
Stream outStream;
 
long posStart = this.ZipFileStream.Position;
long sourceStart = _source.Position;
 
if (_zfe.Method == Compression.Store)
outStream = this.ZipFileStream;
else
outStream = new DeflateStream(this.ZipFileStream, CompressionMode.Compress, true);
 
_zfe.Crc32 = 0 ^ 0xffffffff;
do
{
bytesRead = _source.Read(buffer, 0, buffer.Length);
totalRead += (uint)bytesRead;
if (bytesRead > 0)
{
outStream.Write(buffer, 0, bytesRead);
 
for (uint i = 0; i < bytesRead; i++)
{
_zfe.Crc32 = ZipStorer.CrcTable[(_zfe.Crc32 ^ buffer[i]) & 0xFF] ^ (_zfe.Crc32 >> 8);
}
}
} while (bytesRead == buffer.Length);
outStream.Flush();
 
if (_zfe.Method == Compression.Deflate)
outStream.Dispose();
 
_zfe.Crc32 ^= 0xffffffff;
_zfe.FileSize = totalRead;
_zfe.CompressedSize = (uint)(this.ZipFileStream.Position - posStart);
 
// Verify for real compression
if (_zfe.Method == Compression.Deflate && !this.ForceDeflating && _source.CanSeek && _zfe.CompressedSize > _zfe.FileSize)
{
// Start operation again with Store algorithm
_zfe.Method = Compression.Store;
this.ZipFileStream.Position = posStart;
this.ZipFileStream.SetLength(posStart);
_source.Position = sourceStart;
this.Store(ref _zfe, _source);
}
}
/* DOS Date and time:
MS-DOS date. The date is a packed value with the following format. Bits Description
0-4 Day of the month (1–31)
5-8 Month (1 = January, 2 = February, and so on)
9-15 Year offset from 1980 (add 1980 to get actual year)
MS-DOS time. The time is a packed value with the following format. Bits Description
0-4 Second divided by 2
5-10 Minute (0–59)
11-15 Hour (0–23 on a 24-hour clock)
*/
private uint DateTimeToDosTime(DateTime _dt)
{
return (uint)(
(_dt.Second / 2) | (_dt.Minute << 5) | (_dt.Hour << 11) |
(_dt.Day<<16) | (_dt.Month << 21) | ((_dt.Year - 1980) << 25));
}
private DateTime DosTimeToDateTime(uint _dt)
{
return new DateTime(
(int)(_dt >> 25) + 1980,
(int)(_dt >> 21) & 15,
(int)(_dt >> 16) & 31,
(int)(_dt >> 11) & 31,
(int)(_dt >> 5) & 63,
(int)(_dt & 31) * 2);
}
 
/* CRC32 algorithm
The 'magic number' for the CRC is 0xdebb20e3.
The proper CRC pre and post conditioning
is used, meaning that the CRC register is
pre-conditioned with all ones (a starting value
of 0xffffffff) and the value is post-conditioned by
taking the one's complement of the CRC residual.
If bit 3 of the general purpose flag is set, this
field is set to zero in the local header and the correct
value is put in the data descriptor and in the central
directory.
*/
private void UpdateCrcAndSizes(ref ZipFileEntry _zfe)
{
long lastPos = this.ZipFileStream.Position; // remember position
 
this.ZipFileStream.Position = _zfe.HeaderOffset + 8;
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method
 
this.ZipFileStream.Position = _zfe.HeaderOffset + 14;
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // Update CRC
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // Compressed size
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // Uncompressed size
 
this.ZipFileStream.Position = lastPos; // restore position
}
// Replaces backslashes with slashes to store in zip header
private string NormalizedFilename(string _filename)
{
string filename = _filename.Replace('\\', '/');
 
int pos = filename.IndexOf(':');
if (pos >= 0)
filename = filename.Remove(0, pos + 1);
 
return filename.Trim('/');
}
// Reads the end-of-central-directory record
private bool ReadFileInfo()
{
if (this.ZipFileStream.Length < 22)
return false;
 
try
{
this.ZipFileStream.Seek(-17, SeekOrigin.End);
BinaryReader br = new BinaryReader(this.ZipFileStream);
do
{
this.ZipFileStream.Seek(-5, SeekOrigin.Current);
UInt32 sig = br.ReadUInt32();
if (sig == 0x06054b50)
{
this.ZipFileStream.Seek(6, SeekOrigin.Current);
 
UInt16 entries = br.ReadUInt16();
Int32 centralSize = br.ReadInt32();
UInt32 centralDirOffset = br.ReadUInt32();
UInt16 commentSize = br.ReadUInt16();
 
// check if comment field is the very last data in file
if (this.ZipFileStream.Position + commentSize != this.ZipFileStream.Length)
return false;
 
// Copy entire central directory to a memory buffer
this.ExistingFiles = entries;
this.CentralDirImage = new byte[centralSize];
this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin);
this.ZipFileStream.Read(this.CentralDirImage, 0, centralSize);
 
// Leave the pointer at the begining of central dir, to append new files
this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin);
return true;
}
} while (this.ZipFileStream.Position > 0);
}
catch { }
 
return false;
}
#endregion
 
#region IDisposable Members
/// <summary>
/// Closes the Zip file stream
/// </summary>
public void Dispose()
{
this.Close();
}
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET/gpx.cs
0,0 → 1,1442
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
namespace GMap.NET
{
using System.Xml.Serialization;
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
[System.Xml.Serialization.XmlRootAttribute("gpx", Namespace="http://www.topografix.com/GPX/1/1", IsNullable=false)]
public partial class gpxType
{
 
private metadataType metadataField;
 
private wptType[] wptField;
 
private rteType[] rteField;
 
private trkType[] trkField;
 
private extensionsType extensionsField;
 
private string versionField;
 
private string creatorField;
 
public gpxType()
{
this.versionField = "1.1";
}
 
/// <remarks/>
public metadataType metadata
{
get
{
return this.metadataField;
}
set
{
this.metadataField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("wpt")]
public wptType[] wpt
{
get
{
return this.wptField;
}
set
{
this.wptField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("rte")]
public rteType[] rte
{
get
{
return this.rteField;
}
set
{
this.rteField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("trk")]
public trkType[] trk
{
get
{
return this.trkField;
}
set
{
this.trkField = value;
}
}
 
/// <remarks/>
public extensionsType extensions
{
get
{
return this.extensionsField;
}
set
{
this.extensionsField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string version
{
get
{
return this.versionField;
}
set
{
this.versionField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string creator
{
get
{
return this.creatorField;
}
set
{
this.creatorField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class metadataType
{
 
private string nameField;
 
private string descField;
 
private personType authorField;
 
private copyrightType copyrightField;
 
private linkType[] linkField;
 
private System.DateTime timeField;
 
private bool timeFieldSpecified;
 
private string keywordsField;
 
private boundsType boundsField;
 
private extensionsType extensionsField;
 
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
 
/// <remarks/>
public string desc
{
get
{
return this.descField;
}
set
{
this.descField = value;
}
}
 
/// <remarks/>
public personType author
{
get
{
return this.authorField;
}
set
{
this.authorField = value;
}
}
 
/// <remarks/>
public copyrightType copyright
{
get
{
return this.copyrightField;
}
set
{
this.copyrightField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("link")]
public linkType[] link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
 
/// <remarks/>
public System.DateTime time
{
get
{
return this.timeField;
}
set
{
this.timeField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool timeSpecified
{
get
{
return this.timeFieldSpecified;
}
set
{
this.timeFieldSpecified = value;
}
}
 
/// <remarks/>
public string keywords
{
get
{
return this.keywordsField;
}
set
{
this.keywordsField = value;
}
}
 
/// <remarks/>
public boundsType bounds
{
get
{
return this.boundsField;
}
set
{
this.boundsField = value;
}
}
 
/// <remarks/>
public extensionsType extensions
{
get
{
return this.extensionsField;
}
set
{
this.extensionsField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class personType
{
 
private string nameField;
 
private emailType emailField;
 
private linkType linkField;
 
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
 
/// <remarks/>
public emailType email
{
get
{
return this.emailField;
}
set
{
this.emailField = value;
}
}
 
/// <remarks/>
public linkType link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class emailType
{
 
private string idField;
 
private string domainField;
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string domain
{
get
{
return this.domainField;
}
set
{
this.domainField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class trksegType
{
 
private wptType[] trkptField;
 
private extensionsType extensionsField;
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("trkpt")]
public wptType[] trkpt
{
get
{
return this.trkptField;
}
set
{
this.trkptField = value;
}
}
 
/// <remarks/>
public extensionsType extensions
{
get
{
return this.extensionsField;
}
set
{
this.extensionsField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class wptType
{
 
private decimal eleField;
 
private bool eleFieldSpecified;
 
private System.DateTime timeField;
 
private bool timeFieldSpecified;
 
private decimal magvarField;
 
private bool magvarFieldSpecified;
 
private decimal geoidheightField;
 
private bool geoidheightFieldSpecified;
 
private string nameField;
 
private string cmtField;
 
private string descField;
 
private string srcField;
 
private linkType[] linkField;
 
private string symField;
 
private string typeField;
 
private fixType fixField;
 
private bool fixFieldSpecified;
 
private string satField;
 
private decimal hdopField;
 
private bool hdopFieldSpecified;
 
private decimal vdopField;
 
private bool vdopFieldSpecified;
 
private decimal pdopField;
 
private bool pdopFieldSpecified;
 
private decimal ageofdgpsdataField;
 
private bool ageofdgpsdataFieldSpecified;
 
private string dgpsidField;
 
private extensionsType extensionsField;
 
private decimal latField;
 
private decimal lonField;
 
/// <remarks/>
public decimal ele
{
get
{
return this.eleField;
}
set
{
this.eleField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool eleSpecified
{
get
{
return this.eleFieldSpecified;
}
set
{
this.eleFieldSpecified = value;
}
}
 
/// <remarks/>
public System.DateTime time
{
get
{
return this.timeField;
}
set
{
this.timeField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool timeSpecified
{
get
{
return this.timeFieldSpecified;
}
set
{
this.timeFieldSpecified = value;
}
}
 
/// <remarks/>
public decimal magvar
{
get
{
return this.magvarField;
}
set
{
this.magvarField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool magvarSpecified
{
get
{
return this.magvarFieldSpecified;
}
set
{
this.magvarFieldSpecified = value;
}
}
 
/// <remarks/>
public decimal geoidheight
{
get
{
return this.geoidheightField;
}
set
{
this.geoidheightField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool geoidheightSpecified
{
get
{
return this.geoidheightFieldSpecified;
}
set
{
this.geoidheightFieldSpecified = value;
}
}
 
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
 
/// <remarks/>
public string cmt
{
get
{
return this.cmtField;
}
set
{
this.cmtField = value;
}
}
 
/// <remarks/>
public string desc
{
get
{
return this.descField;
}
set
{
this.descField = value;
}
}
 
/// <remarks/>
public string src
{
get
{
return this.srcField;
}
set
{
this.srcField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("link")]
public linkType[] link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
 
/// <remarks/>
public string sym
{
get
{
return this.symField;
}
set
{
this.symField = value;
}
}
 
/// <remarks/>
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
 
/// <remarks/>
public fixType fix
{
get
{
return this.fixField;
}
set
{
this.fixField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool fixSpecified
{
get
{
return this.fixFieldSpecified;
}
set
{
this.fixFieldSpecified = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="nonNegativeInteger")]
public string sat
{
get
{
return this.satField;
}
set
{
this.satField = value;
}
}
 
/// <remarks/>
public decimal hdop
{
get
{
return this.hdopField;
}
set
{
this.hdopField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool hdopSpecified
{
get
{
return this.hdopFieldSpecified;
}
set
{
this.hdopFieldSpecified = value;
}
}
 
/// <remarks/>
public decimal vdop
{
get
{
return this.vdopField;
}
set
{
this.vdopField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool vdopSpecified
{
get
{
return this.vdopFieldSpecified;
}
set
{
this.vdopFieldSpecified = value;
}
}
 
/// <remarks/>
public decimal pdop
{
get
{
return this.pdopField;
}
set
{
this.pdopField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool pdopSpecified
{
get
{
return this.pdopFieldSpecified;
}
set
{
this.pdopFieldSpecified = value;
}
}
 
/// <remarks/>
public decimal ageofdgpsdata
{
get
{
return this.ageofdgpsdataField;
}
set
{
this.ageofdgpsdataField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ageofdgpsdataSpecified
{
get
{
return this.ageofdgpsdataFieldSpecified;
}
set
{
this.ageofdgpsdataFieldSpecified = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="integer")]
public string dgpsid
{
get
{
return this.dgpsidField;
}
set
{
this.dgpsidField = value;
}
}
 
/// <remarks/>
public extensionsType extensions
{
get
{
return this.extensionsField;
}
set
{
this.extensionsField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal lat
{
get
{
return this.latField;
}
set
{
this.latField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal lon
{
get
{
return this.lonField;
}
set
{
this.lonField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class linkType
{
 
private string textField;
 
private string typeField;
 
private string hrefField;
 
/// <remarks/>
public string text
{
get
{
return this.textField;
}
set
{
this.textField = value;
}
}
 
/// <remarks/>
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="anyURI")]
public string href
{
get
{
return this.hrefField;
}
set
{
this.hrefField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public enum fixType
{
 
/// <remarks/>
none,
 
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("2d")]
Item2d,
 
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("3d")]
Item3d,
 
/// <remarks/>
dgps,
 
/// <remarks/>
pps,
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class extensionsType
{
 
private System.Xml.XmlElement[] anyField;
 
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any
{
get
{
return this.anyField;
}
set
{
this.anyField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class trkType
{
 
private string nameField;
 
private string cmtField;
 
private string descField;
 
private string srcField;
 
private linkType[] linkField;
 
private string numberField;
 
private string typeField;
 
private extensionsType extensionsField;
 
private trksegType[] trksegField;
 
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
 
/// <remarks/>
public string cmt
{
get
{
return this.cmtField;
}
set
{
this.cmtField = value;
}
}
 
/// <remarks/>
public string desc
{
get
{
return this.descField;
}
set
{
this.descField = value;
}
}
 
/// <remarks/>
public string src
{
get
{
return this.srcField;
}
set
{
this.srcField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("link")]
public linkType[] link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="nonNegativeInteger")]
public string number
{
get
{
return this.numberField;
}
set
{
this.numberField = value;
}
}
 
/// <remarks/>
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
 
/// <remarks/>
public extensionsType extensions
{
get
{
return this.extensionsField;
}
set
{
this.extensionsField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("trkseg")]
public trksegType[] trkseg
{
get
{
return this.trksegField;
}
set
{
this.trksegField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class rteType
{
 
private string nameField;
 
private string cmtField;
 
private string descField;
 
private string srcField;
 
private linkType[] linkField;
 
private string numberField;
 
private string typeField;
 
private extensionsType extensionsField;
 
private wptType[] rteptField;
 
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
 
/// <remarks/>
public string cmt
{
get
{
return this.cmtField;
}
set
{
this.cmtField = value;
}
}
 
/// <remarks/>
public string desc
{
get
{
return this.descField;
}
set
{
this.descField = value;
}
}
 
/// <remarks/>
public string src
{
get
{
return this.srcField;
}
set
{
this.srcField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("link")]
public linkType[] link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="nonNegativeInteger")]
public string number
{
get
{
return this.numberField;
}
set
{
this.numberField = value;
}
}
 
/// <remarks/>
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
 
/// <remarks/>
public extensionsType extensions
{
get
{
return this.extensionsField;
}
set
{
this.extensionsField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("rtept")]
public wptType[] rtept
{
get
{
return this.rteptField;
}
set
{
this.rteptField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class boundsType
{
 
private decimal minlatField;
 
private decimal minlonField;
 
private decimal maxlatField;
 
private decimal maxlonField;
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal minlat
{
get
{
return this.minlatField;
}
set
{
this.minlatField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal minlon
{
get
{
return this.minlonField;
}
set
{
this.minlonField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal maxlat
{
get
{
return this.maxlatField;
}
set
{
this.maxlatField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal maxlon
{
get
{
return this.maxlonField;
}
set
{
this.maxlonField = value;
}
}
}
 
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.topografix.com/GPX/1/1")]
public partial class copyrightType
{
 
private string yearField;
 
private string licenseField;
 
private string authorField;
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="gYear")]
public string year
{
get
{
return this.yearField;
}
set
{
this.yearField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="anyURI")]
public string license
{
get
{
return this.licenseField;
}
set
{
this.licenseField = value;
}
}
 
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string author
{
get
{
return this.authorField;
}
set
{
this.authorField = value;
}
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.CacheProviders/MSSQLCEPureImageCache.cs
0,0 → 1,255

namespace GMap.NET.CacheProviders
{
#if !SQLite
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using SqlCommand = System.Data.SqlServerCe.SqlCeCommand;
using SqlConnection = System.Data.SqlServerCe.SqlCeConnection;
using GMap.NET.MapProviders;
 
/// <summary>
/// image cache for ms sql server
/// </summary>
public class MsSQLCePureImageCache : PureImageCache, IDisposable
{
string cache;
string gtileCache;
 
/// <summary>
/// local cache location
/// </summary>
public string CacheLocation
{
get
{
return cache;
}
set
{
cache = value;
gtileCache = Path.Combine(cache, "TileDBv3") + Path.DirectorySeparatorChar + GMapProvider.LanguageStr + Path.DirectorySeparatorChar;
}
}
 
SqlCommand cmdInsert;
SqlCommand cmdFetch;
SqlConnection cnGet;
SqlConnection cnSet;
 
/// <summary>
/// is cache initialized
/// </summary>
public volatile bool Initialized = false;
 
/// <summary>
/// inits connection to server
/// </summary>
/// <returns></returns>
public bool Initialize()
{
if(!Initialized)
{
#region prepare mssql & cache table
try
{
// precrete dir
if(!Directory.Exists(gtileCache))
{
Directory.CreateDirectory(gtileCache);
}
 
string connectionString = string.Format("Data Source={0}Data.sdf", gtileCache);
 
if(!File.Exists(gtileCache + "Data.sdf"))
{
using(System.Data.SqlServerCe.SqlCeEngine engine = new System.Data.SqlServerCe.SqlCeEngine(connectionString))
{
engine.CreateDatabase();
}
 
try
{
using(SqlConnection c = new SqlConnection(connectionString))
{
c.Open();
 
using(SqlCommand cmd = new SqlCommand(
"CREATE TABLE [GMapNETcache] ( \n"
+ " [Type] [int] NOT NULL, \n"
+ " [Zoom] [int] NOT NULL, \n"
+ " [X] [int] NOT NULL, \n"
+ " [Y] [int] NOT NULL, \n"
+ " [Tile] [image] NOT NULL, \n"
+ " CONSTRAINT [PK_GMapNETcache] PRIMARY KEY (Type, Zoom, X, Y) \n"
+ ")", c))
{
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
try
{
File.Delete(gtileCache + "Data.sdf");
}
catch
{
}
 
throw ex;
}
}
 
// different connections so the multi-thread inserts and selects don't collide on open readers.
this.cnGet = new SqlConnection(connectionString);
this.cnGet.Open();
this.cnSet = new SqlConnection(connectionString);
this.cnSet.Open();
 
this.cmdFetch = new SqlCommand("SELECT [Tile] FROM [GMapNETcache] WITH (NOLOCK) WHERE [X]=@x AND [Y]=@y AND [Zoom]=@zoom AND [Type]=@type", cnGet);
this.cmdFetch.Parameters.Add("@x", System.Data.SqlDbType.Int);
this.cmdFetch.Parameters.Add("@y", System.Data.SqlDbType.Int);
this.cmdFetch.Parameters.Add("@zoom", System.Data.SqlDbType.Int);
this.cmdFetch.Parameters.Add("@type", System.Data.SqlDbType.Int);
this.cmdFetch.Prepare();
 
this.cmdInsert = new SqlCommand("INSERT INTO [GMapNETcache] ( [X], [Y], [Zoom], [Type], [Tile] ) VALUES ( @x, @y, @zoom, @type, @tile )", cnSet);
this.cmdInsert.Parameters.Add("@x", System.Data.SqlDbType.Int);
this.cmdInsert.Parameters.Add("@y", System.Data.SqlDbType.Int);
this.cmdInsert.Parameters.Add("@zoom", System.Data.SqlDbType.Int);
this.cmdInsert.Parameters.Add("@type", System.Data.SqlDbType.Int);
this.cmdInsert.Parameters.Add("@tile", System.Data.SqlDbType.Image); //, calcmaximgsize);
//can't prepare insert because of the IMAGE field having a variable size. Could set it to some 'maximum' size?
 
Initialized = true;
}
catch(Exception ex)
{
Initialized = false;
Debug.WriteLine(ex.Message);
}
#endregion
}
return Initialized;
}
 
#region IDisposable Members
public void Dispose()
{
lock(cmdInsert)
{
if(cmdInsert != null)
{
cmdInsert.Dispose();
cmdInsert = null;
}
 
if(cnSet != null)
{
cnSet.Dispose();
cnSet = null;
}
}
 
lock(cmdFetch)
{
if(cmdFetch != null)
{
cmdFetch.Dispose();
cmdFetch = null;
}
 
if(cnGet != null)
{
cnGet.Dispose();
cnGet = null;
}
}
Initialized = false;
}
#endregion
 
#region PureImageCache Members
public bool PutImageToCache(byte[] tile, int type, GPoint pos, int zoom)
{
bool ret = true;
{
if(Initialize())
{
try
{
lock(cmdInsert)
{
cmdInsert.Parameters["@x"].Value = pos.X;
cmdInsert.Parameters["@y"].Value = pos.Y;
cmdInsert.Parameters["@zoom"].Value = zoom;
cmdInsert.Parameters["@type"].Value = type;
cmdInsert.Parameters["@tile"].Value = tile;
cmdInsert.ExecuteNonQuery();
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
ret = false;
Dispose();
}
}
}
return ret;
}
 
public PureImage GetImageFromCache(int type, GPoint pos, int zoom)
{
PureImage ret = null;
{
if(Initialize())
{
try
{
object odata = null;
lock(cmdFetch)
{
cmdFetch.Parameters["@x"].Value = pos.X;
cmdFetch.Parameters["@y"].Value = pos.Y;
cmdFetch.Parameters["@zoom"].Value = zoom;
cmdFetch.Parameters["@type"].Value = type;
odata = cmdFetch.ExecuteScalar();
}
 
if(odata != null && odata != DBNull.Value)
{
byte[] tile = (byte[])odata;
if(tile != null && tile.Length > 0)
{
if(GMapProvider.TileImageProxy != null)
{
ret = GMapProvider.TileImageProxy.FromArray(tile);
}
}
tile = null;
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
ret = null;
Dispose();
}
}
}
return ret;
}
 
int PureImageCache.DeleteOlderThan(DateTime date, int ? type)
{
throw new NotImplementedException();
}
#endregion
}
#endif
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.CacheProviders/MSSQLPureImageCache.cs
0,0 → 1,255

namespace GMap.NET.CacheProviders
{
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using GMap.NET.MapProviders;
 
/// <summary>
/// image cache for ms sql server
/// optimized by mmurfinsimmons@gmail.com
/// </summary>
public class MsSQLPureImageCache : PureImageCache, IDisposable
{
string connectionString = string.Empty;
public string ConnectionString
{
get
{
return connectionString;
}
set
{
if(connectionString != value)
{
connectionString = value;
 
if(Initialized)
{
Dispose();
Initialize();
}
}
}
}
 
SqlCommand cmdInsert;
SqlCommand cmdFetch;
SqlConnection cnGet;
SqlConnection cnSet;
 
bool initialized = false;
 
/// <summary>
/// is cache initialized
/// </summary>
public bool Initialized
{
get
{
lock(this)
{
return initialized;
}
}
private set
{
lock(this)
{
initialized = value;
}
}
}
 
/// <summary>
/// inits connection to server
/// </summary>
/// <returns></returns>
public bool Initialize()
{
lock(this)
{
if(!Initialized)
{
#region prepare mssql & cache table
try
{
// different connections so the multi-thread inserts and selects don't collide on open readers.
this.cnGet = new SqlConnection(connectionString);
this.cnGet.Open();
this.cnSet = new SqlConnection(connectionString);
this.cnSet.Open();
 
bool tableexists = false;
using(SqlCommand cmd = new SqlCommand("select object_id('GMapNETcache')", cnGet))
{
object objid = cmd.ExecuteScalar();
tableexists = (objid != null && objid != DBNull.Value);
}
if(!tableexists)
{
using(SqlCommand cmd = new SqlCommand(
"CREATE TABLE [GMapNETcache] ( \n"
+ " [Type] [int] NOT NULL, \n"
+ " [Zoom] [int] NOT NULL, \n"
+ " [X] [int] NOT NULL, \n"
+ " [Y] [int] NOT NULL, \n"
+ " [Tile] [image] NOT NULL, \n"
+ " CONSTRAINT [PK_GMapNETcache] PRIMARY KEY CLUSTERED (Type, Zoom, X, Y) \n"
+ ")", cnGet))
{
cmd.ExecuteNonQuery();
}
}
 
this.cmdFetch = new SqlCommand("SELECT [Tile] FROM [GMapNETcache] WITH (NOLOCK) WHERE [X]=@x AND [Y]=@y AND [Zoom]=@zoom AND [Type]=@type", cnGet);
this.cmdFetch.Parameters.Add("@x", System.Data.SqlDbType.Int);
this.cmdFetch.Parameters.Add("@y", System.Data.SqlDbType.Int);
this.cmdFetch.Parameters.Add("@zoom", System.Data.SqlDbType.Int);
this.cmdFetch.Parameters.Add("@type", System.Data.SqlDbType.Int);
this.cmdFetch.Prepare();
 
this.cmdInsert = new SqlCommand("INSERT INTO [GMapNETcache] ( [X], [Y], [Zoom], [Type], [Tile] ) VALUES ( @x, @y, @zoom, @type, @tile )", cnSet);
this.cmdInsert.Parameters.Add("@x", System.Data.SqlDbType.Int);
this.cmdInsert.Parameters.Add("@y", System.Data.SqlDbType.Int);
this.cmdInsert.Parameters.Add("@zoom", System.Data.SqlDbType.Int);
this.cmdInsert.Parameters.Add("@type", System.Data.SqlDbType.Int);
this.cmdInsert.Parameters.Add("@tile", System.Data.SqlDbType.Image); //, calcmaximgsize);
//can't prepare insert because of the IMAGE field having a variable size. Could set it to some 'maximum' size?
 
Initialized = true;
}
catch(Exception ex)
{
this.initialized = false;
Debug.WriteLine(ex.Message);
}
#endregion
}
return Initialized;
}
}
 
#region IDisposable Members
public void Dispose()
{
lock(cmdInsert)
{
if(cmdInsert != null)
{
cmdInsert.Dispose();
cmdInsert = null;
}
 
if(cnSet != null)
{
cnSet.Dispose();
cnSet = null;
}
}
 
lock(cmdFetch)
{
if(cmdFetch != null)
{
cmdFetch.Dispose();
cmdFetch = null;
}
 
if(cnGet != null)
{
cnGet.Dispose();
cnGet = null;
}
}
Initialized = false;
}
#endregion
 
#region PureImageCache Members
public bool PutImageToCache(byte[] tile, int type, GPoint pos, int zoom)
{
bool ret = true;
{
if(Initialize())
{
try
{
lock(cmdInsert)
{
cmdInsert.Parameters["@x"].Value = pos.X;
cmdInsert.Parameters["@y"].Value = pos.Y;
cmdInsert.Parameters["@zoom"].Value = zoom;
cmdInsert.Parameters["@type"].Value = type;
cmdInsert.Parameters["@tile"].Value = tile;
cmdInsert.ExecuteNonQuery();
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
ret = false;
Dispose();
}
}
}
return ret;
}
 
public PureImage GetImageFromCache(int type, GPoint pos, int zoom)
{
PureImage ret = null;
{
if(Initialize())
{
try
{
object odata = null;
lock(cmdFetch)
{
cmdFetch.Parameters["@x"].Value = pos.X;
cmdFetch.Parameters["@y"].Value = pos.Y;
cmdFetch.Parameters["@zoom"].Value = zoom;
cmdFetch.Parameters["@type"].Value = type;
odata = cmdFetch.ExecuteScalar();
}
 
if(odata != null && odata != DBNull.Value)
{
byte[] tile = (byte[])odata;
if(tile != null && tile.Length > 0)
{
if(GMapProvider.TileImageProxy != null)
{
ret = GMapProvider.TileImageProxy.FromArray(tile);
}
}
tile = null;
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
ret = null;
Dispose();
}
}
}
return ret;
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="date"></param>
/// <param name="type"></param>
/// <returns></returns>
int PureImageCache.DeleteOlderThan(DateTime date, int ? type)
{
throw new NotImplementedException();
}
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.CacheProviders/MemoryCache.cs
0,0 → 1,168

namespace GMap.NET.CacheProviders
{
using System.Diagnostics;
using GMap.NET.Internals;
using System;
 
public class MemoryCache : IDisposable
{
readonly KiberTileCache TilesInMemory = new KiberTileCache();
 
FastReaderWriterLock kiberCacheLock = new FastReaderWriterLock();
 
/// <summary>
/// the amount of tiles in MB to keep in memmory, default: 22MB, if each ~100Kb it's ~222 tiles
/// </summary>
public int Capacity
{
get
{
kiberCacheLock.AcquireReaderLock();
try
{
return TilesInMemory.MemoryCacheCapacity;
}
finally
{
kiberCacheLock.ReleaseReaderLock();
}
}
set
{
kiberCacheLock.AcquireWriterLock();
try
{
TilesInMemory.MemoryCacheCapacity = value;
}
finally
{
kiberCacheLock.ReleaseWriterLock();
}
}
}
 
/// <summary>
/// current memmory cache size in MB
/// </summary>
public double Size
{
get
{
kiberCacheLock.AcquireReaderLock();
try
{
return TilesInMemory.MemoryCacheSize;
}
finally
{
kiberCacheLock.ReleaseReaderLock();
}
}
}
 
public void Clear()
{
kiberCacheLock.AcquireWriterLock();
try
{
TilesInMemory.Clear();
}
finally
{
kiberCacheLock.ReleaseWriterLock();
}
}
 
// ...
 
internal byte[] GetTileFromMemoryCache(RawTile tile)
{
kiberCacheLock.AcquireReaderLock();
try
{
byte[] ret = null;
if(TilesInMemory.TryGetValue(tile, out ret))
{
return ret;
}
}
finally
{
kiberCacheLock.ReleaseReaderLock();
}
return null;
}
 
internal void AddTileToMemoryCache(RawTile tile, byte[] data)
{
if(data != null)
{
kiberCacheLock.AcquireWriterLock();
try
{
if(!TilesInMemory.ContainsKey(tile))
{
TilesInMemory.Add(tile, data);
}
}
finally
{
kiberCacheLock.ReleaseWriterLock();
}
}
#if DEBUG
else
{
Debug.WriteLine("adding empty data to MemoryCache ;} ");
if(Debugger.IsAttached)
{
Debugger.Break();
}
}
#endif
}
 
internal void RemoveOverload()
{
kiberCacheLock.AcquireWriterLock();
try
{
TilesInMemory.RemoveMemoryOverload();
}
finally
{
kiberCacheLock.ReleaseWriterLock();
}
}
 
#region IDisposable Members
 
~MemoryCache()
{
Dispose(false);
}
 
void Dispose(bool disposing)
{
if(kiberCacheLock != null)
{
if(disposing)
{
Clear();
}
 
kiberCacheLock.Dispose();
kiberCacheLock = null;
}
}
 
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
 
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.CacheProviders/MySQLPureImageCache.cs
0,0 → 1,260

namespace GMap.NET.CacheProviders
{
#if MySQL
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using GMap.NET;
using MySql.Data.MySqlClient;
using GMap.NET.MapProviders;
 
/// <summary>
/// image cache for mysql server
/// </summary>
public class MySQLPureImageCache : PureImageCache, IDisposable
{
string connectionString = string.Empty;
public string ConnectionString
{
get
{
return connectionString;
}
set
{
if(connectionString != value)
{
connectionString = value;
 
if(Initialized)
{
Dispose();
Initialize();
}
}
}
}
 
MySqlCommand cmdInsert;
MySqlCommand cmdFetch;
MySqlConnection cnGet;
MySqlConnection cnSet;
 
bool initialized = false;
 
/// <summary>
/// is cache initialized
/// </summary>
public bool Initialized
{
get
{
lock(this)
{
return initialized;
}
}
private set
{
lock(this)
{
initialized = value;
}
}
}
 
/// <summary>
/// inits connection to server
/// </summary>
/// <returns></returns>
public bool Initialize()
{
lock(this)
{
if(!initialized)
{
#region prepare mssql & cache table
try
{
// different connections so the multi-thread inserts and selects don't collide on open readers.
this.cnGet = new MySqlConnection(connectionString);
this.cnGet.Open();
this.cnSet = new MySqlConnection(connectionString);
this.cnSet.Open();
 
{
using(MySqlCommand cmd = new MySqlCommand(
@" CREATE TABLE IF NOT EXISTS `gmapnetcache` (
`Type` int(10) NOT NULL,
`Zoom` int(10) NOT NULL,
`X` int(10) NOT NULL,
`Y` int(10) NOT NULL,
`Tile` longblob NOT NULL,
PRIMARY KEY (`Type`,`Zoom`,`X`,`Y`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;", cnGet))
{
cmd.ExecuteNonQuery();
}
}
 
this.cmdFetch = new MySqlCommand("SELECT Tile FROM `gmapnetcache` WHERE Type=@type AND Zoom=@zoom AND X=@x AND Y=@y", cnGet);
this.cmdFetch.Parameters.Add("@type", MySqlDbType.Int32);
this.cmdFetch.Parameters.Add("@zoom", MySqlDbType.Int32);
this.cmdFetch.Parameters.Add("@x", MySqlDbType.Int32);
this.cmdFetch.Parameters.Add("@y", MySqlDbType.Int32);
this.cmdFetch.Prepare();
 
this.cmdInsert = new MySqlCommand("INSERT INTO `gmapnetcache` ( Type, Zoom, X, Y, Tile ) VALUES ( @type, @zoom, @x, @y, @tile )", cnSet);
this.cmdInsert.Parameters.Add("@type", MySqlDbType.Int32);
this.cmdInsert.Parameters.Add("@zoom", MySqlDbType.Int32);
this.cmdInsert.Parameters.Add("@x", MySqlDbType.Int32);
this.cmdInsert.Parameters.Add("@y", MySqlDbType.Int32);
this.cmdInsert.Parameters.Add("@tile", MySqlDbType.Blob); //, calcmaximgsize);
//can't prepare insert because of the IMAGE field having a variable size. Could set it to some 'maximum' size?
 
Initialized = true;
}
catch(Exception ex)
{
this.initialized = false;
Debug.WriteLine(ex.Message);
}
#endregion
}
return initialized;
}
}
 
#region IDisposable Members
 
public void Dispose()
{
lock(cmdInsert)
{
if(cmdInsert != null)
{
cmdInsert.Dispose();
cmdInsert = null;
}
 
if(cnSet != null)
{
cnSet.Dispose();
cnSet = null;
}
}
 
lock(cmdFetch)
{
if(cmdFetch != null)
{
cmdFetch.Dispose();
cmdFetch = null;
}
 
if(cnGet != null)
{
cnGet.Dispose();
cnGet = null;
}
}
Initialized = false;
}
#endregion
 
#region PureImageCache Members
public bool PutImageToCache(byte[] tile, int type, GPoint pos, int zoom)
{
bool ret = true;
{
if(Initialize())
{
try
{
lock(cmdInsert)
{
cnSet.Ping();
 
if(cnSet.State != ConnectionState.Open)
{
cnSet.Open();
}
 
cmdInsert.Parameters["@type"].Value = type;
cmdInsert.Parameters["@zoom"].Value = zoom;
cmdInsert.Parameters["@x"].Value = pos.X;
cmdInsert.Parameters["@y"].Value = pos.Y;
cmdInsert.Parameters["@tile"].Value = tile;
cmdInsert.ExecuteNonQuery();
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
ret = false;
Dispose();
}
}
}
return ret;
}
 
public PureImage GetImageFromCache(int type, GPoint pos, int zoom)
{
PureImage ret = null;
{
if(Initialize())
{
try
{
object odata = null;
lock(cmdFetch)
{
cnGet.Ping();
 
if(cnGet.State != ConnectionState.Open)
{
cnGet.Open();
}
 
cmdFetch.Parameters["@type"].Value = type;
cmdFetch.Parameters["@zoom"].Value = zoom;
cmdFetch.Parameters["@x"].Value = pos.X;
cmdFetch.Parameters["@y"].Value = pos.Y;
odata = cmdFetch.ExecuteScalar();
}
 
if(odata != null && odata != DBNull.Value)
{
byte[] tile = (byte[])odata;
if(tile != null && tile.Length > 0)
{
if(GMapProvider.TileImageProxy != null)
{
ret = GMapProvider.TileImageProxy.FromArray(tile);
}
}
tile = null;
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
ret = null;
Dispose();
}
}
}
return ret;
}
 
int PureImageCache.DeleteOlderThan(DateTime date, int ? type)
{
throw new NotImplementedException();
}
#endregion
}
#endif
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.CacheProviders/PostgreSQLPureImageCache.cs
0,0 → 1,275

namespace GMap.NET.CacheProviders
{
#if PostgreSQL
using System;
using System.Diagnostics;
using System.IO;
using Npgsql;
using NpgsqlTypes;
using GMap.NET.MapProviders;
 
/// <summary>
/// image cache for postgresql server
/// </summary>
public class PostgreSQLPureImageCache : PureImageCache, IDisposable
{
string connectionString = string.Empty;
public string ConnectionString
{
get
{
return connectionString;
}
set
{
if(connectionString != value)
{
connectionString = value;
 
if(Initialized)
{
Dispose();
Initialize();
}
}
}
}
 
NpgsqlCommand cmdInsert;
NpgsqlCommand cmdFetch;
NpgsqlConnection cnGet;
NpgsqlConnection cnSet;
 
bool initialized = false;
 
/// <summary>
/// is cache initialized
/// </summary>
public bool Initialized
{
get
{
lock(this)
{
return initialized;
}
}
private set
{
lock(this)
{
initialized = value;
}
}
}
 
/// <summary>
/// inits connection to server
/// </summary>
/// <returns></returns>
public bool Initialize()
{
lock(this)
{
if(!Initialized)
{
#region prepare postgresql & cache table
 
try
{
// different connections so the multi-thread inserts and selects don't collide on open readers.
this.cnGet = new NpgsqlConnection(connectionString);
this.cnGet.Open();
this.cnSet = new NpgsqlConnection(connectionString);
this.cnSet.Open();
 
bool tableexists = false;
using(NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.CommandText = "SELECT COUNT(*) FROM information_schema.tables WHERE table_name='GMapNETcache'";
cmd.Connection = cnGet;
object cnt = cmd.ExecuteScalar();
tableexists = ((long)cnt == 1);
}
 
if(!tableexists)
{
using(NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.Connection = cnGet;
 
// create tile-cache table
cmd.CommandText = "CREATE TABLE \"GMapNETcache\" ( \n"
+ " \"Type\" integer NOT NULL, \n"
+ " \"Zoom\" integer NOT NULL, \n"
+ " \"X\" integer NOT NULL, \n"
+ " \"Y\" integer NOT NULL, \n"
+ " \"Tile\" bytea NOT NULL, \n"
+ " CONSTRAINT \"PK_GMapNETcache\" PRIMARY KEY ( \"Type\", \"Zoom\", \"X\", \"Y\" ) )";
cmd.ExecuteNonQuery();
 
// allows out-of-line storage but not compression of tile data
// see http://www.postgresql.org/docs/9.0/static/storage-toast.html
cmd.CommandText = "ALTER TABLE \"GMapNETcache\" \n"
+ " ALTER COLUMN \"Tile\" SET STORAGE EXTERNAL";
cmd.ExecuteNonQuery();
 
// select pk index for cluster operations
cmd.CommandText = "ALTER TABLE \"GMapNETcache\" \n"
+ " CLUSTER ON \"PK_GMapNETcache\"";
cmd.ExecuteNonQuery();
}
}
 
this.cmdFetch = new NpgsqlCommand("SELECT \"Tile\" FROM \"GMapNETcache\" WHERE \"X\"=@x AND \"Y\"=@y AND \"Zoom\"=@zoom AND \"Type\"=@type", cnGet);
this.cmdFetch.Parameters.Add("@x", NpgsqlDbType.Integer);
this.cmdFetch.Parameters.Add("@y", NpgsqlDbType.Integer);
this.cmdFetch.Parameters.Add("@zoom", NpgsqlDbType.Integer);
this.cmdFetch.Parameters.Add("@type", NpgsqlDbType.Integer);
this.cmdFetch.Prepare();
 
this.cmdInsert = new NpgsqlCommand("INSERT INTO \"GMapNETcache\" ( \"X\", \"Y\", \"Zoom\", \"Type\", \"Tile\" ) VALUES ( @x, @y, @zoom, @type, @tile )", cnSet);
this.cmdInsert.Parameters.Add("@x", NpgsqlDbType.Integer);
this.cmdInsert.Parameters.Add("@y", NpgsqlDbType.Integer);
this.cmdInsert.Parameters.Add("@zoom", NpgsqlDbType.Integer);
this.cmdInsert.Parameters.Add("@type", NpgsqlDbType.Integer);
this.cmdInsert.Parameters.Add("@tile", NpgsqlDbType.Bytea);
this.cmdInsert.Prepare();
 
Initialized = true;
}
catch(Exception ex)
{
this.initialized = false;
Debug.WriteLine(ex.Message);
}
 
#endregion
}
 
return Initialized;
}
}
 
#region IDisposable Members
 
public void Dispose()
{
lock(cmdInsert)
{
if(cmdInsert != null)
{
cmdInsert.Dispose();
cmdInsert = null;
}
 
if(cnSet != null)
{
cnSet.Dispose();
cnSet = null;
}
}
 
lock(cmdFetch)
{
if(cmdFetch != null)
{
cmdFetch.Dispose();
cmdFetch = null;
}
 
if(cnGet != null)
{
cnGet.Dispose();
cnGet = null;
}
}
 
Initialized = false;
}
 
#endregion
 
#region PureImageCache Members
 
public bool PutImageToCache(byte[] tile, int type, GPoint pos, int zoom)
{
bool ret = true;
 
if(Initialize())
{
try
{
lock(cmdInsert)
{
cmdInsert.Parameters["@x"].Value = pos.X;
cmdInsert.Parameters["@y"].Value = pos.Y;
cmdInsert.Parameters["@zoom"].Value = zoom;
cmdInsert.Parameters["@type"].Value = type;
cmdInsert.Parameters["@tile"].Value = tile;
cmdInsert.ExecuteNonQuery();
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
ret = false;
Dispose();
}
}
 
return ret;
}
 
public PureImage GetImageFromCache(int type, GPoint pos, int zoom)
{
PureImage ret = null;
 
if(Initialize())
{
try
{
object odata = null;
lock(cmdFetch)
{
cmdFetch.Parameters["@x"].Value = pos.X;
cmdFetch.Parameters["@y"].Value = pos.Y;
cmdFetch.Parameters["@zoom"].Value = zoom;
cmdFetch.Parameters["@type"].Value = type;
odata = cmdFetch.ExecuteScalar();
}
 
if(odata != null && odata != DBNull.Value)
{
byte[] tile = (byte[])odata;
if(tile != null && tile.Length > 0)
{
if(GMapProvider.TileImageProxy != null)
{
ret = GMapProvider.TileImageProxy.FromArray(tile);
}
}
tile = null;
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
ret = null;
Dispose();
}
}
 
return ret;
}
 
int PureImageCache.DeleteOlderThan(DateTime date, int ? type)
{
throw new NotImplementedException();
}
 
#endregion
}
#endif
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.CacheProviders/SQLitePureImageCache.cs
0,0 → 1,856

namespace GMap.NET.CacheProviders
{
#if SQLite
 
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Text;
using System;
using System.Diagnostics;
using System.Globalization;
using GMap.NET.MapProviders;
using System.Threading;
 
#if !MONO
using System.Data.SQLite;
using GMap.NET.Internals;
#else
using SQLiteConnection = Mono.Data.Sqlite.SqliteConnection;
using SQLiteTransaction = Mono.Data.Sqlite.SqliteTransaction;
using SQLiteCommand = Mono.Data.Sqlite.SqliteCommand;
using SQLiteDataReader = Mono.Data.Sqlite.SqliteDataReader;
using SQLiteParameter = Mono.Data.Sqlite.SqliteParameter;
#endif
 
/// <summary>
/// ultra fast cache system for tiles
/// </summary>
public class SQLitePureImageCache : PureImageCache
{
#if !PocketPC
#if !MONO
static SQLitePureImageCache()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
 
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
if(args.Name.StartsWith("System.Data.SQLite", StringComparison.OrdinalIgnoreCase))
{
string appDataDir = CacheLocator.GetApplicationDataFolderPath();
if(string.IsNullOrEmpty(appDataDir))
{
return null;
}
 
string dllDir = appDataDir + "DllCache" + Path.DirectorySeparatorChar;
string dll = dllDir + "SQLite_v98_NET" + Environment.Version.Major + "_" + (IntPtr.Size == 8 ? "x64" : "x86") + Path.DirectorySeparatorChar + "System.Data.SQLite.DLL";
if(!File.Exists(dll))
{
string dir = Path.GetDirectoryName(dll);
if(!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
 
Debug.WriteLine("Saving to DllCache: " + dll);
 
if(Environment.Version.Major == 2)
{
using(MemoryStream gzipDll = new MemoryStream((IntPtr.Size == 8 ? Properties.Resources.System_Data_SQLite_x64_NET2_dll : Properties.Resources.System_Data_SQLite_x86_NET2_dll)))
{
using(var gs = new System.IO.Compression.GZipStream(gzipDll, System.IO.Compression.CompressionMode.Decompress))
{
using(MemoryStream exctDll = new MemoryStream())
{
byte[] tmp = new byte[1024 * 256];
int r = 0;
while((r = gs.Read(tmp, 0, tmp.Length)) > 0)
{
exctDll.Write(tmp, 0, r);
}
File.WriteAllBytes(dll, exctDll.ToArray());
}
}
}
}
else if(Environment.Version.Major == 4)
{
using(MemoryStream gzipDll = new MemoryStream((IntPtr.Size == 8 ? Properties.Resources.System_Data_SQLite_x64_NET4_dll : Properties.Resources.System_Data_SQLite_x86_NET4_dll)))
{
using(var gs = new System.IO.Compression.GZipStream(gzipDll, System.IO.Compression.CompressionMode.Decompress))
{
using(MemoryStream exctDll = new MemoryStream())
{
byte[] tmp = new byte[1024 * 256];
int r = 0;
while((r = gs.Read(tmp, 0, tmp.Length)) > 0)
{
exctDll.Write(tmp, 0, r);
}
File.WriteAllBytes(dll, exctDll.ToArray());
}
}
}
}
}
 
Debug.WriteLine("Assembly.LoadFile: " + dll);
 
return System.Reflection.Assembly.LoadFile(dll);
}
return null;
}
 
static int ping = 0;
 
/// <summary>
/// triggers dynamic sqlite loading
/// </summary>
public static void Ping()
{
if (++ping == 1)
{
Trace.WriteLine("SQLiteVersion: " + SQLiteConnection.SQLiteVersion + " | " + SQLiteConnection.SQLiteSourceId + " | " + SQLiteConnection.DefineConstants);
}
}
#endif
#endif
 
string cache;
string gtileCache;
string dir;
string db;
bool Created = false;
 
public string GtileCache
{
get
{
return gtileCache;
}
}
 
/// <summary>
/// local cache location
/// </summary>
public string CacheLocation
{
get
{
return cache;
}
set
{
cache = value;
 
gtileCache = Path.Combine(cache, "TileDBv5") + Path.DirectorySeparatorChar;
 
dir = gtileCache + GMapProvider.LanguageStr + Path.DirectorySeparatorChar;
 
// precreate dir
if(!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
 
#if !MONO
SQLiteConnection.ClearAllPools();
#endif
// make empty db
{
db = dir + "Data.gmdb";
 
if(!File.Exists(db))
{
Created = CreateEmptyDB(db);
}
else
{
Created = AlterDBAddTimeColumn(db);
}
 
CheckPreAllocation();
 
//var connBuilder = new SQLiteConnectionStringBuilder();
//connBuilder.DataSource = "c:\filePath.db";
//connBuilder.Version = 3;
//connBuilder.PageSize = 4096;
//connBuilder.JournalMode = SQLiteJournalModeEnum.Wal;
//connBuilder.Pooling = true;
//var x = connBuilder.ToString();
#if !MONO
ConnectionString = string.Format("Data Source=\"{0}\";Page Size=32768;Pooling=True", db); //;Journal Mode=Wal
#else
ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=True,Page Size=32768,Pooling=True", db);
#endif
}
 
// clear old attachments
AttachedCaches.Clear();
RebuildFinnalSelect();
 
// attach all databases from main cache location
#if !PocketPC
var dbs = Directory.GetFiles(dir, "*.gmdb", SearchOption.AllDirectories);
#else
var dbs = Directory.GetFiles(dir, "*.gmdb");
#endif
foreach(var d in dbs)
{
if(d != db)
{
Attach(d);
}
}
}
}
 
/// <summary>
/// pre-allocate 32MB free space 'ahead' if needed,
/// decreases fragmentation
/// </summary>
void CheckPreAllocation()
{
{
byte[] pageSizeBytes = new byte[2];
byte[] freePagesBytes = new byte[4];
 
lock(this)
{
using(var dbf = File.Open(db, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
dbf.Seek(16, SeekOrigin.Begin);
 
#if (!PocketPC && !MONO)
dbf.Lock(16, 2);
dbf.Read(pageSizeBytes, 0, 2);
dbf.Unlock(16, 2);
 
dbf.Seek(36, SeekOrigin.Begin);
 
dbf.Lock(36, 4);
dbf.Read(freePagesBytes, 0, 4);
dbf.Unlock(36, 4);
#else
dbf.Read(pageSizeBytes, 0, 2);
dbf.Seek(36, SeekOrigin.Begin);
dbf.Read(freePagesBytes, 0, 4);
#endif
 
dbf.Close();
}
}
 
if(BitConverter.IsLittleEndian)
{
Array.Reverse(pageSizeBytes);
Array.Reverse(freePagesBytes);
}
UInt16 pageSize = BitConverter.ToUInt16(pageSizeBytes, 0);
UInt32 freePages = BitConverter.ToUInt32(freePagesBytes, 0);
 
var freeMB = (pageSize * freePages) / (1024.0 * 1024.0);
 
#if !PocketPC
int addSizeMB = 32;
int waitUntilMB = 4;
#else
int addSizeMB = 4; // reduce due to test in emulator
int waitUntilMB = 2;
#endif
 
Debug.WriteLine("FreePageSpace in cache: " + freeMB + "MB | " + freePages + " pages");
 
if(freeMB <= waitUntilMB)
{
PreAllocateDB(db, addSizeMB);
}
}
}
 
#region -- import / export --
public static bool CreateEmptyDB(string file)
{
bool ret = true;
 
try
{
string dir = Path.GetDirectoryName(file);
if(!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
 
using(SQLiteConnection cn = new SQLiteConnection())
{
#if !MONO
cn.ConnectionString = string.Format("Data Source=\"{0}\";FailIfMissing=False;Page Size=32768", file);
#else
cn.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=False,Page Size=32768", file);
#endif
cn.Open();
{
using(DbTransaction tr = cn.BeginTransaction())
{
try
{
using(DbCommand cmd = cn.CreateCommand())
{
cmd.Transaction = tr;
#if !PocketPC
cmd.CommandText = Properties.Resources.CreateTileDb;
#else
cmd.CommandText = GMap.NET.WindowsMobile.Properties.Resources.CreateTileDb;
#endif
cmd.ExecuteNonQuery();
}
tr.Commit();
}
catch(Exception exx)
{
#if MONO
Console.WriteLine("CreateEmptyDB: " + exx.ToString());
#endif
Debug.WriteLine("CreateEmptyDB: " + exx.ToString());
 
tr.Rollback();
ret = false;
}
}
cn.Close();
}
}
}
catch(Exception ex)
{
#if MONO
Console.WriteLine("CreateEmptyDB: " + ex.ToString());
#endif
Debug.WriteLine("CreateEmptyDB: " + ex.ToString());
ret = false;
}
return ret;
}
 
public static bool PreAllocateDB(string file, int addSizeInMBytes)
{
bool ret = true;
 
try
{
Debug.WriteLine("PreAllocateDB: " + file + ", +" + addSizeInMBytes + "MB");
 
using(SQLiteConnection cn = new SQLiteConnection())
{
#if !MONO
cn.ConnectionString = string.Format("Data Source=\"{0}\";FailIfMissing=False;Page Size=32768", file);
#else
cn.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=False,Page Size=32768", file);
#endif
cn.Open();
{
using(DbTransaction tr = cn.BeginTransaction())
{
try
{
using(DbCommand cmd = cn.CreateCommand())
{
cmd.Transaction = tr;
cmd.CommandText = string.Format("create table large (a); insert into large values (zeroblob({0})); drop table large;", addSizeInMBytes * 1024 * 1024);
cmd.ExecuteNonQuery();
}
tr.Commit();
}
catch(Exception exx)
{
#if MONO
Console.WriteLine("PreAllocateDB: " + exx.ToString());
#endif
Debug.WriteLine("PreAllocateDB: " + exx.ToString());
 
tr.Rollback();
ret = false;
}
}
cn.Close();
}
}
}
catch(Exception ex)
{
#if MONO
Console.WriteLine("PreAllocateDB: " + ex.ToString());
#endif
Debug.WriteLine("PreAllocateDB: " + ex.ToString());
ret = false;
}
return ret;
}
 
private static bool AlterDBAddTimeColumn(string file)
{
bool ret = true;
 
try
{
if(File.Exists(file))
{
using(SQLiteConnection cn = new SQLiteConnection())
{
#if !MONO
cn.ConnectionString = string.Format("Data Source=\"{0}\";FailIfMissing=False;Page Size=32768;Pooling=True", file);
#else
cn.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=False,Page Size=32768,Pooling=True", file);
#endif
cn.Open();
{
using(DbTransaction tr = cn.BeginTransaction())
{
bool? NoCacheTimeColumn = null;
 
try
{
using(DbCommand cmd = new SQLiteCommand("SELECT CacheTime FROM Tiles", cn))
{
cmd.Transaction = tr;
 
using(DbDataReader rd = cmd.ExecuteReader())
{
rd.Close();
}
NoCacheTimeColumn = false;
}
}
catch(Exception ex)
{
if(ex.Message.Contains("no such column: CacheTime"))
{
NoCacheTimeColumn = true;
}
else
{
throw ex;
}
}
 
try
{
if(NoCacheTimeColumn.HasValue && NoCacheTimeColumn.Value)
{
using(DbCommand cmd = cn.CreateCommand())
{
cmd.Transaction = tr;
 
cmd.CommandText = "ALTER TABLE Tiles ADD CacheTime DATETIME";
 
cmd.ExecuteNonQuery();
}
tr.Commit();
NoCacheTimeColumn = false;
}
}
catch(Exception exx)
{
#if MONO
Console.WriteLine("AlterDBAddTimeColumn: " + exx.ToString());
#endif
Debug.WriteLine("AlterDBAddTimeColumn: " + exx.ToString());
 
tr.Rollback();
ret = false;
}
}
cn.Close();
}
}
}
else
{
ret = false;
}
}
catch(Exception ex)
{
#if MONO
Console.WriteLine("AlterDBAddTimeColumn: " + ex.ToString());
#endif
Debug.WriteLine("AlterDBAddTimeColumn: " + ex.ToString());
ret = false;
}
return ret;
}
 
public static bool VacuumDb(string file)
{
bool ret = true;
 
try
{
using(SQLiteConnection cn = new SQLiteConnection())
{
#if !MONO
cn.ConnectionString = string.Format("Data Source=\"{0}\";FailIfMissing=True;Page Size=32768", file);
#else
cn.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=True,Page Size=32768", file);
#endif
cn.Open();
{
using(DbCommand cmd = cn.CreateCommand())
{
cmd.CommandText = "vacuum;";
cmd.ExecuteNonQuery();
}
cn.Close();
}
}
}
catch(Exception ex)
{
Debug.WriteLine("VacuumDb: " + ex.ToString());
ret = false;
}
return ret;
}
 
public static bool ExportMapDataToDB(string sourceFile, string destFile)
{
bool ret = true;
 
try
{
if(!File.Exists(destFile))
{
ret = CreateEmptyDB(destFile);
}
 
if(ret)
{
using(SQLiteConnection cn1 = new SQLiteConnection())
{
#if !MONO
cn1.ConnectionString = string.Format("Data Source=\"{0}\";Page Size=32768", sourceFile);
#else
cn1.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=True,Page Size=32768", sourceFile);
#endif
 
cn1.Open();
if(cn1.State == System.Data.ConnectionState.Open)
{
using(SQLiteConnection cn2 = new SQLiteConnection())
{
#if !MONO
cn2.ConnectionString = string.Format("Data Source=\"{0}\";Page Size=32768", destFile);
#else
cn2.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=True,Page Size=32768", destFile);
#endif
cn2.Open();
if(cn2.State == System.Data.ConnectionState.Open)
{
using(SQLiteCommand cmd = new SQLiteCommand(string.Format("ATTACH DATABASE \"{0}\" AS Source", sourceFile), cn2))
{
cmd.ExecuteNonQuery();
}
 
using(SQLiteTransaction tr = cn2.BeginTransaction())
{
try
{
List<long> add = new List<long>();
using(SQLiteCommand cmd = new SQLiteCommand("SELECT id, X, Y, Zoom, Type FROM Tiles;", cn1))
{
using(SQLiteDataReader rd = cmd.ExecuteReader())
{
while(rd.Read())
{
long id = rd.GetInt64(0);
using(SQLiteCommand cmd2 = new SQLiteCommand(string.Format("SELECT id FROM Tiles WHERE X={0} AND Y={1} AND Zoom={2} AND Type={3};", rd.GetInt32(1), rd.GetInt32(2), rd.GetInt32(3), rd.GetInt32(4)), cn2))
{
using(SQLiteDataReader rd2 = cmd2.ExecuteReader())
{
if(!rd2.Read())
{
add.Add(id);
}
}
}
}
}
}
 
foreach(long id in add)
{
using(SQLiteCommand cmd = new SQLiteCommand(string.Format("INSERT INTO Tiles(X, Y, Zoom, Type, CacheTime) SELECT X, Y, Zoom, Type, CacheTime FROM Source.Tiles WHERE id={0}; INSERT INTO TilesData(id, Tile) Values((SELECT last_insert_rowid()), (SELECT Tile FROM Source.TilesData WHERE id={0}));", id), cn2))
{
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
}
}
add.Clear();
 
tr.Commit();
}
catch(Exception exx)
{
Debug.WriteLine("ExportMapDataToDB: " + exx.ToString());
tr.Rollback();
ret = false;
}
}
 
using(SQLiteCommand cmd = new SQLiteCommand("DETACH DATABASE Source;", cn2))
{
cmd.ExecuteNonQuery();
}
}
}
}
}
}
}
catch(Exception ex)
{
Debug.WriteLine("ExportMapDataToDB: " + ex.ToString());
ret = false;
}
return ret;
}
#endregion
 
static readonly string singleSqlSelect = "SELECT Tile FROM main.TilesData WHERE id = (SELECT id FROM main.Tiles WHERE X={0} AND Y={1} AND Zoom={2} AND Type={3})";
static readonly string singleSqlInsert = "INSERT INTO main.Tiles(X, Y, Zoom, Type, CacheTime) VALUES(@p1, @p2, @p3, @p4, @p5)";
static readonly string singleSqlInsertLast = "INSERT INTO main.TilesData(id, Tile) VALUES((SELECT last_insert_rowid()), @p1)";
 
string ConnectionString;
 
readonly List<string> AttachedCaches = new List<string>();
string finnalSqlSelect = singleSqlSelect;
string attachSqlQuery = string.Empty;
string detachSqlQuery = string.Empty;
 
void RebuildFinnalSelect()
{
finnalSqlSelect = null;
finnalSqlSelect = singleSqlSelect;
 
attachSqlQuery = null;
attachSqlQuery = string.Empty;
 
detachSqlQuery = null;
detachSqlQuery = string.Empty;
 
int i = 1;
foreach(var c in AttachedCaches)
{
finnalSqlSelect += string.Format("\nUNION SELECT Tile FROM db{0}.TilesData WHERE id = (SELECT id FROM db{0}.Tiles WHERE X={{0}} AND Y={{1}} AND Zoom={{2}} AND Type={{3}})", i);
attachSqlQuery += string.Format("\nATTACH '{0}' as db{1};", c, i);
detachSqlQuery += string.Format("\nDETACH DATABASE db{0};", i);
 
i++;
}
}
 
public void Attach(string db)
{
if(!AttachedCaches.Contains(db))
{
AttachedCaches.Add(db);
RebuildFinnalSelect();
}
}
 
public void Detach(string db)
{
if(AttachedCaches.Contains(db))
{
AttachedCaches.Remove(db);
RebuildFinnalSelect();
}
}
 
#region PureImageCache Members
 
int preAllocationPing = 0;
 
bool PureImageCache.PutImageToCache(byte[] tile, int type, GPoint pos, int zoom)
{
bool ret = true;
if(Created)
{
try
{
using(SQLiteConnection cn = new SQLiteConnection())
{
cn.ConnectionString = ConnectionString;
cn.Open();
{
using(DbTransaction tr = cn.BeginTransaction())
{
try
{
using(DbCommand cmd = cn.CreateCommand())
{
cmd.Transaction = tr;
cmd.CommandText = singleSqlInsert;
 
cmd.Parameters.Add(new SQLiteParameter("@p1", pos.X));
cmd.Parameters.Add(new SQLiteParameter("@p2", pos.Y));
cmd.Parameters.Add(new SQLiteParameter("@p3", zoom));
cmd.Parameters.Add(new SQLiteParameter("@p4", type));
cmd.Parameters.Add(new SQLiteParameter("@p5", DateTime.Now));
 
cmd.ExecuteNonQuery();
}
 
using(DbCommand cmd = cn.CreateCommand())
{
cmd.Transaction = tr;
 
cmd.CommandText = singleSqlInsertLast;
cmd.Parameters.Add(new SQLiteParameter("@p1", tile));
 
cmd.ExecuteNonQuery();
}
tr.Commit();
}
catch(Exception ex)
{
#if MONO
Console.WriteLine("PutImageToCache: " + ex.ToString());
#endif
Debug.WriteLine("PutImageToCache: " + ex.ToString());
 
tr.Rollback();
ret = false;
}
}
}
cn.Close();
}
 
if(Interlocked.Increment(ref preAllocationPing) % 22 == 0)
{
CheckPreAllocation();
}
}
catch(Exception ex)
{
#if MONO
Console.WriteLine("PutImageToCache: " + ex.ToString());
#endif
Debug.WriteLine("PutImageToCache: " + ex.ToString());
ret = false;
}
}
return ret;
}
 
PureImage PureImageCache.GetImageFromCache(int type, GPoint pos, int zoom)
{
PureImage ret = null;
try
{
using(SQLiteConnection cn = new SQLiteConnection())
{
cn.ConnectionString = ConnectionString;
cn.Open();
{
if(!string.IsNullOrEmpty(attachSqlQuery))
{
using(DbCommand com = cn.CreateCommand())
{
com.CommandText = attachSqlQuery;
int x = com.ExecuteNonQuery();
//Debug.WriteLine("Attach: " + x);
}
}
 
using(DbCommand com = cn.CreateCommand())
{
com.CommandText = string.Format(finnalSqlSelect, pos.X, pos.Y, zoom, type);
 
using(DbDataReader rd = com.ExecuteReader(System.Data.CommandBehavior.SequentialAccess))
{
if(rd.Read())
{
long length = rd.GetBytes(0, 0, null, 0, 0);
byte[] tile = new byte[length];
rd.GetBytes(0, 0, tile, 0, tile.Length);
{
if(GMapProvider.TileImageProxy != null)
{
ret = GMapProvider.TileImageProxy.FromArray(tile);
}
}
tile = null;
}
rd.Close();
}
}
 
if(!string.IsNullOrEmpty(detachSqlQuery))
{
using(DbCommand com = cn.CreateCommand())
{
com.CommandText = detachSqlQuery;
int x = com.ExecuteNonQuery();
//Debug.WriteLine("Detach: " + x);
}
}
}
cn.Close();
}
}
catch(Exception ex)
{
#if MONO
Console.WriteLine("GetImageFromCache: " + ex.ToString());
#endif
Debug.WriteLine("GetImageFromCache: " + ex.ToString());
ret = null;
}
 
return ret;
}
 
int PureImageCache.DeleteOlderThan(DateTime date, int? type)
{
int affectedRows = 0;
 
try
{
using(SQLiteConnection cn = new SQLiteConnection())
{
cn.ConnectionString = ConnectionString;
cn.Open();
{
using(DbCommand com = cn.CreateCommand())
{
com.CommandText = string.Format("DELETE FROM Tiles WHERE CacheTime is not NULL and CacheTime < datetime('{0}')", date.ToString("s"));
if(type.HasValue)
{
com.CommandText += " and Type = " + type;
}
affectedRows = com.ExecuteNonQuery();
}
}
}
}
catch(Exception ex)
{
#if MONO
Console.WriteLine("DeleteOlderThan: " + ex);
#endif
Debug.WriteLine("DeleteOlderThan: " + ex);
}
 
return affectedRows;
}
 
#endregion
}
#endif
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Core.csproj
0,0 → 1,396
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{D0C39D9D-BED0-418B-9A5E-713176CAF40C}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>GMap.NET</RootNamespace>
<AssemblyName>GMap.NET.Core</AssemblyName>
<FileAlignment>512</FileAlignment>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>sn.snk</AssemblyOriginatorKeyFile>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation />
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkSubset>
</TargetFrameworkSubset>
<NoWin32Manifest>False</NoWin32Manifest>
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
<NoStdLib>False</NoStdLib>
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
<IntermediateOutputPath>obj\$(Configuration)\</IntermediateOutputPath>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;MONO_disabled; MySQL_disabled; PostgreSQL_disabled; SQLite</DefineConstants>
<DebugType>Full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisLogFile>bin\x86\Debug\GMap.NET.Core.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;MONO_disabled; MySQL_disabled; PostgreSQL_disabled; SQLite</DefineConstants>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisLogFile>bin\x86\Release\GMap.NET.Core.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<Optimize>true</Optimize>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<BaseIntermediateOutputPath>obj\</BaseIntermediateOutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<BaseAddress>4194304</BaseAddress>
<RegisterForComInterop>False</RegisterForComInterop>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'v4.0-Debug|AnyCPU'">
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\v4.0-Debug\</OutputPath>
<DefineConstants>NET40;TRACE;DEBUG;SQLite;MONO_disabled;MySQL_disabled;PostgreSQL_disabled</DefineConstants>
<DebugType>Full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'v4.0-Release|AnyCPU'">
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<OutputPath>bin\v4.0-Release\</OutputPath>
<DefineConstants>NET40;TRACE;SQLite;MONO_disabled;MySQL_disabled;PostgreSQL_disabled</DefineConstants>
<Optimize>true</Optimize>
<PlatformTarget>AnyCPU</PlatformTarget>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFrameworkVersion)' == 'v2.0' ">
<TargetFrameworkVersionNumber>2.0</TargetFrameworkVersionNumber>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFrameworkVersion)' == 'v3.0' ">
<TargetFrameworkVersionNumber>3.0</TargetFrameworkVersionNumber>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFrameworkVersion)' == 'v3.5' ">
<TargetFrameworkVersionNumber>3.5</TargetFrameworkVersionNumber>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFrameworkVersion)' == 'v4.0' ">
<TargetFrameworkVersionNumber>4.0</TargetFrameworkVersionNumber>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFrameworkVersion)' == 'v4.5' ">
<TargetFrameworkVersionNumber>4.5</TargetFrameworkVersionNumber>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFrameworkVersion)' == 'v4.6' ">
<TargetFrameworkVersionNumber>4.6</TargetFrameworkVersionNumber>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFrameworkVersion)' == 'v5.0' ">
<TargetFrameworkVersionNumber>5.0</TargetFrameworkVersionNumber>
</PropertyGroup>
<Choose>
<When Condition=" '$(TargetFrameworkVersionNumber)' &gt;= '4.0' ">
<ItemGroup>
<Reference Include="Mono.Data.Sqlite">
<HintPath>..\References\Windows\NET4\Mono.Data.Sqlite.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System.Data.SQLite">
<HintPath>..\References\Windows\NET4\System.Data.SQLite.DLL</HintPath>
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
</Reference>
<Reference Include="Npgsql">
<HintPath>..\References\Windows\NET4\Npgsql.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Mono.Security">
<HintPath>..\References\Windows\NET4\Mono.Security.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="MySql.Data">
<HintPath>..\References\Windows\NET4\MySql.Data.dll</HintPath>
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
</Reference>
</ItemGroup>
</When>
<Otherwise>
<ItemGroup>
<Reference Include="Mono.Data.Sqlite">
<HintPath>..\References\Windows\Mono.Data.Sqlite.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System.Data.SQLite">
<HintPath>..\References\Windows\System.Data.SQLite.DLL</HintPath>
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
</Reference>
<Reference Include="Npgsql">
<HintPath>..\References\Windows\Npgsql.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Mono.Security">
<HintPath>..\References\Windows\Mono.Security.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="MySql.Data">
<HintPath>..\References\Windows\MySql.Data.dll</HintPath>
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
</Reference>
</ItemGroup>
</Otherwise>
</Choose>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data">
<Private>False</Private>
</Reference>
<Reference Include="System.Data.SqlServerCe">
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
</Reference>
<Reference Include="System.EnterpriseServices" />
<Reference Include="System.Web.Services" />
<Reference Include="System.XML" />
</ItemGroup>
<ItemGroup>
<Compile Include="GMap.NET.CacheProviders\MemoryCache.cs" />
<Compile Include="GMap.NET.Internals\SocksProxySocket\SocksHttpWebRequest.cs" />
<Compile Include="GMap.NET.Internals\DrawTile.cs" />
<Compile Include="GMap.NET.Internals\FastResourceLock.cs" />
<Compile Include="GMap.NET.Internals\SocksProxySocket\AuthMethod.cs" />
<Compile Include="GMap.NET.Internals\SocksProxySocket\AuthNone.cs" />
<Compile Include="GMap.NET.Internals\SocksProxySocket\AuthUserPass.cs" />
<Compile Include="GMap.NET.Internals\SocksProxySocket\IAsyncProxyResult.cs" />
<Compile Include="GMap.NET.Internals\SocksProxySocket\ProxyException.cs" />
<Compile Include="GMap.NET.Internals\SocksProxySocket\ProxySocket.cs" />
<Compile Include="GMap.NET.Internals\SocksProxySocket\Socks4Handler.cs" />
<Compile Include="GMap.NET.Internals\SocksProxySocket\Socks5Handler.cs" />
<Compile Include="GMap.NET.Internals\SocksProxySocket\SocksHandler.cs" />
<Compile Include="GMap.NET.Internals\TileHttpHost.cs" />
<Compile Include="GMap.NET.MapProviders\ArcGIS\ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_MapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Bing\BingMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Bing\BingSatelliteMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Bing\BingHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\ArcGIS\ArcGIS_StreetMap_World_2D_MapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\ArcGIS\ArcGIS_Imagery_World_2D_MapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\ArcGIS\ArcGIS_ShadedRelief_World_2D_MapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\ArcGIS\ArcGIS_Topo_US_2D_MapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\ArcGIS\ArcGIS_World_Physical_MapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\ArcGIS\ArcGIS_World_Shaded_Relief_MapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\ArcGIS\ArcGIS_World_Street_MapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\ArcGIS\ArcGIS_World_Terrain_Base_MapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\ArcGIS\ArcGIS_World_Topo_MapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Czech\CzechGeographicMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Czech\CzechHistoryMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Czech\CzechHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Czech\CzechMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Czech\CzechSatelliteMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Czech\CzechTuristMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Czech\CzechTuristWinterMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Etc\CloudMadeMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Etc\SwedenMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Etc\WikiMapiaMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\CzechOld\CzechHistoryMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\CzechOld\CzechHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\CzechOld\CzechSatelliteMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\CzechOld\CzechTuristMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\CzechOld\CzechMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Etc\TurkeyMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Etc\MapBenderWMSProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Etc\SpainMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Etc\LatviaMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Lithuania\LithuaniaReliefMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Lithuania\LithuaniaHybridOldMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Lithuania\LithuaniaHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Lithuania\LithuaniaOrtoFotoOldMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Lithuania\LithuaniaOrtoFotoMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Lithuania\Lithuania3dMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Lithuania\LithuaniaMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Lithuania\LithuaniaTOP50.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenStreet4UMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenStreetMapQuestSatteliteProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenStreetMapQuestHybridProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenStreetMapQuestProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenCycleTransportMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenCycleLandscapeMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Yandex\YandexHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Yandex\YandexSatelliteMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Yandex\YandexMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Ovi\OviHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Ovi\OviTerrainMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Ovi\OviSatelliteMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Ovi\OviMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\NearMap\NearHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\NearMap\NearSatelliteMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\NearMap\NearMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\Korea\GoogleKoreaHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\Korea\GoogleKoreaSatelliteMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\Korea\GoogleKoreaMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\China\GoogleChinaTerrainMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\China\GoogleChinaHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\China\GoogleChinaSatelliteMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\China\GoogleChinaMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\GoogleTerrainMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\GoogleHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\GoogleSatelliteMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Google\GoogleMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Yahoo\YahooHybridMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Yahoo\YahooSatelliteMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\Yahoo\YahooMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenSeaMapHybridProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenCycleMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenStreetMapSurferTerrainProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenStreetMapSurferProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenStreetOsmProvider.cs" />
<Compile Include="GMap.NET.MapProviders\OpenStreetMap\OpenStreetMapProvider.cs" />
<Compile Include="GMap.NET.MapProviders\GMapProvider.cs" />
<Compile Include="GMap.NET.Projections\SWEREF99_TMProjection.cs" />
<Compile Include="GMap.NET.Projections\MapsLTReliefProjection.cs" />
<Compile Include="GMap.NET.Projections\PlateCarreeProjectionDarbAe.cs" />
<Compile Include="GMap.NET\GDirections.cs" />
<Compile Include="GMap.NET\DirectionsProvider.cs" />
<Compile Include="GMap.NET\GeocodingProvider.cs" />
<Compile Include="GMap.NET\RoutingProvider.cs" />
<Compile Include="GMap.NET\ZipStorer.cs" />
<Compile Include="Properties\VersionInfo.cs" />
<Compile Include="GMap.NET.CacheProviders\MsSQLCePureImageCache.cs" />
<Compile Include="GMap.NET.CacheProviders\PostgreSQLPureImageCache.cs" />
<Compile Include="GMap.NET.CacheProviders\SQLitePureImageCache.cs" />
<Compile Include="GMap.NET.Internals\CacheQueueItem.cs" />
<Compile Include="GMap.NET.Internals\FastReaderWriterLock.cs" />
<Compile Include="GMap.NET.Internals\KiberTileCache.cs" />
<Compile Include="GMap.NET.Internals\PureImage.cs" />
<Compile Include="GMap.NET.Internals\LoadTask.cs" />
<Compile Include="GMap.NET.Internals\RawTile.cs" />
<Compile Include="GMap.NET.Projections\MapsLVProjection.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="GMap.NET.Projections\MapyCZProjection.cs" />
<Compile Include="GMap.NET.Projections\MercatorProjectionYandex.cs" />
<Compile Include="GMap.NET.Projections\PlateCarreeProjectionPergo.cs" />
<Compile Include="GMap.NET.Projections\MapsLTProjection.cs" />
<Compile Include="GMap.NET.Projections\MercatorProjection.cs" />
<Compile Include="GMap.NET.Projections\PlateCarreeProjection.cs" />
<Compile Include="GMap.NET\Extensions.cs" />
<Compile Include="GMap.NET\StatusCodes.cs" />
<Compile Include="GMap.NET.CacheProviders\MySQLPureImageCache.cs" />
<Compile Include="GMap.NET\GpsLog.cs" />
<Compile Include="GMap.NET\gpx.cs" />
<Compile Include="GMap.NET\LanguageType.cs" />
<Compile Include="GMap.NET\PureProjection.cs" />
<Compile Include="GMap.NET\Interface.cs" />
<Compile Include="GMap.NET\AccessMode.cs" />
<Compile Include="GMap.NET\Delegates.cs" />
<Compile Include="GMap.NET\MapRoute.cs" />
<None Include="GMap.NET\MapType.cs" />
<Compile Include="GMap.NET.CacheProviders\MsSQLPureImageCache.cs" />
<Compile Include="GMap.NET\GPoint.cs" />
<Compile Include="GMap.NET\PureImageCache.cs" />
<Compile Include="GMap.NET\GRect.cs" />
<Compile Include="GMap.NET\Singleton.cs" />
<Compile Include="GMap.NET\MouseWheelZoomType.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<DependentUpon>Resources.resx</DependentUpon>
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
</Compile>
<Compile Include="GMap.NET.Internals\Cache.cs" />
<Compile Include="GMap.NET.Internals\Core.cs" />
<Compile Include="GMap.NET.Internals\Tile.cs" />
<Compile Include="GMap.NET.Internals\TileMatrix.cs" />
<Compile Include="GMap.NET\GMaps.cs" />
<Compile Include="GMap.NET\Placemark.cs" />
<Compile Include="GMap.NET\PointLatLng.cs" />
<Compile Include="GMap.NET\RectLatLng.cs" />
<Compile Include="GMap.NET\RenderMode.cs" />
<Compile Include="GMap.NET\GSize.cs" />
<Compile Include="GMap.NET\SizeLatLng.cs" />
<Compile Include="GMap.NET.Internals\Stuff.cs" />
<Service Include="{94E38DFF-614B-4cbd-B67C-F211BB35CE8B}" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="Resources\System.Data.SQLite.x64.NET2.dll.gz" />
<None Include="Resources\System.Data.SQLite.x64.NET4.dll.gz" />
<None Include="Resources\System.Data.SQLite.x86.NET2.dll.gz" />
<None Include="Resources\System.Data.SQLite.x86.NET4.dll.gz" />
<None Include="sn.snk" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<WebReferences Include="Web References\" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/Cache.cs
0,0 → 1,305

namespace GMap.NET.Internals
{
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using GMap.NET.CacheProviders;
using System.Security.Cryptography;
 
internal class CacheLocator
{
private static string location;
public static string Location
{
get
{
if(string.IsNullOrEmpty(location))
{
Reset();
}
 
return location;
}
set
{
if(string.IsNullOrEmpty(value)) // setting to null resets to default
{
Reset();
}
else
{
location = value;
}
 
if(Delay)
{
Cache.Instance.CacheLocation = location;
}
}
}
 
static void Reset()
{
string appDataLocation = GetApplicationDataFolderPath();
 
#if !PocketPC
// http://greatmaps.codeplex.com/discussions/403151
// by default Network Service don't have disk write access
if(string.IsNullOrEmpty(appDataLocation))
{
GMaps.Instance.Mode = AccessMode.ServerOnly;
GMaps.Instance.UseDirectionsCache = false;
GMaps.Instance.UseGeocoderCache = false;
GMaps.Instance.UsePlacemarkCache = false;
GMaps.Instance.UseRouteCache = false;
GMaps.Instance.UseUrlCache = false;
}
else
#endif
{
Location = appDataLocation;
}
}
 
public static string GetApplicationDataFolderPath()
{
#if !PocketPC
bool isSystem = false;
try
{
using(var identity = System.Security.Principal.WindowsIdentity.GetCurrent())
{
if(identity != null)
{
isSystem = identity.IsSystem;
}
}
}
catch(Exception ex)
{
Trace.WriteLine("SQLitePureImageCache, WindowsIdentity.GetCurrent: " + ex);
}
 
string path = string.Empty;
 
// https://greatmaps.codeplex.com/workitem/16112
if(isSystem)
{
path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData);
}
else
{
path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
}
#else
path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
#endif
 
if(!string.IsNullOrEmpty(path))
{
path += Path.DirectorySeparatorChar + "GMap.NET" + Path.DirectorySeparatorChar;
}
 
return path;
}
 
public static bool Delay = false;
}
 
/// <summary>
/// cache system for tiles, geocoding, etc...
/// </summary>
internal class Cache : Singleton<Cache>
{
/// <summary>
/// abstract image cache
/// </summary>
public PureImageCache ImageCache;
 
/// <summary>
/// second level abstract image cache
/// </summary>
public PureImageCache ImageCacheSecond;
 
string cache;
 
/// <summary>
/// local cache location
/// </summary>
public string CacheLocation
{
get
{
return cache;
}
set
{
cache = value;
#if SQLite
if(ImageCache is SQLitePureImageCache)
{
(ImageCache as SQLitePureImageCache).CacheLocation = value;
}
#else
if(ImageCache is MsSQLCePureImageCache)
{
(ImageCache as MsSQLCePureImageCache).CacheLocation = value;
}
#endif
CacheLocator.Delay = true;
}
}
 
public Cache()
{
#region singleton check
if(Instance != null)
{
throw (new System.Exception("You have tried to create a new singleton class where you should have instanced it. Replace your \"new class()\" with \"class.Instance\""));
}
#endregion
 
#if SQLite
ImageCache = new SQLitePureImageCache();
#else
// you can use $ms stuff if you like too ;}
ImageCache = new MsSQLCePureImageCache();
#endif
 
#if PocketPC
// use sd card if exist for cache
string sd = Native.GetRemovableStorageDirectory();
if(!string.IsNullOrEmpty(sd))
{
CacheLocation = sd + Path.DirectorySeparatorChar + "GMap.NET" + Path.DirectorySeparatorChar;
}
else
#endif
{
#if PocketPC
CacheLocation = CacheLocator.Location;
#else
string newCache = CacheLocator.Location;
 
string oldCache = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar + "GMap.NET" + Path.DirectorySeparatorChar;
 
// move database to non-roaming user directory
if(Directory.Exists(oldCache))
{
try
{
if(Directory.Exists(newCache))
{
Directory.Delete(oldCache, true);
}
else
{
Directory.Move(oldCache, newCache);
}
CacheLocation = newCache;
}
catch(Exception ex)
{
CacheLocation = oldCache;
Trace.WriteLine("SQLitePureImageCache, moving data: " + ex.ToString());
}
}
else
{
CacheLocation = newCache;
}
#endif
}
}
 
#region -- etc cache --
 
static readonly SHA1CryptoServiceProvider HashProvider = new SHA1CryptoServiceProvider();
 
void ConvertToHash(ref string s)
{
s = BitConverter.ToString(HashProvider.ComputeHash(Encoding.Unicode.GetBytes(s)));
}
 
public void SaveContent(string url, CacheType type, string content)
{
try
{
ConvertToHash(ref url);
 
string dir = Path.Combine(cache, type.ToString()) + Path.DirectorySeparatorChar;
 
// precrete dir
if(!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
 
string file = dir + url + ".txt";
 
using(StreamWriter writer = new StreamWriter(file, false, Encoding.UTF8))
{
writer.Write(content);
}
}
catch(Exception ex)
{
Debug.WriteLine("SaveContent: " + ex);
}
}
 
public string GetContent(string url, CacheType type, TimeSpan stayInCache)
{
string ret = null;
 
try
{
ConvertToHash(ref url);
 
string dir = Path.Combine(cache, type.ToString()) + Path.DirectorySeparatorChar;
string file = dir + url + ".txt";
 
if(File.Exists(file))
{
var writeTime = File.GetLastWriteTime(file);
if (DateTime.Now - writeTime < stayInCache)
{
using (StreamReader r = new StreamReader(file, Encoding.UTF8))
{
ret = r.ReadToEnd();
}
}
else
{
File.Delete(file);
}
}
}
catch(Exception ex)
{
ret = null;
Debug.WriteLine("GetContent: " + ex);
}
 
return ret;
}
 
public string GetContent(string url, CacheType type)
{
return GetContent(url, type, TimeSpan.FromDays(88));
}
 
#endregion
}
 
internal enum CacheType
{
GeocoderCache,
PlacemarkCache,
RouteCache,
UrlCache,
DirectionsCache,
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/CacheQueueItem.cs
0,0 → 1,40

namespace GMap.NET.Internals
{
using System.IO;
using System;
 
/// <summary>
/// cache queue item
/// </summary>
internal struct CacheQueueItem
{
public RawTile Tile;
public byte[] Img;
public CacheUsage CacheType;
 
public CacheQueueItem(RawTile tile, byte[] Img, CacheUsage cacheType)
{
this.Tile = tile;
this.Img = Img;
this.CacheType = cacheType;
}
 
public override string ToString()
{
return Tile + ", CacheType:" + CacheType;
}
 
public void Clear()
{
Img = null;
}
}
 
internal enum CacheUsage
{
First = 2,
Second = 4,
Both = First | Second
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/Core.cs
0,0 → 1,1400

namespace GMap.NET.Internals
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using GMap.NET.Projections;
using System.IO;
using GMap.NET.MapProviders;
using System.ComponentModel;
 
#if NET40
using System.Collections.Concurrent;
using System.Threading.Tasks;
#endif
 
#if PocketPC
using OpenNETCF.ComponentModel;
using OpenNETCF.Threading;
using Thread=OpenNETCF.Threading.Thread2;
#endif
 
/// <summary>
/// internal map control core
/// </summary>
internal class Core : IDisposable
{
public PointLatLng position;
public GPoint positionPixel;
 
public GPoint renderOffset;
public GPoint centerTileXYLocation;
public GPoint centerTileXYLocationLast;
public GPoint dragPoint;
public GPoint compensationOffset;
 
public GPoint mouseDown;
public GPoint mouseCurrent;
public GPoint mouseLastZoom;
 
public MouseWheelZoomType MouseWheelZoomType = MouseWheelZoomType.MousePositionAndCenter;
public bool MouseWheelZoomEnabled = true;
 
public PointLatLng? LastLocationInBounds = null;
public bool VirtualSizeEnabled = false;
 
public GSize sizeOfMapArea;
public GSize minOfTiles;
public GSize maxOfTiles;
 
public GRect tileRect;
public GRect tileRectBearing;
//public GRect currentRegion;
public float bearing = 0;
public bool IsRotated = false;
 
public bool fillEmptyTiles = true;
 
public TileMatrix Matrix = new TileMatrix();
 
public List<DrawTile> tileDrawingList = new List<DrawTile>();
public FastReaderWriterLock tileDrawingListLock = new FastReaderWriterLock();
 
#if !NET40
public readonly Stack<LoadTask> tileLoadQueue = new Stack<LoadTask>();
#endif
 
#if !PocketPC
static readonly int GThreadPoolSize = 4;
#else
static readonly int GThreadPoolSize = 2;
#endif
 
DateTime LastTileLoadStart = DateTime.Now;
DateTime LastTileLoadEnd = DateTime.Now;
internal volatile bool IsStarted = false;
int zoom;
 
internal double scaleX = 1;
internal double scaleY = 1;
 
internal int maxZoom = 2;
internal int minZoom = 2;
internal int Width;
internal int Height;
 
internal int pxRes100m; // 100 meters
internal int pxRes1000m; // 1km
internal int pxRes10km; // 10km
internal int pxRes100km; // 100km
internal int pxRes1000km; // 1000km
internal int pxRes5000km; // 5000km
 
/// <summary>
/// is user dragging map
/// </summary>
public bool IsDragging = false;
 
public Core()
{
Provider = EmptyProvider.Instance;
}
 
/// <summary>
/// map zoom
/// </summary>
public int Zoom
{
get
{
return zoom;
}
set
{
if (zoom != value && !IsDragging)
{
zoom = value;
 
minOfTiles = Provider.Projection.GetTileMatrixMinXY(value);
maxOfTiles = Provider.Projection.GetTileMatrixMaxXY(value);
 
positionPixel = Provider.Projection.FromLatLngToPixel(Position, value);
 
if (IsStarted)
{
CancelAsyncTasks();
 
Matrix.ClearLevelsBelove(zoom - LevelsKeepInMemmory);
Matrix.ClearLevelsAbove(zoom + LevelsKeepInMemmory);
 
lock (FailedLoads)
{
FailedLoads.Clear();
RaiseEmptyTileError = true;
}
 
GoToCurrentPositionOnZoom();
UpdateBounds();
 
if (OnMapZoomChanged != null)
{
OnMapZoomChanged();
}
}
}
}
}
 
/// <summary>
/// current marker position in pixel coordinates
/// </summary>
public GPoint PositionPixel
{
get
{
return positionPixel;
}
}
 
/// <summary>
/// current marker position
/// </summary>
public PointLatLng Position
{
get
{
 
return position;
}
set
{
position = value;
positionPixel = Provider.Projection.FromLatLngToPixel(value, Zoom);
 
if (IsStarted)
{
if (!IsDragging)
{
GoToCurrentPosition();
}
 
if (OnCurrentPositionChanged != null)
OnCurrentPositionChanged(position);
}
}
}
 
public GMapProvider provider;
public GMapProvider Provider
{
get
{
return provider;
}
set
{
if (provider == null || !provider.Equals(value))
{
bool diffProjection = (provider == null || provider.Projection != value.Projection);
 
provider = value;
 
if (!provider.IsInitialized)
{
provider.IsInitialized = true;
provider.OnInitialized();
}
 
if (provider.Projection != null && diffProjection)
{
tileRect = new GRect(GPoint.Empty, Provider.Projection.TileSize);
tileRectBearing = tileRect;
if (IsRotated)
{
tileRectBearing.Inflate(1, 1);
}
 
minOfTiles = Provider.Projection.GetTileMatrixMinXY(Zoom);
maxOfTiles = Provider.Projection.GetTileMatrixMaxXY(Zoom);
positionPixel = Provider.Projection.FromLatLngToPixel(Position, Zoom);
}
 
if (IsStarted)
{
CancelAsyncTasks();
if (diffProjection)
{
OnMapSizeChanged(Width, Height);
}
ReloadMap();
 
if (minZoom < provider.MinZoom)
{
minZoom = provider.MinZoom;
}
 
//if(provider.MaxZoom.HasValue && maxZoom > provider.MaxZoom)
//{
// maxZoom = provider.MaxZoom.Value;
//}
 
zoomToArea = true;
 
if (provider.Area.HasValue && !provider.Area.Value.Contains(Position))
{
SetZoomToFitRect(provider.Area.Value);
zoomToArea = false;
}
 
if (OnMapTypeChanged != null)
{
OnMapTypeChanged(value);
}
}
}
}
}
 
internal bool zoomToArea = true;
 
/// <summary>
/// sets zoom to max to fit rect
/// </summary>
/// <param name="rect"></param>
/// <returns></returns>
public bool SetZoomToFitRect(RectLatLng rect)
{
int mmaxZoom = GetMaxZoomToFitRect(rect);
if (mmaxZoom > 0)
{
PointLatLng center = new PointLatLng(rect.Lat - (rect.HeightLat / 2), rect.Lng + (rect.WidthLng / 2));
Position = center;
 
if (mmaxZoom > maxZoom)
{
mmaxZoom = maxZoom;
}
 
if (Zoom != mmaxZoom)
{
Zoom = (int)mmaxZoom;
}
 
return true;
}
return false;
}
 
/// <summary>
/// is polygons enabled
/// </summary>
public bool PolygonsEnabled = true;
 
/// <summary>
/// is routes enabled
/// </summary>
public bool RoutesEnabled = true;
 
/// <summary>
/// is markers enabled
/// </summary>
public bool MarkersEnabled = true;
 
/// <summary>
/// can user drag map
/// </summary>
public bool CanDragMap = true;
 
/// <summary>
/// retry count to get tile
/// </summary>
#if !PocketPC
public int RetryLoadTile = 0;
#else
public int RetryLoadTile = 1;
#endif
 
/// <summary>
/// how many levels of tiles are staying decompresed in memory
/// </summary>
#if !PocketPC
public int LevelsKeepInMemmory = 5;
#else
public int LevelsKeepInMemmory = 1;
#endif
 
/// <summary>
/// map render mode
/// </summary>
public RenderMode RenderMode = RenderMode.GDI_PLUS;
 
/// <summary>
/// occurs when current position is changed
/// </summary>
public event PositionChanged OnCurrentPositionChanged;
 
/// <summary>
/// occurs when tile set load is complete
/// </summary>
public event TileLoadComplete OnTileLoadComplete;
 
/// <summary>
/// occurs when tile set is starting to load
/// </summary>
public event TileLoadStart OnTileLoadStart;
 
/// <summary>
/// occurs on empty tile displayed
/// </summary>
public event EmptyTileError OnEmptyTileError;
 
/// <summary>
/// occurs on map drag
/// </summary>
public event MapDrag OnMapDrag;
 
/// <summary>
/// occurs on map zoom changed
/// </summary>
public event MapZoomChanged OnMapZoomChanged;
 
/// <summary>
/// occurs on map type changed
/// </summary>
public event MapTypeChanged OnMapTypeChanged;
 
readonly List<Thread> GThreadPool = new List<Thread>();
// ^
// should be only one pool for multiply controls, any ideas how to fix?
//static readonly List<Thread> GThreadPool = new List<Thread>();
 
// windows forms or wpf
internal string SystemType;
 
internal static int instances = 0;
 
BackgroundWorker invalidator;
 
public BackgroundWorker OnMapOpen()
{
if (!IsStarted)
{
int x = Interlocked.Increment(ref instances);
Debug.WriteLine("OnMapOpen: " + x);
 
IsStarted = true;
 
if (x == 1)
{
GMaps.Instance.noMapInstances = false;
}
 
GoToCurrentPosition();
 
invalidator = new BackgroundWorker();
invalidator.WorkerSupportsCancellation = true;
invalidator.WorkerReportsProgress = true;
invalidator.DoWork += new DoWorkEventHandler(invalidatorWatch);
invalidator.RunWorkerAsync();
 
//if(x == 1)
//{
// first control shown
//}
}
return invalidator;
}
 
public void OnMapClose()
{
Dispose();
}
 
internal readonly object invalidationLock = new object();
internal DateTime lastInvalidation = DateTime.Now;
 
void invalidatorWatch(object sender, DoWorkEventArgs e)
{
var w = sender as BackgroundWorker;
 
TimeSpan span = TimeSpan.FromMilliseconds(111);
int spanMs = (int)span.TotalMilliseconds;
bool skiped = false;
TimeSpan delta;
DateTime now = DateTime.Now;
 
while (Refresh != null && (!skiped && Refresh.WaitOne() || (Refresh.WaitOne(spanMs, false) || true)))
{
if (w.CancellationPending)
break;
 
now = DateTime.Now;
lock (invalidationLock)
{
delta = now - lastInvalidation;
}
 
if (delta > span)
{
lock (invalidationLock)
{
lastInvalidation = now;
}
skiped = false;
 
w.ReportProgress(1);
Debug.WriteLine("Invalidate delta: " + (int)delta.TotalMilliseconds + "ms");
}
else
{
skiped = true;
}
}
}
 
public void UpdateCenterTileXYLocation()
{
PointLatLng center = FromLocalToLatLng(Width / 2, Height / 2);
GPoint centerPixel = Provider.Projection.FromLatLngToPixel(center, Zoom);
centerTileXYLocation = Provider.Projection.FromPixelToTileXY(centerPixel);
}
 
public int vWidth = 800;
public int vHeight = 400;
 
public void OnMapSizeChanged(int width, int height)
{
this.Width = width;
this.Height = height;
 
if (IsRotated)
{
#if !PocketPC
int diag = (int)Math.Round(Math.Sqrt(Width * Width + Height * Height) / Provider.Projection.TileSize.Width, MidpointRounding.AwayFromZero);
#else
int diag = (int) Math.Round(Math.Sqrt(Width * Width + Height * Height) / Provider.Projection.TileSize.Width);
#endif
sizeOfMapArea.Width = 1 + (diag / 2);
sizeOfMapArea.Height = 1 + (diag / 2);
}
else
{
sizeOfMapArea.Width = 1 + (Width / Provider.Projection.TileSize.Width) / 2;
sizeOfMapArea.Height = 1 + (Height / Provider.Projection.TileSize.Height) / 2;
}
 
Debug.WriteLine("OnMapSizeChanged, w: " + width + ", h: " + height + ", size: " + sizeOfMapArea);
 
if (IsStarted)
{
UpdateBounds();
GoToCurrentPosition();
}
}
 
/// <summary>
/// gets current map view top/left coordinate, width in Lng, height in Lat
/// </summary>
/// <returns></returns>
public RectLatLng ViewArea
{
get
{
if (Provider.Projection != null)
{
var p = FromLocalToLatLng(0, 0);
var p2 = FromLocalToLatLng(Width, Height);
 
return RectLatLng.FromLTRB(p.Lng, p.Lat, p2.Lng, p2.Lat);
}
return RectLatLng.Empty;
}
}
 
/// <summary>
/// gets lat/lng from local control coordinates
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public PointLatLng FromLocalToLatLng(long x, long y)
{
GPoint p = new GPoint(x, y);
p.OffsetNegative(renderOffset);
p.Offset(compensationOffset);
 
return Provider.Projection.FromPixelToLatLng(p, Zoom);
}
 
/// <summary>
/// return local coordinates from lat/lng
/// </summary>
/// <param name="latlng"></param>
/// <returns></returns>
public GPoint FromLatLngToLocal(PointLatLng latlng)
{
GPoint pLocal = Provider.Projection.FromLatLngToPixel(latlng, Zoom);
pLocal.Offset(renderOffset);
pLocal.OffsetNegative(compensationOffset);
return pLocal;
}
 
/// <summary>
/// gets max zoom level to fit rectangle
/// </summary>
/// <param name="rect"></param>
/// <returns></returns>
public int GetMaxZoomToFitRect(RectLatLng rect)
{
int zoom = minZoom;
 
if (rect.HeightLat == 0 || rect.WidthLng == 0)
{
zoom = maxZoom / 2;
}
else
{
for (int i = (int)zoom; i <= maxZoom; i++)
{
GPoint p1 = Provider.Projection.FromLatLngToPixel(rect.LocationTopLeft, i);
GPoint p2 = Provider.Projection.FromLatLngToPixel(rect.LocationRightBottom, i);
 
if (((p2.X - p1.X) <= Width + 10) && (p2.Y - p1.Y) <= Height + 10)
{
zoom = i;
}
else
{
break;
}
}
}
 
return zoom;
}
 
/// <summary>
/// initiates map dragging
/// </summary>
/// <param name="pt"></param>
public void BeginDrag(GPoint pt)
{
dragPoint.X = pt.X - renderOffset.X;
dragPoint.Y = pt.Y - renderOffset.Y;
IsDragging = true;
}
 
/// <summary>
/// ends map dragging
/// </summary>
public void EndDrag()
{
IsDragging = false;
mouseDown = GPoint.Empty;
 
Refresh.Set();
}
 
/// <summary>
/// reloads map
/// </summary>
public void ReloadMap()
{
if (IsStarted)
{
Debug.WriteLine("------------------");
 
okZoom = 0;
skipOverZoom = 0;
 
CancelAsyncTasks();
 
Matrix.ClearAllLevels();
 
lock (FailedLoads)
{
FailedLoads.Clear();
RaiseEmptyTileError = true;
}
 
Refresh.Set();
 
UpdateBounds();
}
else
{
throw new Exception("Please, do not call ReloadMap before form is loaded, it's useless");
}
}
 
/// <summary>
/// moves current position into map center
/// </summary>
public void GoToCurrentPosition()
{
compensationOffset = positionPixel; // TODO: fix
 
// reset stuff
renderOffset = GPoint.Empty;
dragPoint = GPoint.Empty;
 
//var dd = new GPoint(-(CurrentPositionGPixel.X - Width / 2), -(CurrentPositionGPixel.Y - Height / 2));
//dd.Offset(compensationOffset);
 
var d = new GPoint(Width / 2, Height / 2);
 
this.Drag(d);
}
 
public bool MouseWheelZooming = false;
 
/// <summary>
/// moves current position into map center
/// </summary>
internal void GoToCurrentPositionOnZoom()
{
compensationOffset = positionPixel; // TODO: fix
 
// reset stuff
renderOffset = GPoint.Empty;
dragPoint = GPoint.Empty;
 
// goto location and centering
if (MouseWheelZooming)
{
if (MouseWheelZoomType != MouseWheelZoomType.MousePositionWithoutCenter)
{
GPoint pt = new GPoint(-(positionPixel.X - Width / 2), -(positionPixel.Y - Height / 2));
pt.Offset(compensationOffset);
renderOffset.X = pt.X - dragPoint.X;
renderOffset.Y = pt.Y - dragPoint.Y;
}
else // without centering
{
renderOffset.X = -positionPixel.X - dragPoint.X;
renderOffset.Y = -positionPixel.Y - dragPoint.Y;
renderOffset.Offset(mouseLastZoom);
renderOffset.Offset(compensationOffset);
}
}
else // use current map center
{
mouseLastZoom = GPoint.Empty;
 
GPoint pt = new GPoint(-(positionPixel.X - Width / 2), -(positionPixel.Y - Height / 2));
pt.Offset(compensationOffset);
renderOffset.X = pt.X - dragPoint.X;
renderOffset.Y = pt.Y - dragPoint.Y;
}
 
UpdateCenterTileXYLocation();
}
 
/// <summary>
/// darg map by offset in pixels
/// </summary>
/// <param name="offset"></param>
public void DragOffset(GPoint offset)
{
renderOffset.Offset(offset);
 
UpdateCenterTileXYLocation();
 
if (centerTileXYLocation != centerTileXYLocationLast)
{
centerTileXYLocationLast = centerTileXYLocation;
UpdateBounds();
}
 
{
LastLocationInBounds = Position;
 
IsDragging = true;
Position = FromLocalToLatLng((int)Width / 2, (int)Height / 2);
IsDragging = false;
}
 
if (OnMapDrag != null)
{
OnMapDrag();
}
}
 
/// <summary>
/// drag map
/// </summary>
/// <param name="pt"></param>
public void Drag(GPoint pt)
{
renderOffset.X = pt.X - dragPoint.X;
renderOffset.Y = pt.Y - dragPoint.Y;
 
UpdateCenterTileXYLocation();
 
if (centerTileXYLocation != centerTileXYLocationLast)
{
centerTileXYLocationLast = centerTileXYLocation;
UpdateBounds();
}
 
if (IsDragging)
{
LastLocationInBounds = Position;
Position = FromLocalToLatLng((int)Width / 2, (int)Height / 2);
 
if (OnMapDrag != null)
{
OnMapDrag();
}
}
}
 
/// <summary>
/// cancels tile loaders and bounds checker
/// </summary>
public void CancelAsyncTasks()
{
if (IsStarted)
{
#if NET40
//TODO: clear loading
#else
Monitor.Enter(tileLoadQueue);
try
{
tileLoadQueue.Clear();
}
finally
{
Monitor.Exit(tileLoadQueue);
}
#endif
}
}
 
bool RaiseEmptyTileError = false;
internal Dictionary<LoadTask, Exception> FailedLoads = new Dictionary<LoadTask, Exception>(new LoadTaskComparer());
 
internal static readonly int WaitForTileLoadThreadTimeout = 5 * 1000 * 60; // 5 min.
 
volatile int okZoom = 0;
volatile int skipOverZoom = 0;
 
#if NET40
static readonly BlockingCollection<LoadTask> tileLoadQueue4 = new BlockingCollection<LoadTask>(new ConcurrentStack<LoadTask>());
static List<Task> tileLoadQueue4Tasks;
static int loadWaitCount = 0;
void AddLoadTask(LoadTask t)
{
if (tileLoadQueue4Tasks == null)
{
lock (tileLoadQueue4)
{
if (tileLoadQueue4Tasks == null)
{
tileLoadQueue4Tasks = new List<Task>();
 
while (tileLoadQueue4Tasks.Count < GThreadPoolSize)
{
Debug.WriteLine("creating ProcessLoadTask: " + tileLoadQueue4Tasks.Count);
 
tileLoadQueue4Tasks.Add(Task.Factory.StartNew(delegate ()
{
string ctid = "ProcessLoadTask[" + Thread.CurrentThread.ManagedThreadId + "]";
Thread.CurrentThread.Name = ctid;
 
Debug.WriteLine(ctid + ": started");
do
{
if (tileLoadQueue4.Count == 0)
{
Debug.WriteLine(ctid + ": ready");
 
if (Interlocked.Increment(ref loadWaitCount) >= GThreadPoolSize)
{
Interlocked.Exchange(ref loadWaitCount, 0);
OnLoadComplete(ctid);
}
}
ProcessLoadTask(tileLoadQueue4.Take(), ctid);
}
while (!tileLoadQueue4.IsAddingCompleted);
 
Debug.WriteLine(ctid + ": exit");
 
}, TaskCreationOptions.LongRunning));
}
}
}
}
tileLoadQueue4.Add(t);
}
#else
byte loadWaitCount = 0;
 
void tileLoadThread()
{
LoadTask? task = null;
bool stop = false;
 
#if !PocketPC
Thread ct = Thread.CurrentThread;
string ctid = "Thread[" + ct.ManagedThreadId + "]";
#else
int ctid = 0;
#endif
while (!stop && IsStarted)
{
task = null;
 
Monitor.Enter(tileLoadQueue);
try
{
while (tileLoadQueue.Count == 0)
{
Debug.WriteLine(ctid + " - Wait " + loadWaitCount + " - " + DateTime.Now.TimeOfDay);
 
if (++loadWaitCount >= GThreadPoolSize)
{
loadWaitCount = 0;
OnLoadComplete(ctid);
}
 
if (!IsStarted || false == Monitor.Wait(tileLoadQueue, WaitForTileLoadThreadTimeout, false) || !IsStarted)
{
stop = true;
break;
}
}
 
if (IsStarted && !stop || tileLoadQueue.Count > 0)
{
task = tileLoadQueue.Pop();
}
}
finally
{
Monitor.Exit(tileLoadQueue);
}
 
if (task.HasValue && IsStarted)
{
ProcessLoadTask(task.Value, ctid);
}
}
 
#if !PocketPC
Monitor.Enter(tileLoadQueue);
try
{
Debug.WriteLine("Quit - " + ct.Name);
lock (GThreadPool)
{
GThreadPool.Remove(ct);
}
}
finally
{
Monitor.Exit(tileLoadQueue);
}
#endif
}
#endif
 
static void ProcessLoadTask(LoadTask task, string ctid)
{
try
{
#region -- execute --
 
var m = task.Core.Matrix.GetTileWithReadLock(task.Zoom, task.Pos);
if (!m.NotEmpty)
{
Debug.WriteLine(ctid + " - try load: " + task);
 
Tile t = new Tile(task.Zoom, task.Pos);
 
foreach (var tl in task.Core.provider.Overlays)
{
int retry = 0;
do
{
PureImage img = null;
Exception ex = null;
 
if (task.Zoom >= task.Core.provider.MinZoom && (!task.Core.provider.MaxZoom.HasValue || task.Zoom <= task.Core.provider.MaxZoom))
{
if (task.Core.skipOverZoom == 0 || task.Zoom <= task.Core.skipOverZoom)
{
// tile number inversion(BottomLeft -> TopLeft)
if (tl.InvertedAxisY)
{
img = GMaps.Instance.GetImageFrom(tl, new GPoint(task.Pos.X, task.Core.maxOfTiles.Height - task.Pos.Y), task.Zoom, out ex);
}
else // ok
{
img = GMaps.Instance.GetImageFrom(tl, task.Pos, task.Zoom, out ex);
}
}
}
 
if (img != null && ex == null)
{
if (task.Core.okZoom < task.Zoom)
{
task.Core.okZoom = task.Zoom;
task.Core.skipOverZoom = 0;
Debug.WriteLine("skipOverZoom disabled, okZoom: " + task.Core.okZoom);
}
}
else if (ex != null)
{
if ((task.Core.skipOverZoom != task.Core.okZoom) && (task.Zoom > task.Core.okZoom))
{
if (ex.Message.Contains("(404) Not Found"))
{
task.Core.skipOverZoom = task.Core.okZoom;
Debug.WriteLine("skipOverZoom enabled: " + task.Core.skipOverZoom);
}
}
}
 
// check for parent tiles if not found
if (img == null && task.Core.okZoom > 0 && task.Core.fillEmptyTiles && task.Core.Provider.Projection is MercatorProjection)
{
int zoomOffset = task.Zoom > task.Core.okZoom ? task.Zoom - task.Core.okZoom : 1;
long Ix = 0;
GPoint parentTile = GPoint.Empty;
 
while (img == null && zoomOffset < task.Zoom)
{
Ix = (long)Math.Pow(2, zoomOffset);
parentTile = new GMap.NET.GPoint((task.Pos.X / Ix), (task.Pos.Y / Ix));
img = GMaps.Instance.GetImageFrom(tl, parentTile, task.Zoom - zoomOffset++, out ex);
}
 
if (img != null)
{
// offsets in quadrant
long Xoff = Math.Abs(task.Pos.X - (parentTile.X * Ix));
long Yoff = Math.Abs(task.Pos.Y - (parentTile.Y * Ix));
 
img.IsParent = true;
img.Ix = Ix;
img.Xoff = Xoff;
img.Yoff = Yoff;
 
// wpf
//var geometry = new RectangleGeometry(new Rect(Core.tileRect.X + 0.6, Core.tileRect.Y + 0.6, Core.tileRect.Width + 0.6, Core.tileRect.Height + 0.6));
//var parentImgRect = new Rect(Core.tileRect.X - Core.tileRect.Width * Xoff + 0.6, Core.tileRect.Y - Core.tileRect.Height * Yoff + 0.6, Core.tileRect.Width * Ix + 0.6, Core.tileRect.Height * Ix + 0.6);
 
// gdi+
//System.Drawing.Rectangle dst = new System.Drawing.Rectangle((int)Core.tileRect.X, (int)Core.tileRect.Y, (int)Core.tileRect.Width, (int)Core.tileRect.Height);
//System.Drawing.RectangleF srcRect = new System.Drawing.RectangleF((float)(Xoff * (img.Img.Width / Ix)), (float)(Yoff * (img.Img.Height / Ix)), (img.Img.Width / Ix), (img.Img.Height / Ix));
}
}
 
if (img != null)
{
Debug.WriteLine(ctid + " - tile loaded: " + img.Data.Length / 1024 + "KB, " + task);
{
t.AddOverlay(img);
}
break;
}
else
{
if (ex != null)
{
lock (task.Core.FailedLoads)
{
if (!task.Core.FailedLoads.ContainsKey(task))
{
task.Core.FailedLoads.Add(task, ex);
 
if (task.Core.OnEmptyTileError != null)
{
if (!task.Core.RaiseEmptyTileError)
{
task.Core.RaiseEmptyTileError = true;
task.Core.OnEmptyTileError(task.Zoom, task.Pos);
}
}
}
}
}
 
if (task.Core.RetryLoadTile > 0)
{
Debug.WriteLine(ctid + " - ProcessLoadTask: " + task + " -> empty tile, retry " + retry);
{
Thread.Sleep(1111);
}
}
}
}
while (++retry < task.Core.RetryLoadTile);
}
 
if (t.HasAnyOverlays && task.Core.IsStarted)
{
task.Core.Matrix.SetTile(t);
}
else
{
t.Dispose();
}
}
 
#endregion
}
catch (Exception ex)
{
Debug.WriteLine(ctid + " - ProcessLoadTask: " + ex.ToString());
}
finally
{
if (task.Core.Refresh != null)
{
task.Core.Refresh.Set();
}
}
}
 
void OnLoadComplete(string ctid)
{
LastTileLoadEnd = DateTime.Now;
long lastTileLoadTimeMs = (long)(LastTileLoadEnd - LastTileLoadStart).TotalMilliseconds;
 
#region -- clear stuff--
if (IsStarted)
{
GMaps.Instance.MemoryCache.RemoveOverload();
 
tileDrawingListLock.AcquireReaderLock();
try
{
Matrix.ClearLevelAndPointsNotIn(Zoom, tileDrawingList);
}
finally
{
tileDrawingListLock.ReleaseReaderLock();
}
}
#endregion
 
UpdateGroundResolution();
#if UseGC
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
#endif
Debug.WriteLine(ctid + " - OnTileLoadComplete: " + lastTileLoadTimeMs + "ms, MemoryCacheSize: " + GMaps.Instance.MemoryCache.Size + "MB");
 
if (OnTileLoadComplete != null)
{
OnTileLoadComplete(lastTileLoadTimeMs);
}
}
 
public AutoResetEvent Refresh = new AutoResetEvent(false);
 
public bool updatingBounds = false;
 
/// <summary>
/// updates map bounds
/// </summary>
void UpdateBounds()
{
if (!IsStarted || Provider.Equals(EmptyProvider.Instance))
{
return;
}
 
updatingBounds = true;
 
tileDrawingListLock.AcquireWriterLock();
try
{
#region -- find tiles around --
tileDrawingList.Clear();
 
for (long i = (int)Math.Floor(-sizeOfMapArea.Width * scaleX), countI = (int)Math.Ceiling(sizeOfMapArea.Width * scaleX); i <= countI; i++)
{
for (long j = (int)Math.Floor(-sizeOfMapArea.Height * scaleY), countJ = (int)Math.Ceiling(sizeOfMapArea.Height * scaleY); j <= countJ; j++)
{
GPoint p = centerTileXYLocation;
p.X += i;
p.Y += j;
 
#if ContinuesMap
// ----------------------------
if(p.X < minOfTiles.Width)
{
p.X += (maxOfTiles.Width + 1);
}
 
if(p.X > maxOfTiles.Width)
{
p.X -= (maxOfTiles.Width + 1);
}
// ----------------------------
#endif
 
if (p.X >= minOfTiles.Width && p.Y >= minOfTiles.Height && p.X <= maxOfTiles.Width && p.Y <= maxOfTiles.Height)
{
DrawTile dt = new DrawTile()
{
PosXY = p,
PosPixel = new GPoint(p.X * tileRect.Width, p.Y * tileRect.Height),
DistanceSqr = (centerTileXYLocation.X - p.X) * (centerTileXYLocation.X - p.X) + (centerTileXYLocation.Y - p.Y) * (centerTileXYLocation.Y - p.Y)
};
 
if (!tileDrawingList.Contains(dt))
{
tileDrawingList.Add(dt);
}
}
}
}
 
if (GMaps.Instance.ShuffleTilesOnLoad)
{
Stuff.Shuffle<DrawTile>(tileDrawingList);
}
else
{
tileDrawingList.Sort();
}
#endregion
}
finally
{
tileDrawingListLock.ReleaseWriterLock();
}
 
#if NET40
Interlocked.Exchange(ref loadWaitCount, 0);
#else
Monitor.Enter(tileLoadQueue);
try
{
#endif
tileDrawingListLock.AcquireReaderLock();
try
{
foreach (DrawTile p in tileDrawingList)
{
LoadTask task = new LoadTask(p.PosXY, Zoom, this);
#if NET40
AddLoadTask(task);
#else
{
if (!tileLoadQueue.Contains(task))
{
tileLoadQueue.Push(task);
}
}
#endif
}
}
finally
{
tileDrawingListLock.ReleaseReaderLock();
}
 
#if !NET40
#region -- starts loader threads if needed --
 
lock (GThreadPool)
{
while (GThreadPool.Count < GThreadPoolSize)
{
Thread t = new Thread(new ThreadStart(tileLoadThread));
{
t.Name = "TileLoader: " + GThreadPool.Count;
t.IsBackground = true;
t.Priority = ThreadPriority.BelowNormal;
}
GThreadPool.Add(t);
 
Debug.WriteLine("add " + t.Name + " to GThreadPool");
 
t.Start();
}
}
#endregion
#endif
{
LastTileLoadStart = DateTime.Now;
Debug.WriteLine("OnTileLoadStart - at zoom " + Zoom + ", time: " + LastTileLoadStart.TimeOfDay);
}
#if !NET40
loadWaitCount = 0;
Monitor.PulseAll(tileLoadQueue);
}
finally
{
Monitor.Exit(tileLoadQueue);
}
#endif
updatingBounds = false;
 
if (OnTileLoadStart != null)
{
OnTileLoadStart();
}
}
 
/// <summary>
/// updates ground resolution info
/// </summary>
void UpdateGroundResolution()
{
double rez = Provider.Projection.GetGroundResolution(Zoom, Position.Lat);
pxRes100m = (int)(100.0 / rez); // 100 meters
pxRes1000m = (int)(1000.0 / rez); // 1km
pxRes10km = (int)(10000.0 / rez); // 10km
pxRes100km = (int)(100000.0 / rez); // 100km
pxRes1000km = (int)(1000000.0 / rez); // 1000km
pxRes5000km = (int)(5000000.0 / rez); // 5000km
}
 
#region IDisposable Members
 
~Core()
{
Dispose(false);
}
 
void Dispose(bool disposing)
{
if (IsStarted)
{
if (invalidator != null)
{
invalidator.CancelAsync();
invalidator.DoWork -= new DoWorkEventHandler(invalidatorWatch);
invalidator.Dispose();
invalidator = null;
}
 
if (Refresh != null)
{
Refresh.Set();
Refresh.Close();
Refresh = null;
}
 
int x = Interlocked.Decrement(ref instances);
Debug.WriteLine("OnMapClose: " + x);
 
CancelAsyncTasks();
IsStarted = false;
 
if (Matrix != null)
{
Matrix.Dispose();
Matrix = null;
}
 
if (FailedLoads != null)
{
lock (FailedLoads)
{
FailedLoads.Clear();
RaiseEmptyTileError = false;
}
FailedLoads = null;
}
 
tileDrawingListLock.AcquireWriterLock();
try
{
tileDrawingList.Clear();
}
finally
{
tileDrawingListLock.ReleaseWriterLock();
}
 
#if NET40
//TODO: maybe
#else
// cancel waiting loaders
Monitor.Enter(tileLoadQueue);
try
{
Monitor.PulseAll(tileLoadQueue);
}
finally
{
Monitor.Exit(tileLoadQueue);
}
 
lock (GThreadPool)
{
#if PocketPC
Debug.WriteLine("waiting until loaders are stopped...");
while(GThreadPool.Count > 0)
{
var t = GThreadPool[0];
 
if (t.State != ThreadState.Stopped)
{
var tr = t.Join(1111);
 
Debug.WriteLine(t.Name + ", " + t.State);
 
if (!tr)
{
continue;
}
else
{
GThreadPool.Remove(t);
}
}
else
{
GThreadPool.Remove(t);
}
}
Thread.Sleep(1111);
#endif
}
#endif
 
if (tileDrawingListLock != null)
{
tileDrawingListLock.Dispose();
tileDrawingListLock = null;
tileDrawingList = null;
}
 
if (x == 0)
{
#if DEBUG
GMaps.Instance.CancelTileCaching();
#endif
GMaps.Instance.noMapInstances = true;
GMaps.Instance.WaitForCache.Set();
if (disposing)
{
GMaps.Instance.MemoryCache.Clear();
}
}
}
}
 
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
 
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/DrawTile.cs
0,0 → 1,37

using System;
namespace GMap.NET.Internals
{
/// <summary>
/// struct for drawing tile
/// </summary>
internal struct DrawTile : IEquatable<DrawTile>, IComparable<DrawTile>
{
public GPoint PosXY;
public GPoint PosPixel;
public double DistanceSqr;
 
public override string ToString()
{
return PosXY + ", px: " + PosPixel;
}
 
#region IEquatable<DrawTile> Members
 
public bool Equals(DrawTile other)
{
return (PosXY == other.PosXY);
}
 
#endregion
 
#region IComparable<DrawTile> Members
 
public int CompareTo(DrawTile other)
{
return other.DistanceSqr.CompareTo(DistanceSqr);
}
 
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/FastReaderWriterLock.cs
0,0 → 1,194
#if !MONO && !PocketPC
#define UseFastResourceLock
#endif
 
namespace GMap.NET.Internals
{
using System;
using System.Threading;
#if !MONO
using System.Runtime.InteropServices;
#endif
 
/// <summary>
/// custom ReaderWriterLock
/// in Vista and later uses integrated Slim Reader/Writer (SRW) Lock
/// http://msdn.microsoft.com/en-us/library/aa904937(VS.85).aspx
/// http://msdn.microsoft.com/en-us/magazine/cc163405.aspx#S2
/// </summary>
public sealed class FastReaderWriterLock : IDisposable
{
#if !MONO && !PocketPC
private static class NativeMethods
{
// Methods
[DllImport("Kernel32", ExactSpelling = true)]
internal static extern void AcquireSRWLockExclusive(ref IntPtr srw);
[DllImport("Kernel32", ExactSpelling = true)]
internal static extern void AcquireSRWLockShared(ref IntPtr srw);
[DllImport("Kernel32", ExactSpelling = true)]
internal static extern void InitializeSRWLock(out IntPtr srw);
[DllImport("Kernel32", ExactSpelling = true)]
internal static extern void ReleaseSRWLockExclusive(ref IntPtr srw);
[DllImport("Kernel32", ExactSpelling = true)]
internal static extern void ReleaseSRWLockShared(ref IntPtr srw);
}
 
IntPtr LockSRW = IntPtr.Zero;
 
public FastReaderWriterLock()
{
if (UseNativeSRWLock)
{
NativeMethods.InitializeSRWLock(out this.LockSRW);
}
else
{
#if UseFastResourceLock
pLock = new FastResourceLock();
#endif
}
}
 
#if UseFastResourceLock
~FastReaderWriterLock()
{
Dispose(false);
}
 
void Dispose(bool disposing)
{
if (pLock != null)
{
pLock.Dispose();
pLock = null;
}
}
 
FastResourceLock pLock;
#endif
 
static readonly bool UseNativeSRWLock = Stuff.IsRunningOnVistaOrLater() && IntPtr.Size == 4; // works only in 32-bit mode, any ideas on native 64-bit support?
 
#endif
 
#if !UseFastResourceLock
Int32 busy = 0;
Int32 readCount = 0;
#endif
 
public void AcquireReaderLock()
{
#if !MONO && !PocketPC
if (UseNativeSRWLock)
{
NativeMethods.AcquireSRWLockShared(ref LockSRW);
}
else
#endif
{
#if UseFastResourceLock
pLock.AcquireShared();
#else
Thread.BeginCriticalRegion();
 
while(Interlocked.CompareExchange(ref busy, 1, 0) != 0)
{
Thread.Sleep(1);
}
 
Interlocked.Increment(ref readCount);
 
// somehow this fix deadlock on heavy reads
Thread.Sleep(0);
Thread.Sleep(0);
Thread.Sleep(0);
Thread.Sleep(0);
Thread.Sleep(0);
Thread.Sleep(0);
Thread.Sleep(0);
 
Interlocked.Exchange(ref busy, 0);
#endif
}
}
 
public void ReleaseReaderLock()
{
#if !MONO && !PocketPC
if (UseNativeSRWLock)
{
NativeMethods.ReleaseSRWLockShared(ref LockSRW);
}
else
#endif
{
#if UseFastResourceLock
pLock.ReleaseShared();
#else
Interlocked.Decrement(ref readCount);
Thread.EndCriticalRegion();
#endif
}
}
 
public void AcquireWriterLock()
{
#if !MONO && !PocketPC
if (UseNativeSRWLock)
{
NativeMethods.AcquireSRWLockExclusive(ref LockSRW);
}
else
#endif
{
#if UseFastResourceLock
pLock.AcquireExclusive();
#else
Thread.BeginCriticalRegion();
 
while(Interlocked.CompareExchange(ref busy, 1, 0) != 0)
{
Thread.Sleep(1);
}
 
while(Interlocked.CompareExchange(ref readCount, 0, 0) != 0)
{
Thread.Sleep(1);
}
#endif
}
}
 
public void ReleaseWriterLock()
{
#if !MONO && !PocketPC
if (UseNativeSRWLock)
{
NativeMethods.ReleaseSRWLockExclusive(ref LockSRW);
}
else
#endif
{
#if UseFastResourceLock
pLock.ReleaseExclusive();
#else
Interlocked.Exchange(ref busy, 0);
Thread.EndCriticalRegion();
#endif
}
}
 
#region IDisposable Members
 
public void Dispose()
{
#if UseFastResourceLock
this.Dispose(true);
GC.SuppressFinalize(this);
#endif
}
 
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/FastResourceLock.cs
0,0 → 1,976
/*
* Process Hacker -
* fast resource lock
*
* Copyright (C) 2009 wj32
*
* This file is part of Process Hacker.
*
* Process Hacker is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Process Hacker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Process Hacker. If not, see <http://www.gnu.org/licenses/>.
*/
 
//#define DEFER_EVENT_CREATION
//#define ENABLE_STATISTICS
//#define RIGOROUS_CHECKS
 
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
 
namespace GMap.NET.Internals
{
#if !MONO && !PocketPC
/// <summary>
/// Provides a fast resource (reader-writer) lock.
/// </summary>
/// <remarks>
/// There are three types of acquire methods in this lock:
///
/// Normal methods (AcquireExclusive, AcquireShared) are preferred
/// for general purpose use.
/// Busy wait methods (SpinAcquireExclusive, SpinAcquireShared) are
/// preferred if very little time is spent while the lock is acquired.
/// However, these do not give exclusive acquires precedence over
/// shared acquires.
/// Try methods (TryAcquireExclusive, TryAcquireShared) can be used to
/// quickly test if the lock is available.
///
/// Note that all three types of functions can be used concurrently
/// in the same class instance.
/// </remarks>
internal sealed class FastResourceLock : IDisposable
{
// Details
//
// Resource lock value width: 32 bits.
// Lock owned (either exclusive or shared): L (1 bit).
// Exclusive waking: W (1 bit).
// Shared owners count: SC (10 bits).
// Shared waiters count: SW (10 bits).
// Exclusive waiters count: EW (10 bits).
//
// Acquire exclusive:
// {L=0,W=0,SC=0,SW,EW=0} -> {L=1,W=0,SC=0,SW,EW=0}
// {L=0,W=1,SC=0,SW,EW} or {L=1,W,SC,SW,EW} ->
// {L,W,SC,SW,EW+1},
// wait on event,
// {L=0,W=1,SC=0,SW,EW} -> {L=1,W=0,SC=0,SW,EW}
//
// Acquire shared:
// {L=0,W=0,SC=0,SW,EW=0} -> {L=1,W=0,SC=1,SW,EW=0}
// {L=1,W=0,SC>0,SW,EW=0} -> {L=1,W=0,SC+1,SW,EW=0}
// {L=1,W=0,SC=0,SW,EW=0} or {L,W=1,SC,SW,EW} or
// {L,W,SC,SW,EW>0} -> {L,W,SC,SW+1,EW},
// wait on event,
// retry.
//
// Release exclusive:
// {L=1,W=0,SC=0,SW,EW>0} ->
// {L=0,W=1,SC=0,SW,EW-1},
// release one exclusive waiter.
// {L=1,W=0,SC=0,SW,EW=0} ->
// {L=0,W=0,SC=0,SW=0,EW=0},
// release all shared waiters.
//
// Note that we never do a direct acquire when W=1
// (i.e. L=0 if W=1), so here we don't have to check
// the value of W.
//
// Release shared:
// {L=1,W=0,SC>1,SW,EW} -> {L=1,W=0,SC-1,SW,EW}
// {L=1,W=0,SC=1,SW,EW=0} -> {L=0,W=0,SC=0,SW,EW=0}
// {L=1,W=0,SC=1,SW,EW>0} ->
// {L=0,W=1,SC=0,SW,EW-1},
// release one exclusive waiter.
//
// Again, we don't need to check the value of W.
//
// Convert exclusive to shared:
// {L=1,W=0,SC=0,SW,EW} ->
// {L=1,W=0,SC=1,SW=0,EW},
// release all shared waiters.
//
// Convert shared to exclusive:
// {L=1,W=0,SC=1,SW,EW} ->
// {L=1,W=0,SC=0,SW,EW}
//
 
/* */
 
// Note: I have included many small optimizations in the code
// because of the CLR's dumbass JIT compiler.
 
#region Constants
 
// Lock owned: 1 bit.
private const int LockOwned = 0x1;
 
// Exclusive waking: 1 bit.
private const int LockExclusiveWaking = 0x2;
 
// Shared owners count: 10 bits.
private const int LockSharedOwnersShift = 2;
private const int LockSharedOwnersMask = 0x3ff;
private const int LockSharedOwnersIncrement = 0x4;
 
// Shared waiters count: 10 bits.
private const int LockSharedWaitersShift = 12;
private const int LockSharedWaitersMask = 0x3ff;
private const int LockSharedWaitersIncrement = 0x1000;
 
// Exclusive waiters count: 10 bits.
private const int LockExclusiveWaitersShift = 22;
private const int LockExclusiveWaitersMask = 0x3ff;
private const int LockExclusiveWaitersIncrement = 0x400000;
 
private const int ExclusiveMask = LockExclusiveWaking | (LockExclusiveWaitersMask << LockExclusiveWaitersShift);
 
#endregion
 
public struct Statistics
{
/// <summary>
/// The number of times the lock has been acquired in exclusive mode.
/// </summary>
public int AcqExcl;
/// <summary>
/// The number of times the lock has been acquired in shared mode.
/// </summary>
public int AcqShrd;
/// <summary>
/// The number of times either the fast path was retried due to the
/// spin count or the exclusive waiter went to sleep.
/// </summary>
/// <remarks>
/// This number is usually much higher than AcqExcl, and indicates
/// a good spin count if AcqExclSlp is very small.
/// </remarks>
public int AcqExclCont;
/// <summary>
/// The number of times either the fast path was retried due to the
/// spin count or the shared waiter went to sleep.
/// </summary>
/// <remarks>
/// This number is usually much higher than AcqShrd, and indicates
/// a good spin count if AcqShrdSlp is very small.
/// </remarks>
public int AcqShrdCont;
/// <summary>
/// The number of times exclusive waiters have gone to sleep.
/// </summary>
/// <remarks>
/// If this number is high and not much time is spent in the
/// lock, consider increasing the spin count.
/// </remarks>
public int AcqExclSlp;
/// <summary>
/// The number of times shared waiters have gone to sleep.
/// </summary>
/// <remarks>
/// If this number is high and not much time is spent in the
/// lock, consider increasing the spin count.
/// </remarks>
public int AcqShrdSlp;
/// <summary>
/// The highest number of exclusive waiters at any one time.
/// </summary>
public int PeakExclWtrsCount;
/// <summary>
/// The highest number of shared waiters at any one time.
/// </summary>
public int PeakShrdWtrsCount;
}
 
// The number of times to spin before going to sleep.
private static readonly int SpinCount = NativeMethods.SpinCount;
 
private int _value;
private IntPtr _sharedWakeEvent;
private IntPtr _exclusiveWakeEvent;
 
#if ENABLE_STATISTICS
private int _acqExclCount = 0;
private int _acqShrdCount = 0;
private int _acqExclContCount = 0;
private int _acqShrdContCount = 0;
private int _acqExclSlpCount = 0;
private int _acqShrdSlpCount = 0;
private int _peakExclWtrsCount = 0;
private int _peakShrdWtrsCount = 0;
#endif
 
/// <summary>
/// Creates a FastResourceLock.
/// </summary>
public FastResourceLock()
{
_value = 0;
 
#if !DEFER_EVENT_CREATION
_sharedWakeEvent = NativeMethods.CreateSemaphore(IntPtr.Zero, 0, int.MaxValue, null);
_exclusiveWakeEvent = NativeMethods.CreateSemaphore(IntPtr.Zero, 0, int.MaxValue, null);
#endif
}
 
~FastResourceLock()
{
this.Dispose(false);
}
 
private void Dispose(bool disposing)
{
if(_sharedWakeEvent != IntPtr.Zero)
{
NativeMethods.CloseHandle(_sharedWakeEvent);
_sharedWakeEvent = IntPtr.Zero;
}
 
if(_exclusiveWakeEvent != IntPtr.Zero)
{
NativeMethods.CloseHandle(_exclusiveWakeEvent);
_exclusiveWakeEvent = IntPtr.Zero;
}
}
 
/// <summary>
/// Disposes resources associated with the FastResourceLock.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
 
/// <summary>
/// Gets the number of exclusive waiters.
/// </summary>
public int ExclusiveWaiters
{
get
{
return (_value >> LockExclusiveWaitersShift) & LockExclusiveWaitersMask;
}
}
 
/// <summary>
/// Gets whether the lock is owned in either
/// exclusive or shared mode.
/// </summary>
public bool Owned
{
get
{
return (_value & LockOwned) != 0;
}
}
 
/// <summary>
/// Gets the number of shared owners.
/// </summary>
public int SharedOwners
{
get
{
return (_value >> LockSharedOwnersShift) & LockSharedOwnersMask;
}
}
 
/// <summary>
/// Gets the number of shared waiters.
/// </summary>
public int SharedWaiters
{
get
{
return (_value >> LockSharedWaitersShift) & LockSharedWaitersMask;
}
}
 
/// <summary>
/// Acquires the lock in exclusive mode, blocking
/// if necessary.
/// </summary>
/// <remarks>
/// Exclusive acquires are given precedence over shared
/// acquires.
/// </remarks>
public void AcquireExclusive()
{
int value;
int i = 0;
 
#if ENABLE_STATISTICS
Interlocked.Increment(ref _acqExclCount);
 
#endif
while(true)
{
value = _value;
 
// Case 1: lock not owned AND an exclusive waiter is not waking up.
// Here we don't have to check if there are exclusive waiters, because
// if there are the lock would be owned, and we are checking that anyway.
if((value & (LockOwned | LockExclusiveWaking)) == 0)
{
#if RIGOROUS_CHECKS
System.Diagnostics.Trace.Assert(((value >> LockSharedOwnersShift) & LockSharedOwnersMask) == 0);
System.Diagnostics.Trace.Assert(((value >> LockExclusiveWaitersShift) & LockExclusiveWaitersMask) == 0);
 
#endif
if(Interlocked.CompareExchange(
ref _value,
value + LockOwned,
value
) == value)
break;
}
// Case 2: lock owned OR lock not owned and an exclusive waiter is waking up.
// The second case means an exclusive waiter has just been woken up and is
// going to acquire the lock. We have to go to sleep to make sure we don't
// steal the lock.
else if(i >= SpinCount)
{
#if DEFER_EVENT_CREATION
// This call must go *before* the next operation. Otherwise,
// we will have a race condition between potential releasers
// and us.
this.EnsureEventCreated(ref _exclusiveWakeEvent);
 
#endif
if(Interlocked.CompareExchange(
ref _value,
value + LockExclusiveWaitersIncrement,
value
) == value)
{
#if ENABLE_STATISTICS
Interlocked.Increment(ref _acqExclSlpCount);
 
int exclWtrsCount = (value >> LockExclusiveWaitersShift) & LockExclusiveWaitersMask;
 
Interlocked2.Set(
ref _peakExclWtrsCount,
(p) => p < exclWtrsCount,
(p) => exclWtrsCount
);
 
#endif
// Go to sleep.
if(NativeMethods.WaitForSingleObject(
_exclusiveWakeEvent,
Timeout.Infinite
) != NativeMethods.WaitObject0)
UtilsBreak("Utils.MsgFailedToWaitIndefinitely");
 
// Acquire the lock.
// At this point *no one* should be able to steal the lock from us.
do
{
value = _value;
#if RIGOROUS_CHECKS
 
System.Diagnostics.Trace.Assert((value & LockOwned) == 0);
System.Diagnostics.Trace.Assert((value & LockExclusiveWaking) != 0);
#endif
} while(Interlocked.CompareExchange(
ref _value,
value + LockOwned - LockExclusiveWaking,
value
) != value);
 
break;
}
}
 
#if ENABLE_STATISTICS
Interlocked.Increment(ref _acqExclContCount);
#endif
i++;
}
}
 
/// <summary>
/// Acquires the lock in shared mode, blocking
/// if necessary.
/// </summary>
/// <remarks>
/// Exclusive acquires are given precedence over shared
/// acquires.
/// </remarks>
public void AcquireShared()
{
int value;
int i = 0;
 
#if ENABLE_STATISTICS
Interlocked.Increment(ref _acqShrdCount);
 
#endif
while(true)
{
value = _value;
 
// Case 1: lock not owned AND no exclusive waiter is waking up AND
// there are no shared owners AND there are no exclusive waiters
if((value & (
LockOwned |
(LockSharedOwnersMask << LockSharedOwnersShift) |
ExclusiveMask
)) == 0)
{
if(Interlocked.CompareExchange(
ref _value,
value + LockOwned + LockSharedOwnersIncrement,
value
) == value)
break;
}
// Case 2: lock is owned AND no exclusive waiter is waking up AND
// there are shared owners AND there are no exclusive waiters
else if(
(value & LockOwned) != 0 &&
((value >> LockSharedOwnersShift) & LockSharedOwnersMask) != 0 &&
(value & ExclusiveMask) == 0
)
{
if(Interlocked.CompareExchange(
ref _value,
value + LockSharedOwnersIncrement,
value
) == value)
break;
}
// Other cases.
else if(i >= SpinCount)
{
#if DEFER_EVENT_CREATION
this.EnsureEventCreated(ref _sharedWakeEvent);
 
#endif
if(Interlocked.CompareExchange(
ref _value,
value + LockSharedWaitersIncrement,
value
) == value)
{
#if ENABLE_STATISTICS
Interlocked.Increment(ref _acqShrdSlpCount);
 
int shrdWtrsCount = (value >> LockSharedWaitersShift) & LockSharedWaitersMask;
 
Interlocked2.Set(
ref _peakShrdWtrsCount,
(p) => p < shrdWtrsCount,
(p) => shrdWtrsCount
);
 
#endif
// Go to sleep.
if(NativeMethods.WaitForSingleObject(
_sharedWakeEvent,
Timeout.Infinite
) != NativeMethods.WaitObject0)
UtilsBreak("Utils.MsgFailedToWaitIndefinitely");
 
// Go back and try again.
continue;
}
}
 
#if ENABLE_STATISTICS
Interlocked.Increment(ref _acqShrdContCount);
#endif
i++;
}
}
 
public static void UtilsBreak(string logMessage)
{
System.Diagnostics.Debugger.Log(0, "Error", logMessage);
System.Diagnostics.Debugger.Break();
}
 
/// <summary>
/// Converts the ownership mode from exclusive to shared.
/// </summary>
/// <remarks>
/// Exclusive acquires are not given a chance to acquire
/// the lock before this function does - as a result,
/// this function will never block.
/// </remarks>
public void ConvertExclusiveToShared()
{
int value;
int sharedWaiters;
 
while(true)
{
value = _value;
#if RIGOROUS_CHECKS
 
System.Diagnostics.Trace.Assert((value & LockOwned) != 0);
System.Diagnostics.Trace.Assert((value & LockExclusiveWaking) == 0);
System.Diagnostics.Trace.Assert(((value >> LockSharedOwnersShift) & LockSharedOwnersMask) == 0);
#endif
 
sharedWaiters = (value >> LockSharedWaitersShift) & LockSharedWaitersMask;
 
if(Interlocked.CompareExchange(
ref _value,
(value + LockSharedOwnersIncrement) & ~(LockSharedWaitersMask << LockSharedWaitersShift),
value
) == value)
{
if(sharedWaiters != 0)
NativeMethods.ReleaseSemaphore(_sharedWakeEvent, sharedWaiters, IntPtr.Zero);
 
break;
}
}
}
 
#if DEFER_EVENT_CREATION
/// <summary>
/// Checks if the specified event has been created, and
/// if not, creates it.
/// </summary>
/// <param name="handle">A reference to the event handle.</param>
private void EnsureEventCreated(ref IntPtr handle)
{
IntPtr eventHandle;
 
if(Thread.VolatileRead(ref handle) != IntPtr.Zero)
return;
 
eventHandle = NativeMethods.CreateSemaphore(IntPtr.Zero, 0, int.MaxValue, null);
 
if(Interlocked.CompareExchange(ref handle, eventHandle, IntPtr.Zero) != IntPtr.Zero)
NativeMethods.CloseHandle(eventHandle);
}
#endif
 
/// <summary>
/// Gets statistics information for the lock.
/// </summary>
/// <returns>A structure containing statistics.</returns>
public Statistics GetStatistics()
{
#if ENABLE_STATISTICS
return new Statistics()
{
AcqExcl = _acqExclCount,
AcqShrd = _acqShrdCount,
AcqExclCont = _acqExclContCount,
AcqShrdCont = _acqShrdContCount,
AcqExclSlp = _acqExclSlpCount,
AcqShrdSlp = _acqShrdSlpCount,
PeakExclWtrsCount = _peakExclWtrsCount,
PeakShrdWtrsCount = _peakShrdWtrsCount
};
#else
return new Statistics();
#endif
}
 
/// <summary>
/// Releases the lock in exclusive mode.
/// </summary>
public void ReleaseExclusive()
{
int value;
 
while(true)
{
value = _value;
#if RIGOROUS_CHECKS
 
System.Diagnostics.Trace.Assert((value & LockOwned) != 0);
System.Diagnostics.Trace.Assert((value & LockExclusiveWaking) == 0);
System.Diagnostics.Trace.Assert(((value >> LockSharedOwnersShift) & LockSharedOwnersMask) == 0);
#endif
 
// Case 1: if we have exclusive waiters, release one.
if(((value >> LockExclusiveWaitersShift) & LockExclusiveWaitersMask) != 0)
{
if(Interlocked.CompareExchange(
ref _value,
value - LockOwned + LockExclusiveWaking - LockExclusiveWaitersIncrement,
value
) == value)
{
NativeMethods.ReleaseSemaphore(_exclusiveWakeEvent, 1, IntPtr.Zero);
 
break;
}
}
// Case 2: if we have shared waiters, release all of them.
else
{
int sharedWaiters;
 
sharedWaiters = (value >> LockSharedWaitersShift) & LockSharedWaitersMask;
 
if(Interlocked.CompareExchange(
ref _value,
value & ~(LockOwned | (LockSharedWaitersMask << LockSharedWaitersShift)),
value
) == value)
{
if(sharedWaiters != 0)
NativeMethods.ReleaseSemaphore(_sharedWakeEvent, sharedWaiters, IntPtr.Zero);
 
break;
}
}
}
}
 
/// <summary>
/// Releases the lock in shared mode.
/// </summary>
public void ReleaseShared()
{
int value;
int sharedOwners;
 
while(true)
{
value = _value;
#if RIGOROUS_CHECKS
 
System.Diagnostics.Trace.Assert((value & LockOwned) != 0);
System.Diagnostics.Trace.Assert((value & LockExclusiveWaking) == 0);
System.Diagnostics.Trace.Assert(((value >> LockSharedOwnersShift) & LockSharedOwnersMask) != 0);
#endif
 
sharedOwners = (value >> LockSharedOwnersShift) & LockSharedOwnersMask;
 
// Case 1: there are multiple shared owners.
if(sharedOwners > 1)
{
if(Interlocked.CompareExchange(
ref _value,
value - LockSharedOwnersIncrement,
value
) == value)
break;
}
// Case 2: we are the last shared owner AND there are exclusive waiters.
else if(((value >> LockExclusiveWaitersShift) & LockExclusiveWaitersMask) != 0)
{
if(Interlocked.CompareExchange(
ref _value,
value - LockOwned + LockExclusiveWaking - LockSharedOwnersIncrement - LockExclusiveWaitersIncrement,
value
) == value)
{
NativeMethods.ReleaseSemaphore(_exclusiveWakeEvent, 1, IntPtr.Zero);
 
break;
}
}
// Case 3: we are the last shared owner AND there are no exclusive waiters.
else
{
if(Interlocked.CompareExchange(
ref _value,
value - LockOwned - LockSharedOwnersIncrement,
value
) == value)
break;
}
}
}
 
/// <summary>
/// Acquires the lock in exclusive mode, busy waiting
/// if necessary.
/// </summary>
/// <remarks>
/// Exclusive acquires are *not* given precedence over shared
/// acquires for busy wait methods.
/// </remarks>
public void SpinAcquireExclusive()
{
int value;
 
while(true)
{
value = _value;
 
if((value & (LockOwned | LockExclusiveWaking)) == 0)
{
if(Interlocked.CompareExchange(
ref _value,
value + LockOwned,
value
) == value)
break;
}
 
if(NativeMethods.SpinEnabled)
Thread.SpinWait(8);
else
Thread.Sleep(0);
}
}
 
/// <summary>
/// Acquires the lock in shared mode, busy waiting
/// if necessary.
/// </summary>
/// <remarks>
/// Exclusive acquires are *not* given precedence over shared
/// acquires for busy wait methods.
/// </remarks>
public void SpinAcquireShared()
{
int value;
 
while(true)
{
value = _value;
 
if((value & ExclusiveMask) == 0)
{
if((value & LockOwned) == 0)
{
if(Interlocked.CompareExchange(
ref _value,
value + LockOwned + LockSharedOwnersIncrement,
value
) == value)
break;
}
else if(((value >> LockSharedOwnersShift) & LockSharedOwnersMask) != 0)
{
if(Interlocked.CompareExchange(
ref _value,
value + LockSharedOwnersIncrement,
value
) == value)
break;
}
}
 
if(NativeMethods.SpinEnabled)
Thread.SpinWait(8);
else
Thread.Sleep(0);
}
}
 
/// <summary>
/// Converts the ownership mode from shared to exclusive,
/// busy waiting if necessary.
/// </summary>
public void SpinConvertSharedToExclusive()
{
int value;
 
while(true)
{
value = _value;
 
// Can't convert if there are other shared owners.
if(((value >> LockSharedOwnersShift) & LockSharedOwnersMask) == 1)
{
if(Interlocked.CompareExchange(
ref _value,
value - LockSharedOwnersIncrement,
value
) == value)
break;
}
 
if(NativeMethods.SpinEnabled)
Thread.SpinWait(8);
else
Thread.Sleep(0);
}
}
 
/// <summary>
/// Attempts to acquire the lock in exclusive mode.
/// </summary>
/// <returns>Whether the lock was acquired.</returns>
public bool TryAcquireExclusive()
{
int value;
 
value = _value;
 
if((value & (LockOwned | LockExclusiveWaking)) != 0)
return false;
 
return Interlocked.CompareExchange(
ref _value,
value + LockOwned,
value
) == value;
}
 
/// <summary>
/// Attempts to acquire the lock in shared mode.
/// </summary>
/// <returns>Whether the lock was acquired.</returns>
public bool TryAcquireShared()
{
int value;
 
value = _value;
 
if((value & ExclusiveMask) != 0)
return false;
 
if((value & LockOwned) == 0)
{
return Interlocked.CompareExchange(
ref _value,
value + LockOwned + LockSharedOwnersIncrement,
value
) == value;
}
else if(((value >> LockSharedOwnersShift) & LockSharedOwnersMask) != 0)
{
return Interlocked.CompareExchange(
ref _value,
value + LockSharedOwnersIncrement,
value
) == value;
}
else
{
return false;
}
}
 
/// <summary>
/// Attempts to convert the ownership mode from shared
/// to exclusive.
/// </summary>
/// <returns>Whether the lock was converted.</returns>
public bool TryConvertSharedToExclusive()
{
int value;
 
while(true)
{
value = _value;
#if RIGOROUS_CHECKS
 
System.Diagnostics.Trace.Assert((value & LockOwned) != 0);
System.Diagnostics.Trace.Assert((value & LockExclusiveWaking) == 0);
System.Diagnostics.Trace.Assert(((value >> LockSharedOwnersShift) & LockSharedOwnersMask) != 0);
#endif
 
// Can't convert if there are other shared owners.
if(((value >> LockSharedOwnersShift) & LockSharedOwnersMask) != 1)
return false;
 
if(Interlocked.CompareExchange(
ref _value,
value - LockSharedOwnersIncrement,
value
) == value)
return true;
}
}
}
 
[SuppressUnmanagedCodeSecurity]
internal class NativeMethods
{
public const int WaitObject0 = 0x0;
public const int WaitAbandoned = 0x80;
public const int WaitTimeout = 0x102;
public const int WaitFailed = -1;
 
public static readonly int SpinCount = Environment.ProcessorCount != 1 ? 4000 : 0;
public static readonly bool SpinEnabled = Environment.ProcessorCount != 1;
 
// We need to import some stuff. We can't use
// ProcessHacker.Native because it depends on this library.
 
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(
[In] IntPtr Handle
);
 
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr CreateEvent(
[In] [Optional] IntPtr EventAttributes,
[In] bool ManualReset,
[In] bool InitialState,
[In] [Optional] string Name
);
 
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr CreateSemaphore(
[In] [Optional] IntPtr SemaphoreAttributes,
[In] int InitialCount,
[In] int MaximumCount,
[In] [Optional] string Name
);
 
[DllImport("kernel32.dll")]
public static extern bool ReleaseSemaphore(
[In] IntPtr SemaphoreHandle,
[In] int ReleaseCount,
[In] IntPtr PreviousCount // out int
);
 
[DllImport("kernel32.dll")]
public static extern bool ResetEvent(
[In] IntPtr EventHandle
);
 
[DllImport("kernel32.dll")]
public static extern bool SetEvent(
[In] IntPtr EventHandle
);
 
[DllImport("kernel32.dll")]
public static extern int WaitForSingleObject(
[In] IntPtr Handle,
[In] int Milliseconds
);
 
[DllImport("ntdll.dll")]
public static extern int NtCreateKeyedEvent(
[Out] out IntPtr KeyedEventHandle,
[In] int DesiredAccess,
[In] [Optional] IntPtr ObjectAttributes,
[In] int Flags
);
 
[DllImport("ntdll.dll")]
public static extern int NtReleaseKeyedEvent(
[In] IntPtr KeyedEventHandle,
[In] IntPtr KeyValue,
[In] bool Alertable,
[In] [Optional] IntPtr Timeout
);
 
[DllImport("ntdll.dll")]
public static extern int NtWaitForKeyedEvent(
[In] IntPtr KeyedEventHandle,
[In] IntPtr KeyValue,
[In] bool Alertable,
[In] [Optional] IntPtr Timeout
);
}
#endif
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/KiberTileCache.cs
0,0 → 1,91

namespace GMap.NET.Internals
{
using System.Collections.Generic;
using System.IO;
using System;
using System.Diagnostics;
 
/// <summary>
/// kiber speed memory cache for tiles with history support ;}
/// </summary>
internal class KiberTileCache : Dictionary<RawTile, byte[]>
{
public KiberTileCache() : base(new RawTileComparer())
{
}
 
readonly Queue<RawTile> Queue = new Queue<RawTile>();
 
/// <summary>
/// the amount of tiles in MB to keep in memmory, default: 22MB, if each ~100Kb it's ~222 tiles
/// </summary>
#if !PocketPC
public int MemoryCacheCapacity = 22;
#else
public int MemoryCacheCapacity = 3;
#endif
 
long memoryCacheSize = 0;
 
/// <summary>
/// current memmory cache size in MB
/// </summary>
public double MemoryCacheSize
{
get
{
return memoryCacheSize / 1048576.0;
}
}
 
public new void Add(RawTile key, byte[] value)
{
Queue.Enqueue(key);
base.Add(key, value);
 
memoryCacheSize += value.Length;
}
 
// do not allow directly removal of elements
private new void Remove(RawTile key)
{
 
}
 
public new void Clear()
{
Queue.Clear();
base.Clear();
memoryCacheSize = 0;
}
 
internal void RemoveMemoryOverload()
{
while(MemoryCacheSize > MemoryCacheCapacity)
{
if(Keys.Count > 0 && Queue.Count > 0)
{
RawTile first = Queue.Dequeue();
try
{
var m = base[first];
{
base.Remove(first);
memoryCacheSize -= m.Length;
}
m = null;
}
catch(Exception ex)
{
Debug.WriteLine("RemoveMemoryOverload: " + ex);
}
}
else
{
break;
}
}
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/LoadTask.cs
0,0 → 1,50

using System;
using System.Collections.Generic;
namespace GMap.NET.Internals
{
/// <summary>
/// tile load task
/// </summary>
internal struct LoadTask : IEquatable<LoadTask>
{
public GPoint Pos;
public int Zoom;
 
internal Core Core;
 
public LoadTask(GPoint pos, int zoom, Core core = null)
{
Pos = pos;
Zoom = zoom;
Core = core;
}
 
public override string ToString()
{
return Zoom + " - " + Pos.ToString();
}
 
#region IEquatable<LoadTask> Members
 
public bool Equals(LoadTask other)
{
return (Zoom == other.Zoom && Pos == other.Pos);
}
 
#endregion
}
 
internal class LoadTaskComparer : IEqualityComparer<LoadTask>
{
public bool Equals(LoadTask x, LoadTask y)
{
return x.Zoom == y.Zoom && x.Pos == y.Pos;
}
 
public int GetHashCode(LoadTask obj)
{
return obj.Zoom ^ obj.Pos.GetHashCode();
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/PureImage.cs
0,0 → 1,52

namespace GMap.NET
{
using System;
using System.IO;
 
/// <summary>
/// image abstraction proxy
/// </summary>
public abstract class PureImageProxy
{
abstract public PureImage FromStream(Stream stream);
abstract public bool Save(Stream stream, PureImage image);
 
public PureImage FromArray(byte[] data)
{
MemoryStream m = new MemoryStream(data, 0, data.Length, false, true);
var pi = FromStream(m);
if(pi != null)
{
m.Position = 0;
pi.Data = m;
}
else
{
m.Dispose();
}
m = null;
 
return pi;
}
}
 
/// <summary>
/// image abstraction
/// </summary>
public abstract class PureImage : IDisposable
{
public MemoryStream Data;
 
internal bool IsParent;
internal long Ix;
internal long Xoff;
internal long Yoff;
 
#region IDisposable Members
 
public abstract void Dispose();
 
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/RawTile.cs
0,0 → 1,42
namespace GMap.NET.Internals
{
using System.IO;
using System;
using System.Collections.Generic;
 
/// <summary>
/// struct for raw tile
/// </summary>
internal struct RawTile
{
public int Type;
public GPoint Pos;
public int Zoom;
 
public RawTile(int Type, GPoint Pos, int Zoom)
{
this.Type = Type;
this.Pos = Pos;
this.Zoom = Zoom;
}
 
public override string ToString()
{
return Type + " at zoom " + Zoom + ", pos: " + Pos;
}
}
 
internal class RawTileComparer : IEqualityComparer<RawTile>
{
public bool Equals(RawTile x, RawTile y)
{
return x.Type == y.Type && x.Zoom == y.Zoom && x.Pos == y.Pos;
}
 
public int GetHashCode(RawTile obj)
{
return obj.Type ^ obj.Zoom ^ obj.Pos.GetHashCode();
}
}
}
 
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/SocksProxySocket/AuthMethod.cs
0,0 → 1,113
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
 
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
using System;
using System.Net;
using System.Net.Sockets;
 
namespace Org.Mentalis.Network.ProxySocket.Authentication {
/// <summary>
/// Implements a SOCKS authentication scheme.
/// </summary>
/// <remarks>This is an abstract class; it must be inherited.</remarks>
internal abstract class AuthMethod {
/// <summary>
/// Initializes an AuthMethod instance.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
public AuthMethod(Socket server) {
Server = server;
}
/// <summary>
/// Authenticates the user.
/// </summary>
/// <exception cref="ProxyException">Authentication with the proxy server failed.</exception>
/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
public abstract void Authenticate();
/// <summary>
/// Authenticates the user asynchronously.
/// </summary>
/// <param name="callback">The method to call when the authentication is complete.</param>
/// <exception cref="ProxyException">Authentication with the proxy server failed.</exception>
/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
public abstract void BeginAuthenticate(HandShakeComplete callback);
/// <summary>
/// Gets or sets the socket connection with the proxy server.
/// </summary>
/// <value>The socket connection with the proxy server.</value>
protected Socket Server {
get {
return m_Server;
}
set {
if (value == null)
throw new ArgumentNullException();
m_Server = value;
}
}
/// <summary>
/// Gets or sets a byt array that can be used to store data.
/// </summary>
/// <value>A byte array to store data.</value>
protected byte[] Buffer {
get {
return m_Buffer;
}
set {
m_Buffer = value;
}
}
/// <summary>
/// Gets or sets the number of bytes that have been received from the remote proxy server.
/// </summary>
/// <value>An integer that holds the number of bytes that have been received from the remote proxy server.</value>
protected int Received {
get {
return m_Received;
}
set {
m_Received = value;
}
}
// private variables
/// <summary>Holds the value of the Buffer property.</summary>
private byte[] m_Buffer;
/// <summary>Holds the value of the Server property.</summary>
private Socket m_Server;
/// <summary>Holds the address of the method to call when the proxy has authenticated the client.</summary>
protected HandShakeComplete CallBack;
/// <summary>Holds the value of the Received property.</summary>
private int m_Received;
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/SocksProxySocket/AuthNone.cs
0,0 → 1,60
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
 
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
using System;
using System.Net;
using System.Net.Sockets;
 
namespace Org.Mentalis.Network.ProxySocket.Authentication {
/// <summary>
/// This class implements the 'No Authentication' scheme.
/// </summary>
internal sealed class AuthNone : AuthMethod {
/// <summary>
/// Initializes an AuthNone instance.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
public AuthNone(Socket server) : base(server) {}
/// <summary>
/// Authenticates the user.
/// </summary>
public override void Authenticate() {
return; // Do Nothing
}
/// <summary>
/// Authenticates the user asynchronously.
/// </summary>
/// <param name="callback">The method to call when the authentication is complete.</param>
/// <remarks>This method immediately calls the callback method.</remarks>
public override void BeginAuthenticate(HandShakeComplete callback) {
callback(null);
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/SocksProxySocket/AuthUserPass.cs
0,0 → 1,157
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
 
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
namespace Org.Mentalis.Network.ProxySocket.Authentication {
/// <summary>
/// This class implements the 'username/password authentication' scheme.
/// </summary>
internal sealed class AuthUserPass : AuthMethod {
/// <summary>
/// Initializes a new AuthUserPass instance.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
/// <param name="user">The username to use.</param>
/// <param name="pass">The password to use.</param>
/// <exception cref="ArgumentNullException"><c>user</c> -or- <c>pass</c> is null.</exception>
public AuthUserPass(Socket server, string user, string pass) : base(server) {
Username = user;
Password = pass;
}
/// <summary>
/// Creates an array of bytes that has to be sent if the user wants to authenticate with the username/password authentication scheme.
/// </summary>
/// <returns>An array of bytes that has to be sent if the user wants to authenticate with the username/password authentication scheme.</returns>
private byte[] GetAuthenticationBytes() {
byte[] buffer = new byte[3 + Username.Length + Password.Length];
buffer[0] = 1;
buffer[1] = (byte)Username.Length;
Array.Copy(Encoding.ASCII.GetBytes(Username), 0, buffer, 2, Username.Length);
buffer[Username.Length + 2] = (byte)Password.Length;
Array.Copy(Encoding.ASCII.GetBytes(Password), 0, buffer, Username.Length + 3, Password.Length);
return buffer;
}
/// <summary>
/// Starts the authentication process.
/// </summary>
public override void Authenticate() {
Server.Send(GetAuthenticationBytes());
byte[] buffer = new byte[2];
int received = 0;
while (received != 2) {
received += Server.Receive(buffer, received, 2 - received, SocketFlags.None);
}
if (buffer[1] != 0) {
Server.Close();
throw new ProxyException("Username/password combination rejected.");
}
return;
}
/// <summary>
/// Starts the asynchronous authentication process.
/// </summary>
/// <param name="callback">The method to call when the authentication is complete.</param>
public override void BeginAuthenticate(HandShakeComplete callback) {
CallBack = callback;
Server.BeginSend(GetAuthenticationBytes(), 0, 3 + Username.Length + Password.Length, SocketFlags.None, new AsyncCallback(this.OnSent), Server);
return;
}
/// <summary>
/// Called when the authentication bytes have been sent.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnSent(IAsyncResult ar) {
try {
Server.EndSend(ar);
Buffer = new byte[2];
Server.BeginReceive(Buffer, 0, 2, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
} catch (Exception e) {
CallBack(e);
}
}
/// <summary>
/// Called when the socket received an authentication reply.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnReceive(IAsyncResult ar) {
try {
Received += Server.EndReceive(ar);
if (Received == Buffer.Length)
if (Buffer[1] == 0)
CallBack(null);
else
throw new ProxyException("Username/password combination not accepted.");
else
Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
} catch (Exception e) {
CallBack(e);
}
}
/// <summary>
/// Gets or sets the username to use when authenticating with the proxy server.
/// </summary>
/// <value>The username to use when authenticating with the proxy server.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
private string Username {
get {
return m_Username;
}
set {
if (value == null)
throw new ArgumentNullException();
m_Username = value;
}
}
/// <summary>
/// Gets or sets the password to use when authenticating with the proxy server.
/// </summary>
/// <value>The password to use when authenticating with the proxy server.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
private string Password {
get {
return m_Password;
}
set {
if (value == null)
throw new ArgumentNullException();
m_Password = value;
}
}
// private variables
/// <summary>Holds the value of the Username property.</summary>
private string m_Username;
/// <summary>Holds the value of the Password property.</summary>
private string m_Password;
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/SocksProxySocket/IAsyncProxyResult.cs
0,0 → 1,96
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
 
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
using System;
using System.Threading;
 
namespace Org.Mentalis.Network.ProxySocket {
/// <summary>
/// A class that implements the IAsyncResult interface. Objects from this class are returned by the BeginConnect method of the ProxySocket class.
/// </summary>
internal class IAsyncProxyResult : IAsyncResult {
/// <summary>Initializes the internal variables of this object</summary>
/// <param name="stateObject">An object that contains state information for this request.</param>
internal void Init(object stateObject) {
m_StateObject = stateObject;
m_Completed = false;
if (m_WaitHandle != null)
m_WaitHandle.Reset();
}
/// <summary>Initializes the internal variables of this object</summary>
internal void Reset() {
m_StateObject = null;
m_Completed = true;
if (m_WaitHandle != null)
m_WaitHandle.Set();
}
/// <summary>Gets a value that indicates whether the server has completed processing the call. It is illegal for the server to use any client supplied resources outside of the agreed upon sharing semantics after it sets the IsCompleted property to "true". Thus, it is safe for the client to destroy the resources after IsCompleted property returns "true".</summary>
/// <value>A boolean that indicates whether the server has completed processing the call.</value>
public bool IsCompleted {
get {
return m_Completed;
}
}
/// <summary>Gets a value that indicates whether the BeginXXXX call has been completed synchronously. If this is detected in the AsyncCallback delegate, it is probable that the thread that called BeginInvoke is the current thread.</summary>
/// <value>Returns false.</value>
public bool CompletedSynchronously {
get {
return false;
}
}
/// <summary>Gets an object that was passed as the state parameter of the BeginXXXX method call.</summary>
/// <value>The object that was passed as the state parameter of the BeginXXXX method call.</value>
public object AsyncState {
get {
return m_StateObject;
}
}
/// <summary>
/// The AsyncWaitHandle property returns the WaitHandle that can use to perform a WaitHandle.WaitOne or WaitAny or WaitAll. The object which implements IAsyncResult need not derive from the System.WaitHandle classes directly. The WaitHandle wraps its underlying synchronization primitive and should be signaled after the call is completed. This enables the client to wait for the call to complete instead polling. The Runtime supplies a number of waitable objects that mirror Win32 synchronization primitives e.g. ManualResetEvent, AutoResetEvent and Mutex.
/// WaitHandle supplies methods that support waiting for such synchronization objects to become signaled with "any" or "all" semantics i.e. WaitHandle.WaitOne, WaitAny and WaitAll. Such methods are context aware to avoid deadlocks. The AsyncWaitHandle can be allocated eagerly or on demand. It is the choice of the IAsyncResult implementer.
///</summary>
/// <value>The WaitHandle associated with this asynchronous result.</value>
public WaitHandle AsyncWaitHandle {
get {
if (m_WaitHandle == null)
m_WaitHandle = new ManualResetEvent(false);
return m_WaitHandle;
}
}
// private variables
/// <summary>Used internally to represent the state of the asynchronous request</summary>
internal bool m_Completed = true;
/// <summary>Holds the value of the StateObject property.</summary>
private object m_StateObject;
/// <summary>Holds the value of the WaitHandle property.</summary>
private ManualResetEvent m_WaitHandle;
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/SocksProxySocket/ProxyException.cs
0,0 → 1,82
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
 
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
using System;
 
namespace Org.Mentalis.Network.ProxySocket {
/// <summary>
/// The exception that is thrown when a proxy error occurs.
/// </summary>
internal class ProxyException : Exception {
/// <summary>
/// Initializes a new instance of the ProxyException class.
/// </summary>
public ProxyException() : this("An error occured while talking to the proxy server.") {}
/// <summary>
/// Initializes a new instance of the ProxyException class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public ProxyException(string message) : base(message) {}
/// <summary>
/// Initializes a new instance of the ProxyException class.
/// </summary>
/// <param name="socks5Error">The error number returned by a SOCKS5 server.</param>
public ProxyException(int socks5Error) : this(ProxyException.Socks5ToString(socks5Error)) {}
/// <summary>
/// Converts a SOCKS5 error number to a human readable string.
/// </summary>
/// <param name="socks5Error">The error number returned by a SOCKS5 server.</param>
/// <returns>A string representation of the specified SOCKS5 error number.</returns>
public static string Socks5ToString(int socks5Error) {
switch(socks5Error) {
case 0:
return "Connection succeeded.";
case 1:
return "General SOCKS server failure.";
case 2:
return "Connection not allowed by ruleset.";
case 3:
return "Network unreachable.";
case 4:
return "Host unreachable.";
case 5:
return "Connection refused.";
case 6:
return "TTL expired.";
case 7:
return "Command not supported.";
case 8:
return "Address type not supported.";
default:
return "Unspecified SOCKS error.";
}
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/SocksProxySocket/ProxySocket.cs
0,0 → 1,467
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
 
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
using System;
using System.Net;
using System.Net.Sockets;
 
// Implements a number of classes to allow Sockets to connect trough a firewall.
namespace Org.Mentalis.Network.ProxySocket
{
/// <summary>
/// Specifies the type of proxy servers that an instance of the ProxySocket class can use.
/// </summary>
internal enum ProxyTypes
{
/// <summary>No proxy server; the ProxySocket object behaves exactly like an ordinary Socket object.</summary>
None,
/// <summary>A SOCKS4[A] proxy server.</summary>
Socks4,
/// <summary>A SOCKS5 proxy server.</summary>
Socks5
}
 
/// <summary>
/// Implements a Socket class that can connect trough a SOCKS proxy server.
/// </summary>
/// <remarks>This class implements SOCKS4[A] and SOCKS5.<br>It does not, however, implement the BIND commands, so you cannot .</br></remarks>
internal class ProxySocket : Socket
{
/// <summary>
/// Initializes a new instance of the ProxySocket class.
/// </summary>
/// <param name="addressFamily">One of the AddressFamily values.</param>
/// <param name="socketType">One of the SocketType values.</param>
/// <param name="protocolType">One of the ProtocolType values.</param>
/// <exception cref="SocketException">The combination of addressFamily, socketType, and protocolType results in an invalid socket.</exception>
public ProxySocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : this(addressFamily, socketType, protocolType, "") { }
/// <summary>
/// Initializes a new instance of the ProxySocket class.
/// </summary>
/// <param name="addressFamily">One of the AddressFamily values.</param>
/// <param name="socketType">One of the SocketType values.</param>
/// <param name="protocolType">One of the ProtocolType values.</param>
/// <param name="proxyUsername">The username to use when authenticating with the proxy server.</param>
/// <exception cref="SocketException">The combination of addressFamily, socketType, and protocolType results in an invalid socket.</exception>
/// <exception cref="ArgumentNullException"><c>proxyUsername</c> is null.</exception>
public ProxySocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, string proxyUsername) : this(addressFamily, socketType, protocolType, proxyUsername, "") { }
/// <summary>
/// Initializes a new instance of the ProxySocket class.
/// </summary>
/// <param name="addressFamily">One of the AddressFamily values.</param>
/// <param name="socketType">One of the SocketType values.</param>
/// <param name="protocolType">One of the ProtocolType values.</param>
/// <param name="proxyUsername">The username to use when authenticating with the proxy server.</param>
/// <param name="proxyPassword">The password to use when authenticating with the proxy server.</param>
/// <exception cref="SocketException">The combination of addressFamily, socketType, and protocolType results in an invalid socket.</exception>
/// <exception cref="ArgumentNullException"><c>proxyUsername</c> -or- <c>proxyPassword</c> is null.</exception>
public ProxySocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, string proxyUsername, string proxyPassword)
: base(addressFamily, socketType, protocolType)
{
ProxyUser = proxyUsername;
ProxyPass = proxyPassword;
ToThrow = new InvalidOperationException();
}
/// <summary>
/// Establishes a connection to a remote device.
/// </summary>
/// <param name="remoteEP">An EndPoint that represents the remote device.</param>
/// <exception cref="ArgumentNullException">The remoteEP parameter is a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
/// <exception cref="ProxyException">An error occured while talking to the proxy server.</exception>
public new void Connect(EndPoint remoteEP)
{
if (remoteEP == null)
throw new ArgumentNullException("<remoteEP> cannot be null.");
if (this.ProtocolType != ProtocolType.Tcp || ProxyType == ProxyTypes.None || ProxyEndPoint == null)
base.Connect(remoteEP);
else
{
base.Connect(ProxyEndPoint);
if (ProxyType == ProxyTypes.Socks4)
(new Socks4Handler(this, ProxyUser)).Negotiate((IPEndPoint)remoteEP);
else if (ProxyType == ProxyTypes.Socks5)
(new Socks5Handler(this, ProxyUser, ProxyPass)).Negotiate((IPEndPoint)remoteEP);
}
}
/// <summary>
/// Establishes a connection to a remote device.
/// </summary>
/// <param name="host">The remote host to connect to.</param>
/// <param name="port">The remote port to connect to.</param>
/// <exception cref="ArgumentNullException">The host parameter is a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentException">The port parameter is invalid.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
/// <exception cref="ProxyException">An error occured while talking to the proxy server.</exception>
/// <remarks>If you use this method with a SOCKS4 server, it will let the server resolve the hostname. Not all SOCKS4 servers support this 'remote DNS' though.</remarks>
public void Connect(string host, int port)
{
if (host == null)
throw new ArgumentNullException("<host> cannot be null.");
if (port <= 0 || port > 65535)
throw new ArgumentException("Invalid port.");
if (this.ProtocolType != ProtocolType.Tcp || ProxyType == ProxyTypes.None || ProxyEndPoint == null)
base.Connect(new IPEndPoint(Dns.GetHostEntry(host).AddressList[0], port));
else
{
base.Connect(ProxyEndPoint);
if (ProxyType == ProxyTypes.Socks4)
(new Socks4Handler(this, ProxyUser)).Negotiate(host, port);
else if (ProxyType == ProxyTypes.Socks5)
(new Socks5Handler(this, ProxyUser, ProxyPass)).Negotiate(host, port);
}
}
/// <summary>
/// Begins an asynchronous request for a connection to a network device.
/// </summary>
/// <param name="remoteEP">An EndPoint that represents the remote device.</param>
/// <param name="callback">The AsyncCallback delegate.</param>
/// <param name="state">An object that contains state information for this request.</param>
/// <returns>An IAsyncResult that references the asynchronous connection.</returns>
/// <exception cref="ArgumentNullException">The remoteEP parameter is a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="SocketException">An operating system error occurs while creating the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
public new IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
{
if (remoteEP == null || callback == null)
throw new ArgumentNullException();
if (this.ProtocolType != ProtocolType.Tcp || ProxyType == ProxyTypes.None || ProxyEndPoint == null)
{
return base.BeginConnect(remoteEP, callback, state);
}
else
{
CallBack = callback;
if (ProxyType == ProxyTypes.Socks4)
{
AsyncResult = (new Socks4Handler(this, ProxyUser)).BeginNegotiate((IPEndPoint)remoteEP, new HandShakeComplete(this.OnHandShakeComplete), ProxyEndPoint);
return AsyncResult;
}
else if (ProxyType == ProxyTypes.Socks5)
{
AsyncResult = (new Socks5Handler(this, ProxyUser, ProxyPass)).BeginNegotiate((IPEndPoint)remoteEP, new HandShakeComplete(this.OnHandShakeComplete), ProxyEndPoint);
return AsyncResult;
}
return null;
}
}
/// <summary>
/// Begins an asynchronous request for a connection to a network device.
/// </summary>
/// <param name="host">The host to connect to.</param>
/// <param name="port">The port on the remote host to connect to.</param>
/// <param name="callback">The AsyncCallback delegate.</param>
/// <param name="state">An object that contains state information for this request.</param>
/// <returns>An IAsyncResult that references the asynchronous connection.</returns>
/// <exception cref="ArgumentNullException">The host parameter is a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentException">The port parameter is invalid.</exception>
/// <exception cref="SocketException">An operating system error occurs while creating the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
public IAsyncResult BeginConnect(string host, int port, AsyncCallback callback, object state)
{
if (host == null || callback == null)
throw new ArgumentNullException();
if (port <= 0 || port > 65535)
throw new ArgumentException();
CallBack = callback;
if (this.ProtocolType != ProtocolType.Tcp || ProxyType == ProxyTypes.None || ProxyEndPoint == null)
{
RemotePort = port;
AsyncResult = BeginDns(host, new HandShakeComplete(this.OnHandShakeComplete));
return AsyncResult;
}
else
{
if (ProxyType == ProxyTypes.Socks4)
{
AsyncResult = (new Socks4Handler(this, ProxyUser)).BeginNegotiate(host, port, new HandShakeComplete(this.OnHandShakeComplete), ProxyEndPoint);
return AsyncResult;
}
else if (ProxyType == ProxyTypes.Socks5)
{
AsyncResult = (new Socks5Handler(this, ProxyUser, ProxyPass)).BeginNegotiate(host, port, new HandShakeComplete(this.OnHandShakeComplete), ProxyEndPoint);
return AsyncResult;
}
return null;
}
}
/// <summary>
/// Ends a pending asynchronous connection request.
/// </summary>
/// <param name="asyncResult">Stores state information for this asynchronous operation as well as any user-defined data.</param>
/// <exception cref="ArgumentNullException">The asyncResult parameter is a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentException">The asyncResult parameter was not returned by a call to the BeginConnect method.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
/// <exception cref="InvalidOperationException">EndConnect was previously called for the asynchronous connection.</exception>
/// <exception cref="ProxyException">The proxy server refused the connection.</exception>
public new void EndConnect(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException();
if (!asyncResult.IsCompleted)
throw new ArgumentException();
if (ToThrow != null)
throw ToThrow;
return;
}
/// <summary>
/// Begins an asynchronous request to resolve a DNS host name or IP address in dotted-quad notation to an IPAddress instance.
/// </summary>
/// <param name="host">The host to resolve.</param>
/// <param name="callback">The method to call when the hostname has been resolved.</param>
/// <returns>An IAsyncResult instance that references the asynchronous request.</returns>
/// <exception cref="SocketException">There was an error while trying to resolve the host.</exception>
internal IAsyncProxyResult BeginDns(string host, HandShakeComplete callback)
{
try
{
Dns.BeginGetHostEntry(host, new AsyncCallback(this.OnResolved), this);
return new IAsyncProxyResult();
}
catch
{
throw new SocketException();
}
}
/// <summary>
/// Called when the specified hostname has been resolved.
/// </summary>
/// <param name="asyncResult">The result of the asynchronous operation.</param>
private void OnResolved(IAsyncResult asyncResult)
{
try
{
IPHostEntry dns = Dns.EndGetHostEntry(asyncResult);
base.BeginConnect(new IPEndPoint(dns.AddressList[0], RemotePort), new AsyncCallback(this.OnConnect), State);
}
catch (Exception e)
{
OnHandShakeComplete(e);
}
}
/// <summary>
/// Called when the Socket is connected to the remote host.
/// </summary>
/// <param name="asyncResult">The result of the asynchronous operation.</param>
private void OnConnect(IAsyncResult asyncResult)
{
try
{
base.EndConnect(asyncResult);
OnHandShakeComplete(null);
}
catch (Exception e)
{
OnHandShakeComplete(e);
}
}
/// <summary>
/// Called when the Socket has finished talking to the proxy server and is ready to relay data.
/// </summary>
/// <param name="error">The error to throw when the EndConnect method is called.</param>
private void OnHandShakeComplete(Exception error)
{
if (error != null)
this.Close();
ToThrow = error;
AsyncResult.Reset();
if (CallBack != null)
CallBack(AsyncResult);
}
/// <summary>
/// Gets or sets the EndPoint of the proxy server.
/// </summary>
/// <value>An IPEndPoint object that holds the IP address and the port of the proxy server.</value>
public IPEndPoint ProxyEndPoint
{
get
{
return m_ProxyEndPoint;
}
set
{
m_ProxyEndPoint = value;
}
}
/// <summary>
/// Gets or sets the type of proxy server to use.
/// </summary>
/// <value>One of the ProxyTypes values.</value>
public ProxyTypes ProxyType
{
get
{
return m_ProxyType;
}
set
{
m_ProxyType = value;
}
}
/// <summary>
/// Gets or sets a user-defined object.
/// </summary>
/// <value>The user-defined object.</value>
private object State
{
get
{
return m_State;
}
set
{
m_State = value;
}
}
/// <summary>
/// Gets or sets the username to use when authenticating with the proxy.
/// </summary>
/// <value>A string that holds the username that's used when authenticating with the proxy.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
public string ProxyUser
{
get
{
return m_ProxyUser;
}
set
{
if (value == null)
throw new ArgumentNullException();
m_ProxyUser = value;
}
}
/// <summary>
/// Gets or sets the password to use when authenticating with the proxy.
/// </summary>
/// <value>A string that holds the password that's used when authenticating with the proxy.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
public string ProxyPass
{
get
{
return m_ProxyPass;
}
set
{
if (value == null)
throw new ArgumentNullException();
m_ProxyPass = value;
}
}
/// <summary>
/// Gets or sets the asynchronous result object.
/// </summary>
/// <value>An instance of the IAsyncProxyResult class.</value>
private IAsyncProxyResult AsyncResult
{
get
{
return m_AsyncResult;
}
set
{
m_AsyncResult = value;
}
}
/// <summary>
/// Gets or sets the exception to throw when the EndConnect method is called.
/// </summary>
/// <value>An instance of the Exception class (or subclasses of Exception).</value>
private Exception ToThrow
{
get
{
return m_ToThrow;
}
set
{
m_ToThrow = value;
}
}
/// <summary>
/// Gets or sets the remote port the user wants to connect to.
/// </summary>
/// <value>An integer that specifies the port the user wants to connect to.</value>
private int RemotePort
{
get
{
return m_RemotePort;
}
set
{
m_RemotePort = value;
}
}
// private variables
/// <summary>Holds the value of the State property.</summary>
private object m_State;
/// <summary>Holds the value of the ProxyEndPoint property.</summary>
private IPEndPoint m_ProxyEndPoint = null;
/// <summary>Holds the value of the ProxyType property.</summary>
private ProxyTypes m_ProxyType = ProxyTypes.None;
/// <summary>Holds the value of the ProxyUser property.</summary>
private string m_ProxyUser = null;
/// <summary>Holds the value of the ProxyPass property.</summary>
private string m_ProxyPass = null;
/// <summary>Holds a pointer to the method that should be called when the Socket is connected to the remote device.</summary>
private AsyncCallback CallBack = null;
/// <summary>Holds the value of the AsyncResult property.</summary>
private IAsyncProxyResult m_AsyncResult;
/// <summary>Holds the value of the ToThrow property.</summary>
private Exception m_ToThrow = null;
/// <summary>Holds the value of the RemotePort property.</summary>
private int m_RemotePort;
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/SocksProxySocket/Socks4Handler.cs
0,0 → 1,234
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
 
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
namespace Org.Mentalis.Network.ProxySocket {
/// <summary>
/// Implements the SOCKS4[A] protocol.
/// </summary>
internal sealed class Socks4Handler : SocksHandler {
/// <summary>
/// Initilizes a new instance of the SocksHandler class.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
/// <param name="user">The username to use when authenticating with the server.</param>
/// <exception cref="ArgumentNullException"><c>server</c> -or- <c>user</c> is null.</exception>
public Socks4Handler(Socket server, string user) : base(server, user) {}
/// <summary>
/// Creates an array of bytes that has to be sent when the user wants to connect to a specific host/port combination.
/// </summary>
/// <param name="host">The host to connect to.</param>
/// <param name="port">The port to connect to.</param>
/// <returns>An array of bytes that has to be sent when the user wants to connect to a specific host/port combination.</returns>
/// <remarks>Resolving the host name will be done at server side. Do note that some SOCKS4 servers do not implement this functionality.</remarks>
/// <exception cref="ArgumentNullException"><c>host</c> is null.</exception>
/// <exception cref="ArgumentException"><c>port</c> is invalid.</exception>
private byte[] GetHostPortBytes(string host, int port) {
if (host == null)
throw new ArgumentNullException();
if (port <= 0 || port > 65535)
throw new ArgumentException();
byte [] connect = new byte[10 + Username.Length + host.Length];
connect[0] = 4;
connect[1] = 1;
Array.Copy(PortToBytes(port), 0, connect, 2, 2);
connect[4] = connect[5] = connect[6] = 0;
connect[7] = 1;
Array.Copy(Encoding.ASCII.GetBytes(Username), 0, connect, 8, Username.Length);
connect[8 + Username.Length] = 0;
Array.Copy(Encoding.ASCII.GetBytes(host), 0, connect, 9 + Username.Length, host.Length);
connect[9 + Username.Length + host.Length] = 0;
return connect;
}
/// <summary>
/// Creates an array of bytes that has to be sent when the user wants to connect to a specific IPEndPoint.
/// </summary>
/// <param name="remoteEP">The IPEndPoint to connect to.</param>
/// <returns>An array of bytes that has to be sent when the user wants to connect to a specific IPEndPoint.</returns>
/// <exception cref="ArgumentNullException"><c>remoteEP</c> is null.</exception>
private byte[] GetEndPointBytes(IPEndPoint remoteEP) {
if (remoteEP == null)
throw new ArgumentNullException();
byte [] connect = new byte[9 + Username.Length];
connect[0] = 4;
connect[1] = 1;
Array.Copy(PortToBytes(remoteEP.Port), 0, connect, 2, 2);
Array.Copy(remoteEP.Address.GetAddressBytes(), 0, connect, 4, 4);
Array.Copy(Encoding.ASCII.GetBytes(Username), 0, connect, 8, Username.Length);
connect[8 + Username.Length] = 0;
return connect;
}
/// <summary>
/// Starts negotiating with the SOCKS server.
/// </summary>
/// <param name="host">The host to connect to.</param>
/// <param name="port">The port to connect to.</param>
/// <exception cref="ArgumentNullException"><c>host</c> is null.</exception>
/// <exception cref="ArgumentException"><c>port</c> is invalid.</exception>
/// <exception cref="ProxyException">The proxy rejected the request.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
public override void Negotiate(string host, int port) {
Negotiate(GetHostPortBytes(host, port));
}
/// <summary>
/// Starts negotiating with the SOCKS server.
/// </summary>
/// <param name="remoteEP">The IPEndPoint to connect to.</param>
/// <exception cref="ArgumentNullException"><c>remoteEP</c> is null.</exception>
/// <exception cref="ProxyException">The proxy rejected the request.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
public override void Negotiate(IPEndPoint remoteEP) {
Negotiate(GetEndPointBytes(remoteEP));
}
/// <summary>
/// Starts negotiating with the SOCKS server.
/// </summary>
/// <param name="connect">The bytes to send when trying to authenticate.</param>
/// <exception cref="ArgumentNullException"><c>connect</c> is null.</exception>
/// <exception cref="ArgumentException"><c>connect</c> is too small.</exception>
/// <exception cref="ProxyException">The proxy rejected the request.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
private void Negotiate(byte [] connect) {
if (connect == null)
throw new ArgumentNullException();
if (connect.Length < 2)
throw new ArgumentException();
Server.Send(connect);
byte [] buffer = ReadBytes(8);
if (buffer[1] != 90) {
Server.Close();
throw new ProxyException("Negotiation failed.");
}
}
/// <summary>
/// Starts negotiating asynchronously with a SOCKS proxy server.
/// </summary>
/// <param name="host">The remote server to connect to.</param>
/// <param name="port">The remote port to connect to.</param>
/// <param name="callback">The method to call when the connection has been established.</param>
/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
public override IAsyncProxyResult BeginNegotiate(string host, int port, HandShakeComplete callback, IPEndPoint proxyEndPoint) {
ProtocolComplete = callback;
Buffer = GetHostPortBytes(host, port);
Server.BeginConnect(proxyEndPoint, new AsyncCallback(this.OnConnect), Server);
AsyncResult = new IAsyncProxyResult();
return AsyncResult;
}
/// <summary>
/// Starts negotiating asynchronously with a SOCKS proxy server.
/// </summary>
/// <param name="remoteEP">An IPEndPoint that represents the remote device.</param>
/// <param name="callback">The method to call when the connection has been established.</param>
/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
public override IAsyncProxyResult BeginNegotiate(IPEndPoint remoteEP, HandShakeComplete callback, IPEndPoint proxyEndPoint) {
ProtocolComplete = callback;
Buffer = GetEndPointBytes(remoteEP);
Server.BeginConnect(proxyEndPoint, new AsyncCallback(this.OnConnect), Server);
AsyncResult = new IAsyncProxyResult();
return AsyncResult;
}
/// <summary>
/// Called when the Socket is connected to the remote proxy server.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnConnect(IAsyncResult ar) {
try {
Server.EndConnect(ar);
} catch (Exception e) {
ProtocolComplete(e);
return;
}
try {
Server.BeginSend(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnSent), Server);
} catch (Exception e) {
ProtocolComplete(e);
}
}
/// <summary>
/// Called when the Socket has sent the handshake data.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnSent(IAsyncResult ar) {
try {
if (Server.EndSend(ar) < Buffer.Length) {
ProtocolComplete(new SocketException());
return;
}
} catch (Exception e) {
ProtocolComplete(e);
return;
}
try {
Buffer = new byte[8];
Received = 0;
Server.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
} catch (Exception e) {
ProtocolComplete(e);
}
}
/// <summary>
/// Called when the Socket has received a reply from the remote proxy server.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnReceive(IAsyncResult ar) {
try {
int received = Server.EndReceive(ar);
if (received <= 0) {
ProtocolComplete(new SocketException());
return;
}
Received += received;
if (Received == 8) {
if (Buffer[1] == 90)
ProtocolComplete(null);
else {
Server.Close();
ProtocolComplete(new ProxyException("Negotiation failed."));
}
} else {
Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
}
} catch (Exception e) {
ProtocolComplete(e);
}
}
}
}
 
 
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/SocksProxySocket/Socks5Handler.cs
0,0 → 1,420
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
 
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Org.Mentalis.Network.ProxySocket.Authentication;
 
namespace Org.Mentalis.Network.ProxySocket {
/// <summary>
/// Implements the SOCKS5 protocol.
/// </summary>
internal sealed class Socks5Handler : SocksHandler {
/// <summary>
/// Initiliazes a new Socks5Handler instance.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
/// <exception cref="ArgumentNullException"><c>server</c> is null.</exception>
public Socks5Handler(Socket server) : this(server, "") {}
/// <summary>
/// Initiliazes a new Socks5Handler instance.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
/// <param name="user">The username to use.</param>
/// <exception cref="ArgumentNullException"><c>server</c> -or- <c>user</c> is null.</exception>
public Socks5Handler(Socket server, string user) : this(server, user, "") {}
/// <summary>
/// Initiliazes a new Socks5Handler instance.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
/// <param name="user">The username to use.</param>
/// <param name="pass">The password to use.</param>
/// <exception cref="ArgumentNullException"><c>server</c> -or- <c>user</c> -or- <c>pass</c> is null.</exception>
public Socks5Handler(Socket server, string user, string pass) : base(server, user) {
Password = pass;
}
/// <summary>
/// Starts the synchronous authentication process.
/// </summary>
/// <exception cref="ProxyException">Authentication with the proxy server failed.</exception>
/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
private void Authenticate() {
Server.Send(new byte [] {5, 2, 0, 2});
byte[] buffer = ReadBytes(2);
if (buffer[1] == 255)
throw new ProxyException("No authentication method accepted.");
AuthMethod authenticate;
switch (buffer[1]) {
case 0:
authenticate = new AuthNone(Server);
break;
case 2:
authenticate = new AuthUserPass(Server, Username, Password);
break;
default:
throw new ProtocolViolationException();
}
authenticate.Authenticate();
}
/// <summary>
/// Creates an array of bytes that has to be sent when the user wants to connect to a specific host/port combination.
/// </summary>
/// <param name="host">The host to connect to.</param>
/// <param name="port">The port to connect to.</param>
/// <returns>An array of bytes that has to be sent when the user wants to connect to a specific host/port combination.</returns>
/// <exception cref="ArgumentNullException"><c>host</c> is null.</exception>
/// <exception cref="ArgumentException"><c>port</c> or <c>host</c> is invalid.</exception>
private byte[] GetHostPortBytes(string host, int port) {
if (host == null)
throw new ArgumentNullException();
if (port <= 0 || port > 65535 || host.Length > 255)
throw new ArgumentException();
byte [] connect = new byte[7 + host.Length];
connect[0] = 5;
connect[1] = 1;
connect[2] = 0; //reserved
connect[3] = 3;
connect[4] = (byte)host.Length;
Array.Copy(Encoding.ASCII.GetBytes(host), 0, connect, 5, host.Length);
Array.Copy(PortToBytes(port), 0, connect, host.Length + 5, 2);
return connect;
}
/// <summary>
/// Creates an array of bytes that has to be sent when the user wants to connect to a specific IPEndPoint.
/// </summary>
/// <param name="remoteEP">The IPEndPoint to connect to.</param>
/// <returns>An array of bytes that has to be sent when the user wants to connect to a specific IPEndPoint.</returns>
/// <exception cref="ArgumentNullException"><c>remoteEP</c> is null.</exception>
private byte[] GetEndPointBytes(IPEndPoint remoteEP) {
if (remoteEP == null)
throw new ArgumentNullException();
byte [] connect = new byte[10];
connect[0] = 5;
connect[1] = 1;
connect[2] = 0; //reserved
connect[3] = 1;
 
Array.Copy(remoteEP.Address.GetAddressBytes(), 0, connect, 4, 4);
Array.Copy(PortToBytes(remoteEP.Port), 0, connect, 8, 2);
return connect;
}
/// <summary>
/// Starts negotiating with the SOCKS server.
/// </summary>
/// <param name="host">The host to connect to.</param>
/// <param name="port">The port to connect to.</param>
/// <exception cref="ArgumentNullException"><c>host</c> is null.</exception>
/// <exception cref="ArgumentException"><c>port</c> is invalid.</exception>
/// <exception cref="ProxyException">The proxy rejected the request.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
public override void Negotiate(string host, int port) {
Negotiate(GetHostPortBytes(host, port));
}
/// <summary>
/// Starts negotiating with the SOCKS server.
/// </summary>
/// <param name="remoteEP">The IPEndPoint to connect to.</param>
/// <exception cref="ArgumentNullException"><c>remoteEP</c> is null.</exception>
/// <exception cref="ProxyException">The proxy rejected the request.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
public override void Negotiate(IPEndPoint remoteEP) {
Negotiate(GetEndPointBytes(remoteEP));
}
/// <summary>
/// Starts negotiating with the SOCKS server.
/// </summary>
/// <param name="connect">The bytes to send when trying to authenticate.</param>
/// <exception cref="ArgumentNullException"><c>connect</c> is null.</exception>
/// <exception cref="ArgumentException"><c>connect</c> is too small.</exception>
/// <exception cref="ProxyException">The proxy rejected the request.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
private void Negotiate(byte[] connect) {
Authenticate();
Server.Send(connect);
byte[] buffer = ReadBytes(4);
if (buffer[1] != 0) {
Server.Close();
throw new ProxyException(buffer[1]);
}
switch(buffer[3]) {
case 1:
buffer = ReadBytes(6); //IPv4 address with port
break;
case 3:
buffer = ReadBytes(1);
buffer = ReadBytes(buffer[0] + 2); //domain name with port
break;
case 4:
buffer = ReadBytes(18); //IPv6 address with port
break;
default:
Server.Close();
throw new ProtocolViolationException();
}
}
/// <summary>
/// Starts negotiating asynchronously with the SOCKS server.
/// </summary>
/// <param name="host">The host to connect to.</param>
/// <param name="port">The port to connect to.</param>
/// <param name="callback">The method to call when the negotiation is complete.</param>
/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
public override IAsyncProxyResult BeginNegotiate(string host, int port, HandShakeComplete callback, IPEndPoint proxyEndPoint) {
ProtocolComplete = callback;
HandShake = GetHostPortBytes(host, port);
Server.BeginConnect(proxyEndPoint, new AsyncCallback(this.OnConnect), Server);
AsyncResult = new IAsyncProxyResult();
return AsyncResult;
}
/// <summary>
/// Starts negotiating asynchronously with the SOCKS server.
/// </summary>
/// <param name="remoteEP">An IPEndPoint that represents the remote device.</param>
/// <param name="callback">The method to call when the negotiation is complete.</param>
/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
public override IAsyncProxyResult BeginNegotiate(IPEndPoint remoteEP, HandShakeComplete callback, IPEndPoint proxyEndPoint) {
ProtocolComplete = callback;
HandShake = GetEndPointBytes(remoteEP);
Server.BeginConnect(proxyEndPoint, new AsyncCallback(this.OnConnect), Server);
AsyncResult = new IAsyncProxyResult();
return AsyncResult;
}
/// <summary>
/// Called when the socket is connected to the remote server.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnConnect(IAsyncResult ar) {
try {
Server.EndConnect(ar);
} catch (Exception e) {
ProtocolComplete(e);
return;
}
try {
Server.BeginSend(new byte [] {5, 2, 0, 2}, 0, 4, SocketFlags.None, new AsyncCallback(this.OnAuthSent), Server);
} catch (Exception e) {
ProtocolComplete(e);
}
}
/// <summary>
/// Called when the authentication bytes have been sent.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnAuthSent(IAsyncResult ar) {
try {
Server.EndSend(ar);
} catch (Exception e) {
ProtocolComplete(e);
return;
}
try {
Buffer = new byte[1024];
Received = 0;
Server.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnAuthReceive), Server);
} catch (Exception e) {
ProtocolComplete(e);
}
}
/// <summary>
/// Called when an authentication reply has been received.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnAuthReceive(IAsyncResult ar) {
try {
Received += Server.EndReceive(ar);
if (Received <= 0)
throw new SocketException();
} catch (Exception e) {
ProtocolComplete(e);
return;
}
try {
if (Received < 2) {
Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnAuthReceive), Server);
} else {
AuthMethod authenticate;
switch(Buffer[1]) {
case 0:
authenticate = new AuthNone(Server);
break;
case 2:
authenticate = new AuthUserPass(Server, Username, Password);
break;
default:
ProtocolComplete(new SocketException());
return;
}
authenticate.BeginAuthenticate(new HandShakeComplete(this.OnAuthenticated));
}
} catch (Exception e) {
ProtocolComplete(e);
}
}
/// <summary>
/// Called when the socket has been successfully authenticated with the server.
/// </summary>
/// <param name="e">The exception that has occured while authenticating, or <em>null</em> if no error occured.</param>
private void OnAuthenticated(Exception e) {
if (e != null) {
ProtocolComplete(e);
return;
}
try {
Server.BeginSend(HandShake, 0, HandShake.Length, SocketFlags.None, new AsyncCallback(this.OnSent), Server);
} catch (Exception ex) {
ProtocolComplete(ex);
}
}
/// <summary>
/// Called when the connection request has been sent.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnSent(IAsyncResult ar) {
try {
Server.EndSend(ar);
} catch (Exception e) {
ProtocolComplete(e);
return;
}
try {
Buffer = new byte[5];
Received = 0;
Server.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
} catch (Exception e) {
ProtocolComplete(e);
}
}
/// <summary>
/// Called when a connection reply has been received.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnReceive(IAsyncResult ar) {
try {
Received += Server.EndReceive(ar);
} catch (Exception e) {
ProtocolComplete(e);
return;
}
try {
if (Received == Buffer.Length)
ProcessReply(Buffer);
else
Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
} catch (Exception e) {
ProtocolComplete(e);
}
}
/// <summary>
/// Processes the received reply.
/// </summary>
/// <param name="buffer">The received reply</param>
/// <exception cref="ProtocolViolationException">The received reply is invalid.</exception>
private void ProcessReply(byte[] buffer) {
switch(buffer[3]) {
case 1:
Buffer = new byte[5]; //IPv4 address with port - 1 byte
break;
case 3:
Buffer = new byte[buffer[4] + 2]; //domain name with port
break;
case 4:
buffer = new byte[17]; //IPv6 address with port - 1 byte
break;
default:
throw new ProtocolViolationException();
}
Received = 0;
Server.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReadLast), Server);
}
/// <summary>
/// Called when the last bytes are read from the socket.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnReadLast(IAsyncResult ar) {
try {
Received += Server.EndReceive(ar);
} catch (Exception e) {
ProtocolComplete(e);
return;
}
try {
if (Received == Buffer.Length)
ProtocolComplete(null);
else
Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnReadLast), Server);
} catch (Exception e) {
ProtocolComplete(e);
}
}
/// <summary>
/// Gets or sets the password to use when authenticating with the SOCKS5 server.
/// </summary>
/// <value>The password to use when authenticating with the SOCKS5 server.</value>
private string Password {
get {
return m_Password;
}
set {
if (value == null)
throw new ArgumentNullException();
m_Password = value;
}
}
/// <summary>
/// Gets or sets the bytes to use when sending a connect request to the proxy server.
/// </summary>
/// <value>The array of bytes to use when sending a connect request to the proxy server.</value>
private byte[] HandShake {
get {
return m_HandShake;
}
set {
m_HandShake = value;
}
}
// private variables
/// <summary>Holds the value of the Password property.</summary>
private string m_Password;
/// <summary>Holds the value of the HandShake property.</summary>
private byte[] m_HandShake;
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/SocksProxySocket/SocksHandler.cs
0,0 → 1,192
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
 
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
using System;
using System.Net;
using System.Net.Sockets;
 
namespace Org.Mentalis.Network.ProxySocket {
/// <summary>
/// References the callback method to be called when the protocol negotiation is completed.
/// </summary>
internal delegate void HandShakeComplete(Exception error);
/// <summary>
/// Implements a specific version of the SOCKS protocol. This is an abstract class; it must be inherited.
/// </summary>
internal abstract class SocksHandler {
/// <summary>
/// Initilizes a new instance of the SocksHandler class.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
/// <param name="user">The username to use when authenticating with the server.</param>
/// <exception cref="ArgumentNullException"><c>server</c> -or- <c>user</c> is null.</exception>
public SocksHandler(Socket server, string user) {
Server = server;
Username = user;
}
/// <summary>
/// Converts a port number to an array of bytes.
/// </summary>
/// <param name="port">The port to convert.</param>
/// <returns>An array of two bytes that represents the specified port.</returns>
protected byte[] PortToBytes(int port) {
byte [] ret = new byte[2];
ret[0] = (byte)(port / 256);
ret[1] = (byte)(port % 256);
return ret;
}
 
/// <summary>
/// Reads a specified number of bytes from the Server socket.
/// </summary>
/// <param name="count">The number of bytes to return.</param>
/// <returns>An array of bytes.</returns>
/// <exception cref="ArgumentException">The number of bytes to read is invalid.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
protected byte[] ReadBytes(int count) {
if (count <= 0)
throw new ArgumentException();
byte[] buffer = new byte[count];
int received = 0;
while(received != count) {
received += Server.Receive(buffer, received, count - received, SocketFlags.None);
}
return buffer;
}
/// <summary>
/// Gets or sets the socket connection with the proxy server.
/// </summary>
/// <value>A Socket object that represents the connection with the proxy server.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
protected Socket Server {
get {
return m_Server;
}
set {
if (value == null)
throw new ArgumentNullException();
m_Server = value;
}
}
/// <summary>
/// Gets or sets the username to use when authenticating with the proxy server.
/// </summary>
/// <value>A string that holds the username to use when authenticating with the proxy server.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
protected string Username {
get {
return m_Username;
}
set {
if (value == null)
throw new ArgumentNullException();
m_Username = value;
}
}
/// <summary>
/// Gets or sets the return value of the BeginConnect call.
/// </summary>
/// <value>An IAsyncProxyResult object that is the return value of the BeginConnect call.</value>
protected IAsyncProxyResult AsyncResult {
get {
return m_AsyncResult;
}
set {
m_AsyncResult = value;
}
}
/// <summary>
/// Gets or sets a byte buffer.
/// </summary>
/// <value>An array of bytes.</value>
protected byte[] Buffer {
get {
return m_Buffer;
}
set {
m_Buffer = value;
}
}
/// <summary>
/// Gets or sets the number of bytes that have been received from the remote proxy server.
/// </summary>
/// <value>An integer that holds the number of bytes that have been received from the remote proxy server.</value>
protected int Received {
get {
return m_Received;
}
set {
m_Received = value;
}
}
// private variables
/// <summary>Holds the value of the Server property.</summary>
private Socket m_Server;
/// <summary>Holds the value of the Username property.</summary>
private string m_Username;
/// <summary>Holds the value of the AsyncResult property.</summary>
private IAsyncProxyResult m_AsyncResult;
/// <summary>Holds the value of the Buffer property.</summary>
private byte[] m_Buffer;
/// <summary>Holds the value of the Received property.</summary>
private int m_Received;
/// <summary>Holds the address of the method to call when the SOCKS protocol has been completed.</summary>
protected HandShakeComplete ProtocolComplete;
/// <summary>
/// Starts negotiating with a SOCKS proxy server.
/// </summary>
/// <param name="host">The remote server to connect to.</param>
/// <param name="port">The remote port to connect to.</param>
public abstract void Negotiate(string host, int port);
/// <summary>
/// Starts negotiating with a SOCKS proxy server.
/// </summary>
/// <param name="remoteEP">The remote endpoint to connect to.</param>
public abstract void Negotiate(IPEndPoint remoteEP);
/// <summary>
/// Starts negotiating asynchronously with a SOCKS proxy server.
/// </summary>
/// <param name="remoteEP">An IPEndPoint that represents the remote device. </param>
/// <param name="callback">The method to call when the connection has been established.</param>
/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
public abstract IAsyncProxyResult BeginNegotiate(IPEndPoint remoteEP, HandShakeComplete callback, IPEndPoint proxyEndPoint);
/// <summary>
/// Starts negotiating asynchronously with a SOCKS proxy server.
/// </summary>
/// <param name="host">The remote server to connect to.</param>
/// <param name="port">The remote port to connect to.</param>
/// <param name="callback">The method to call when the connection has been established.</param>
/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
public abstract IAsyncProxyResult BeginNegotiate(string host, int port, HandShakeComplete callback, IPEndPoint proxyEndPoint);
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/SocksProxySocket/SocksHttpWebRequest.cs
0,0 → 1,413
using System;
using System.Collections.Generic;
using System.Text;
 
namespace GMap.NET.Internals
{
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Org.Mentalis.Network.ProxySocket; // http://www.mentalis.org/soft/class.qpx?id=9
 
/// <summary>
/// http://ditrans.blogspot.com/2009/03/making-witty-work-with-socks-proxy.html
/// </summary>
internal class SocksHttpWebRequest : WebRequest
{
#region Member Variables
 
private readonly Uri _requestUri;
private WebHeaderCollection _requestHeaders;
private string _method;
private SocksHttpWebResponse _response;
private string _requestMessage;
private byte[] _requestContentBuffer;
 
// darn MS for making everything internal (yeah, I'm talking about you, System.net.KnownHttpVerb)
static readonly StringCollection validHttpVerbs =
new StringCollection { "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "OPTIONS" };
 
#endregion
 
#region Constructor
 
private SocksHttpWebRequest(Uri requestUri)
{
_requestUri = requestUri;
}
 
#endregion
 
#region WebRequest Members
 
public override WebResponse GetResponse()
{
if (Proxy == null)
{
throw new InvalidOperationException("Proxy property cannot be null.");
}
if (String.IsNullOrEmpty(Method))
{
throw new InvalidOperationException("Method has not been set.");
}
 
if (RequestSubmitted)
{
return _response;
}
_response = InternalGetResponse();
RequestSubmitted = true;
return _response;
}
 
public override Uri RequestUri
{
get
{
return _requestUri;
}
}
 
public override IWebProxy Proxy
{
get;
set;
}
 
public override WebHeaderCollection Headers
{
get
{
if (_requestHeaders == null)
{
_requestHeaders = new WebHeaderCollection();
}
return _requestHeaders;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException("This operation cannot be performed after the request has been submitted.");
}
_requestHeaders = value;
}
}
 
public bool RequestSubmitted
{
get;
private set;
}
 
public override string Method
{
get
{
return _method ?? "GET";
}
set
{
if (validHttpVerbs.Contains(value))
{
_method = value;
}
else
{
throw new ArgumentOutOfRangeException("value", string.Format("'{0}' is not a known HTTP verb.", value));
}
}
}
 
public override long ContentLength
{
get;
set;
}
 
public override string ContentType
{
get;
set;
}
 
public override Stream GetRequestStream()
{
if (RequestSubmitted)
{
throw new InvalidOperationException("This operation cannot be performed after the request has been submitted.");
}
 
if (_requestContentBuffer == null)
{
_requestContentBuffer = new byte[ContentLength];
}
else if (ContentLength == default(long))
{
_requestContentBuffer = new byte[int.MaxValue];
}
else if (_requestContentBuffer.Length != ContentLength)
{
Array.Resize(ref _requestContentBuffer, (int)ContentLength);
}
return new MemoryStream(_requestContentBuffer);
}
 
#endregion
 
#region Methods
 
public static new WebRequest Create(string requestUri)
{
return new SocksHttpWebRequest(new Uri(requestUri));
}
 
public static new WebRequest Create(Uri requestUri)
{
return new SocksHttpWebRequest(requestUri);
}
 
private string BuildHttpRequestMessage()
{
if (RequestSubmitted)
{
throw new InvalidOperationException("This operation cannot be performed after the request has been submitted.");
}
 
var message = new StringBuilder();
 
message.AppendFormat("{0} {1} HTTP/1.0\r\nHost: {2}\r\n", Method, RequestUri.PathAndQuery, RequestUri.Host);
 
// add the headers
foreach (var key in Headers.Keys)
{
message.AppendFormat("{0}: {1}\r\n", key, Headers[key.ToString()]);
}
 
if (!string.IsNullOrEmpty(ContentType))
{
message.AppendFormat("Content-Type: {0}\r\n", ContentType);
}
if (ContentLength > 0)
{
message.AppendFormat("Content-Length: {0}\r\n", ContentLength);
}
 
// add a blank line to indicate the end of the headers
message.Append("\r\n");
 
// add content
if (_requestContentBuffer != null && _requestContentBuffer.Length > 0)
{
using (var stream = new MemoryStream(_requestContentBuffer, false))
{
using (var reader = new StreamReader(stream))
{
message.Append(reader.ReadToEnd());
}
}
}
 
return message.ToString();
}
 
private SocksHttpWebResponse InternalGetResponse()
{
MemoryStream data = null;
string header = string.Empty;
 
using (var _socksConnection = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
var proxyUri = Proxy.GetProxy(RequestUri);
var ipAddress = GetProxyIpAddress(proxyUri);
_socksConnection.ProxyEndPoint = new IPEndPoint(ipAddress, proxyUri.Port);
_socksConnection.ProxyType = ProxyTypes.Socks5;
 
// open connection
_socksConnection.Connect(RequestUri.Host, 80);
 
// send an HTTP request
_socksConnection.Send(Encoding.UTF8.GetBytes(RequestMessage));
 
// read the HTTP reply
var buffer = new byte[1024 * 4];
int bytesReceived = 0;
bool headerDone = false;
 
while ((bytesReceived = _socksConnection.Receive(buffer)) > 0)
{
if (!headerDone)
{
var headPart = Encoding.UTF8.GetString(buffer, 0, bytesReceived > 1024 ? 1024 : bytesReceived);
var indexOfFirstBlankLine = headPart.IndexOf("\r\n\r\n");
if (indexOfFirstBlankLine > 0)
{
headPart = headPart.Substring(0, indexOfFirstBlankLine);
header += headPart;
headerDone = true;
 
var headerPartLength = Encoding.UTF8.GetByteCount(headPart) + 4;
 
// 0123456789
// ----
if (headerPartLength < bytesReceived)
{
data = new MemoryStream();
data.Write(buffer, headerPartLength, bytesReceived - headerPartLength);
}
}
else
{
header += headPart;
}
}
else
{
if (data == null)
{
data = new MemoryStream();
}
data.Write(buffer, 0, bytesReceived);
}
}
 
if (data != null)
{
data.Position = 0;
}
}
 
return new SocksHttpWebResponse(data, header);
}
 
private static IPAddress GetProxyIpAddress(Uri proxyUri)
{
IPAddress ipAddress;
if (!IPAddress.TryParse(proxyUri.Host, out ipAddress))
{
try
{
return Dns.GetHostEntry(proxyUri.Host).AddressList[0];
}
catch (Exception e)
{
throw new InvalidOperationException(
string.Format("Unable to resolve proxy hostname '{0}' to a valid IP address.", proxyUri.Host), e);
}
}
return ipAddress;
}
 
#endregion
 
#region Properties
 
public string RequestMessage
{
get
{
if (string.IsNullOrEmpty(_requestMessage))
{
_requestMessage = BuildHttpRequestMessage();
}
return _requestMessage;
}
}
 
#endregion
 
}
 
internal class SocksHttpWebResponse : WebResponse
{
 
#region Member Variables
 
WebHeaderCollection _httpResponseHeaders;
MemoryStream data;
 
public override long ContentLength
{
get;
set;
}
 
public override string ContentType
{
get;
set;
}
 
#endregion
 
#region Constructors
 
public SocksHttpWebResponse(MemoryStream data, string headers)
{
this.data = data;
 
var headerValues = headers.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
 
// ignore the first line in the header since it is the HTTP response code
for (int i = 1; i < headerValues.Length; i++)
{
var headerEntry = headerValues[i].Split(new[] { ':' });
Headers.Add(headerEntry[0], headerEntry[1]);
 
switch (headerEntry[0])
{
case "Content-Type":
{
ContentType = headerEntry[1];
}
break;
 
case "Content-Length":
{
long r = 0;
if(long.TryParse(headerEntry[1], out r))
{
ContentLength = r;
}
}
break;
}
}
}
 
#endregion
 
#region WebResponse Members
 
public override Stream GetResponseStream()
{
return data != null ? data : Stream.Null;
}
 
public override void Close()
{
if (data != null)
{
data.Close();
}
/* the base implementation throws an exception */
}
 
public override WebHeaderCollection Headers
{
get
{
if (_httpResponseHeaders == null)
{
_httpResponseHeaders = new WebHeaderCollection();
}
return _httpResponseHeaders;
}
}
 
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/Stuff.cs
0,0 → 1,254

namespace GMap.NET.Internals
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
 
/// <summary>
/// etc functions...
/// </summary>
internal class Stuff
{
public static string EnumToString(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
 
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}
 
[System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "SetCursorPos")]
[return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern bool SetCursorPos(int X, int Y);
 
public static readonly Random random = new System.Random();
 
public static void Shuffle<T>(List<T> deck)
{
int N = deck.Count;
 
for(int i = 0; i < N; ++i)
{
int r = i + (int)(random.Next(N - i));
T t = deck[r];
deck[r] = deck[i];
deck[i] = t;
}
}
 
public static MemoryStream CopyStream(Stream inputStream, bool SeekOriginBegin)
{
const int readSize = 32 * 1024;
byte[] buffer = new byte[readSize];
MemoryStream ms = new MemoryStream();
{
int count = 0;
while((count = inputStream.Read(buffer, 0, readSize)) > 0)
{
ms.Write(buffer, 0, count);
}
}
buffer = null;
if(SeekOriginBegin)
{
inputStream.Seek(0, SeekOrigin.Begin);
}
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
 
public static bool IsRunningOnVistaOrLater()
{
OperatingSystem os = Environment.OSVersion;
 
if(os.Platform == PlatformID.Win32NT)
{
Version vs = os.Version;
 
if(vs.Major >= 6 && vs.Minor >= 0)
{
return true;
}
}
 
return false;
}
 
public static bool IsRunningOnWin7orLater()
{
OperatingSystem os = Environment.OSVersion;
 
if(os.Platform == PlatformID.Win32NT)
{
Version vs = os.Version;
 
if(vs.Major >= 6 && vs.Minor > 0)
{
return true;
}
}
 
return false;
}
 
public static void RemoveInvalidPathSymbols(ref string url)
{
#if !PocketPC
char[] ilg = Path.GetInvalidFileNameChars();
#else
char[] ilg = new char[41];
for(int i = 0; i < 32; i++)
ilg[i] = (char) i;
 
ilg[32] = '"';
ilg[33] = '<';
ilg[34] = '>';
ilg[35] = '|';
ilg[36] = '?';
ilg[37] = ':';
ilg[38] = '/';
ilg[39] = '\\';
ilg[39] = '*';
#endif
foreach(char c in ilg)
{
url = url.Replace(c, '_');
}
}
 
#region -- encryption --
static string EncryptString(string Message, string Passphrase)
{
byte[] Results;
 
using (var HashProvider = new SHA1CryptoServiceProvider())
{
byte[] TDESKey = HashProvider.ComputeHash(Encoding.UTF8.GetBytes(Passphrase));
Array.Resize(ref TDESKey, 16);
 
using (TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider())
{
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
 
byte[] DataToEncrypt = Encoding.UTF8.GetBytes(Message);
 
// Step 5. Attempt to encrypt the string
try
{
using (ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor())
{
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
}
finally
{
// Clear the TripleDes and Hashprovider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
 
// Step 6. Return the encrypted string as a base64 encoded string
return Convert.ToBase64String(Results);
}
 
static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
 
using (var HashProvider = new SHA1CryptoServiceProvider())
{
byte[] TDESKey = HashProvider.ComputeHash(Encoding.UTF8.GetBytes(Passphrase));
Array.Resize(ref TDESKey, 16);
 
// Step 2. Create a new TripleDESCryptoServiceProvider object
using (TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider())
{
// Step 3. Setup the decoder
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
 
// Step 4. Convert the input string to a byte[]
byte[] DataToDecrypt = Convert.FromBase64String(Message);
 
// Step 5. Attempt to decrypt the string
try
{
using (ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor())
{
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
}
finally
{
// Clear the TripleDes and Hashprovider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
 
// Step 6. Return the decrypted string in UTF8 format
return Encoding.UTF8.GetString(Results, 0, Results.Length);
}
 
public static string EncryptString(string Message)
{
return EncryptString(Message, manifesto);
}
 
public static string GString(string Message)
{
var ret = DecryptString(Message, manifesto);
 
return ret;
}
 
static readonly string manifesto = "GMap.NET is great and Powerful, Free, cross platform, open source .NET control.";
#endregion
}
 
#if PocketPC
static class Monitor
{
static readonly OpenNETCF.Threading.Monitor2 wait = new OpenNETCF.Threading.Monitor2();
 
public static void Enter(Stack<LoadTask> tileLoadQueue)
{
wait.Enter();
}
 
public static void Exit(Stack<LoadTask> tileLoadQueue)
{
wait.Exit();
}
 
public static void Wait(Stack<LoadTask> tileLoadQueue)
{
wait.Wait();
}
 
public static bool Wait(Stack<LoadTask> tileLoadQueue, int WaitForTileLoadThreadTimeout, bool p)
{
wait.Wait();
return true;
}
 
internal static void PulseAll(Stack<LoadTask> tileLoadQueue)
{
wait.PulseAll();
}
}
#endif
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/Tile.cs
0,0 → 1,147

namespace GMap.NET.Internals
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
 
/// <summary>
/// represent tile
/// </summary>
public struct Tile : IDisposable
{
public static readonly Tile Empty = new Tile();
 
GPoint pos;
int zoom;
PureImage[] overlays;
long OverlaysCount;
 
public readonly bool NotEmpty;
 
public Tile(int zoom, GPoint pos)
{
this.NotEmpty = true;
this.zoom = zoom;
this.pos = pos;
this.overlays = null;
this.OverlaysCount = 0;
}
 
public IEnumerable<PureImage> Overlays
{
get
{
#if PocketPC
for (long i = 0, size = OverlaysCount; i < size; i++)
#else
for (long i = 0, size = Interlocked.Read(ref OverlaysCount); i < size; i++)
#endif
{
yield return overlays[i];
}
}
}
 
internal void AddOverlay(PureImage i)
{
if (overlays == null)
{
overlays = new PureImage[4];
}
#if !PocketPC
overlays[Interlocked.Increment(ref OverlaysCount) - 1] = i;
#else
overlays[++OverlaysCount - 1] = i;
#endif
}
 
internal bool HasAnyOverlays
{
get
{
#if PocketPC
return OverlaysCount > 0;
#else
return Interlocked.Read(ref OverlaysCount) > 0;
#endif
}
}
 
public int Zoom
{
get
{
return zoom;
}
private set
{
zoom = value;
}
}
 
public GPoint Pos
{
get
{
return pos;
}
private set
{
pos = value;
}
}
 
#region IDisposable Members
 
public void Dispose()
{
if (overlays != null)
{
#if PocketPC
for (long i = OverlaysCount - 1; i >= 0; i--)
 
#else
for (long i = Interlocked.Read(ref OverlaysCount) - 1; i >= 0; i--)
#endif
{
#if !PocketPC
Interlocked.Decrement(ref OverlaysCount);
#else
OverlaysCount--;
#endif
overlays[i].Dispose();
overlays[i] = null;
}
overlays = null;
}
}
 
#endregion
 
public static bool operator ==(Tile m1, Tile m2)
{
return m1.pos == m2.pos && m1.zoom == m2.zoom;
}
 
public static bool operator !=(Tile m1, Tile m2)
{
return !(m1 == m2);
}
 
public override bool Equals(object obj)
{
if (!(obj is Tile))
return false;
 
Tile comp = (Tile)obj;
return comp.Zoom == this.Zoom && comp.Pos == this.Pos;
}
 
public override int GetHashCode()
{
return zoom ^ pos.GetHashCode();
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/TileHttpHost.cs
0,0 → 1,157
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
using System.IO;
using GMap.NET.MapProviders;
 
namespace GMap.NET.Internals
{
internal class TileHttpHost
{
volatile bool listen = false;
TcpListener server;
int port;
 
readonly byte[] responseHeaderBytes;
 
public TileHttpHost()
{
string response = "HTTP/1.0 200 OK\r\nContent-Type: image\r\nConnection: close\r\n\r\n";
responseHeaderBytes = Encoding.ASCII.GetBytes(response);
}
 
public void Stop()
{
if (listen)
{
listen = false;
if (server != null)
{
server.Stop();
}
}
}
 
public void Start(int port)
{
if (server == null)
{
this.port = port;
server = new TcpListener(IPAddress.Any, port);
}
else
{
if (this.port != port)
{
Stop();
this.port = port;
server = null;
server = new TcpListener(IPAddress.Any, port);
}
else
{
if (listen)
{
return;
}
}
}
 
server.Start();
listen = true;
 
Thread t = new Thread(() =>
{
Debug.WriteLine("TileHttpHost: " + server.LocalEndpoint);
 
while (listen)
{
try
{
if (!server.Pending())
{
Thread.Sleep(111);
}
else
{
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessRequest), server.AcceptTcpClient());
}
}
catch (Exception ex)
{
Debug.WriteLine("TileHttpHost: " + ex);
}
}
 
Debug.WriteLine("TileHttpHost: stoped");
});
 
t.Name = "TileHost";
t.IsBackground = true;
t.Start();
}
 
void ProcessRequest(object p)
{
try
{
using(TcpClient c = p as TcpClient)
{
using(var s = c.GetStream())
{
using(StreamReader r = new StreamReader(s, Encoding.UTF8))
{
var request = r.ReadLine();
 
if(!string.IsNullOrEmpty(request) && request.StartsWith("GET"))
{
//Debug.WriteLine("TileHttpHost: " + request);
 
// http://localhost:88/88888/5/15/11
// GET /8888888888/5/15/11 HTTP/1.1
 
var rq = request.Split(' ');
if(rq.Length >= 2)
{
var ids = rq[1].Split(new char[]{'/'}, StringSplitOptions.RemoveEmptyEntries);
if(ids.Length == 4)
{
int dbId = int.Parse(ids[0]);
int zoom = int.Parse(ids[1]);
int x = int.Parse(ids[2]);
int y = int.Parse(ids[3]);
 
var pr = GMapProviders.TryGetProvider(dbId);
if(pr != null)
{
Exception ex;
var img = GMaps.Instance.GetImageFrom(pr, new GPoint(x, y), zoom, out ex);
if (img != null)
{
using (img)
{
s.Write(responseHeaderBytes, 0, responseHeaderBytes.Length);
img.Data.WriteTo(s);
}
}
}
}
}
}
}
}
c.Close();
}
}
catch (Exception ex)
{
Debug.WriteLine("TileHttpHost, ProcessRequest: " + ex);
}
//Debug.WriteLine("disconnected");
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Internals/TileMatrix.cs
0,0 → 1,246

namespace GMap.NET.Internals
{
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
using System;
 
/// <summary>
/// matrix for tiles
/// </summary>
internal class TileMatrix : IDisposable
{
List<Dictionary<GPoint, Tile>> Levels = new List<Dictionary<GPoint, Tile>>(33);
FastReaderWriterLock Lock = new FastReaderWriterLock();
 
public TileMatrix()
{
for(int i = 0; i < Levels.Capacity; i++)
{
Levels.Add(new Dictionary<GPoint, Tile>(55, new GPointComparer()));
}
}
 
public void ClearAllLevels()
{
Lock.AcquireWriterLock();
try
{
foreach(var matrix in Levels)
{
foreach(var t in matrix)
{
t.Value.Dispose();
}
matrix.Clear();
}
}
finally
{
Lock.ReleaseWriterLock();
}
}
 
public void ClearLevel(int zoom)
{
Lock.AcquireWriterLock();
try
{
if(zoom < Levels.Count)
{
var l = Levels[zoom];
 
foreach(var t in l)
{
t.Value.Dispose();
}
 
l.Clear();
}
}
finally
{
Lock.ReleaseWriterLock();
}
}
 
List<KeyValuePair<GPoint, Tile>> tmp = new List<KeyValuePair<GPoint, Tile>>(44);
 
public void ClearLevelAndPointsNotIn(int zoom, List<DrawTile> list)
{
Lock.AcquireWriterLock();
try
{
if(zoom < Levels.Count)
{
var l = Levels[zoom];
 
tmp.Clear();
 
foreach(var t in l)
{
if(!list.Exists(p => p.PosXY == t.Key))
{
tmp.Add(t);
}
}
 
foreach(var r in tmp)
{
l.Remove(r.Key);
r.Value.Dispose();
}
 
tmp.Clear();
}
}
finally
{
Lock.ReleaseWriterLock();
}
}
 
public void ClearLevelsBelove(int zoom)
{
Lock.AcquireWriterLock();
try
{
if(zoom - 1 < Levels.Count)
{
for(int i = zoom - 1; i >= 0; i--)
{
var l = Levels[i];
 
foreach(var t in l)
{
t.Value.Dispose();
}
 
l.Clear();
}
}
}
finally
{
Lock.ReleaseWriterLock();
}
}
 
public void ClearLevelsAbove(int zoom)
{
Lock.AcquireWriterLock();
try
{
if(zoom + 1 < Levels.Count)
{
for(int i = zoom + 1; i < Levels.Count; i++)
{
var l = Levels[i];
 
foreach(var t in l)
{
t.Value.Dispose();
}
 
l.Clear();
}
}
}
finally
{
Lock.ReleaseWriterLock();
}
}
 
public void EnterReadLock()
{
Lock.AcquireReaderLock();
}
 
public void LeaveReadLock()
{
Lock.ReleaseReaderLock();
}
 
public Tile GetTileWithNoLock(int zoom, GPoint p)
{
Tile ret = Tile.Empty;
 
//if(zoom < Levels.Count)
{
Levels[zoom].TryGetValue(p, out ret);
}
 
return ret;
}
 
public Tile GetTileWithReadLock(int zoom, GPoint p)
{
Tile ret = Tile.Empty;
 
Lock.AcquireReaderLock();
try
{
ret = GetTileWithNoLock(zoom, p);
}
finally
{
Lock.ReleaseReaderLock();
}
 
return ret;
}
 
public void SetTile(Tile t)
{
Lock.AcquireWriterLock();
try
{
if(t.Zoom < Levels.Count)
{
Levels[t.Zoom][t.Pos] = t;
}
}
finally
{
Lock.ReleaseWriterLock();
}
}
 
#region IDisposable Members
 
~TileMatrix()
{
Dispose(false);
}
 
void Dispose(bool disposing)
{
if(Lock != null)
{
if(disposing)
{
ClearAllLevels();
}
 
Levels.Clear();
Levels = null;
 
tmp.Clear();
tmp = null;
 
Lock.Dispose();
Lock = null;
}
}
 
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
 
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/ArcGIS/ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_MapProvider.cs
0,0 → 1,86

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
/// <summary>
/// ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_Map provider,
/// http://www.darb.ae/ArcGIS/rest/services/BaseMaps/Q2_2011_NAVTQ_Eng_V5/MapServer
/// </summary>
public class ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_MapProvider : GMapProvider
{
public static readonly ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_MapProvider Instance;
 
ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_MapProvider()
{
MaxZoom = 12;
Area = RectLatLng.FromLTRB(49.8846923723311, 28.0188609585523, 58.2247031977662, 21.154115956732);
Copyright = string.Format("©{0} ESRI - Map data ©{0} ArcGIS", DateTime.Today.Year);
}
 
static ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_MapProvider()
{
Instance = new ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_MapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("E03CFEDF-9277-49B3-9912-D805347F934B");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_MapProvider";
public override string Name
{
get
{
return name;
}
}
 
public override PureProjection Projection
{
get
{
return PlateCarreeProjectionDarbAe.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom)
{
// http://www.darb.ae/ArcGIS/rest/services/BaseMaps/Q2_2011_NAVTQ_Eng_V5/MapServer/tile/0/121/144
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://www.darb.ae/ArcGIS/rest/services/BaseMaps/Q2_2011_NAVTQ_Eng_V5/MapServer/tile/{0}/{1}/{2}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/ArcGIS/ArcGIS_Imagery_World_2D_MapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// ArcGIS_Imagery_World_2D_Map provider, http://server.arcgisonline.com
/// </summary>
public class ArcGIS_Imagery_World_2D_MapProvider : ArcGISMapPlateCarreeProviderBase
{
public static readonly ArcGIS_Imagery_World_2D_MapProvider Instance;
 
ArcGIS_Imagery_World_2D_MapProvider()
{
}
 
static ArcGIS_Imagery_World_2D_MapProvider()
{
Instance = new ArcGIS_Imagery_World_2D_MapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("FF7ADDAD-F155-41DB-BC42-CC6FD97C8B9D");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "ArcGIS_Imagery_World_2D_Map";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_Imagery_World_2D/MapServer/tile/1/0/1.jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_Imagery_World_2D/MapServer/tile/{0}/{1}/{2}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/ArcGIS/ArcGIS_ShadedRelief_World_2D_MapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// ArcGIS_ShadedRelief_World_2D_Map provider, http://server.arcgisonline.com
/// </summary>
public class ArcGIS_ShadedRelief_World_2D_MapProvider : ArcGISMapPlateCarreeProviderBase
{
public static readonly ArcGIS_ShadedRelief_World_2D_MapProvider Instance;
 
ArcGIS_ShadedRelief_World_2D_MapProvider()
{
}
 
static ArcGIS_ShadedRelief_World_2D_MapProvider()
{
Instance = new ArcGIS_ShadedRelief_World_2D_MapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("A8995FA4-D9D8-415B-87D0-51A7E53A90D4");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "ArcGIS_ShadedRelief_World_2D_Map";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_ShadedRelief_World_2D/MapServer/tile/1/0/1.jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_ShadedRelief_World_2D/MapServer/tile/{0}/{1}/{2}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/ArcGIS/ArcGIS_StreetMap_World_2D_MapProvider.cs
0,0 → 1,166

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
public abstract class ArcGISMapPlateCarreeProviderBase : GMapProvider
{
public ArcGISMapPlateCarreeProviderBase()
{
Copyright = string.Format("©{0} ESRI - Map data ©{0} ArcGIS", DateTime.Today.Year);
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return PlateCarreeProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
}
 
public abstract class ArcGISMapMercatorProviderBase : GMapProvider
{
public ArcGISMapMercatorProviderBase()
{
MaxZoom = null;
Copyright = string.Format("©{0} ESRI - Map data ©{0} ArcGIS", DateTime.Today.Year);
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
}
 
/// <summary>
/// ArcGIS_StreetMap_World_2D_Map provider, http://server.arcgisonline.com
/// </summary>
public class ArcGIS_StreetMap_World_2D_MapProvider : ArcGISMapPlateCarreeProviderBase
{
public static readonly ArcGIS_StreetMap_World_2D_MapProvider Instance;
 
ArcGIS_StreetMap_World_2D_MapProvider()
{
}
 
static ArcGIS_StreetMap_World_2D_MapProvider()
{
Instance = new ArcGIS_StreetMap_World_2D_MapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("00BF56D4-4B48-4939-9B11-575BBBE4A718");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "ArcGIS_StreetMap_World_2D_Map";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapServer/tile/0/0/0.jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapServer/tile/{0}/{1}/{2}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/ArcGIS/ArcGIS_Topo_US_2D_MapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// ArcGIS_Topo_US_2D_Map provider, http://server.arcgisonline.com
/// </summary>
public class ArcGIS_Topo_US_2D_MapProvider : ArcGISMapPlateCarreeProviderBase
{
public static readonly ArcGIS_Topo_US_2D_MapProvider Instance;
 
ArcGIS_Topo_US_2D_MapProvider()
{
}
 
static ArcGIS_Topo_US_2D_MapProvider()
{
Instance = new ArcGIS_Topo_US_2D_MapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("7652CC72-5C92-40F5-B572-B8FEAA728F6D");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "ArcGIS_Topo_US_2D_Map";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://server.arcgisonline.com/ArcGIS/rest/services/NGS_Topo_US_2D/MapServer/tile/4/3/15
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://server.arcgisonline.com/ArcGIS/rest/services/NGS_Topo_US_2D/MapServer/tile/{0}/{1}/{2}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/ArcGIS/ArcGIS_World_Physical_MapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// ArcGIS_World_Physical_Map provider, http://server.arcgisonline.com
/// </summary>
public class ArcGIS_World_Physical_MapProvider : ArcGISMapMercatorProviderBase
{
public static readonly ArcGIS_World_Physical_MapProvider Instance;
 
ArcGIS_World_Physical_MapProvider()
{
}
 
static ArcGIS_World_Physical_MapProvider()
{
Instance = new ArcGIS_World_Physical_MapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("0C0E73E3-5EA6-4F08-901C-AE85BCB1BFC8");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "ArcGIS_World_Physical_Map";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://services.arcgisonline.com/ArcGIS/rest/services/World_Physical_Map/MapServer/tile/2/0/2.jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Physical_Map/MapServer/tile/{0}/{1}/{2}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/ArcGIS/ArcGIS_World_Shaded_Relief_MapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// ArcGIS_World_Shaded_Relief_Map provider, http://server.arcgisonline.com
/// </summary>
public class ArcGIS_World_Shaded_Relief_MapProvider : ArcGISMapMercatorProviderBase
{
public static readonly ArcGIS_World_Shaded_Relief_MapProvider Instance;
 
ArcGIS_World_Shaded_Relief_MapProvider()
{
}
 
static ArcGIS_World_Shaded_Relief_MapProvider()
{
Instance = new ArcGIS_World_Shaded_Relief_MapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("2E821FEF-8EA1-458A-BC82-4F699F4DEE79");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "ArcGIS_World_Shaded_Relief_Map";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://services.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/0/0/0jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{0}/{1}/{2}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/ArcGIS/ArcGIS_World_Street_MapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// ArcGIS_World_Street_Map provider, http://server.arcgisonline.com
/// </summary>
public class ArcGIS_World_Street_MapProvider : ArcGISMapMercatorProviderBase
{
public static readonly ArcGIS_World_Street_MapProvider Instance;
 
ArcGIS_World_Street_MapProvider()
{
}
 
static ArcGIS_World_Street_MapProvider()
{
Instance = new ArcGIS_World_Street_MapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("E1FACDF6-E535-4D69-A49F-12B623A467A9");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "ArcGIS_World_Street_Map";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/0/0/0jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{0}/{1}/{2}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/ArcGIS/ArcGIS_World_Terrain_Base_MapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// ArcGIS_World_Terrain_Base_Map provider, http://server.arcgisonline.com
/// </summary>
public class ArcGIS_World_Terrain_Base_MapProvider : ArcGISMapMercatorProviderBase
{
public static readonly ArcGIS_World_Terrain_Base_MapProvider Instance;
 
ArcGIS_World_Terrain_Base_MapProvider()
{
}
 
static ArcGIS_World_Terrain_Base_MapProvider()
{
Instance = new ArcGIS_World_Terrain_Base_MapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("927F175B-5200-4D95-A99B-1C87C93099DA");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "ArcGIS_World_Terrain_Base_Map";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://services.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer/tile/0/0/0jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer/tile/{0}/{1}/{2}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/ArcGIS/ArcGIS_World_Topo_MapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// ArcGIS_World_Topo_Map provider, http://server.arcgisonline.com
/// </summary>
public class ArcGIS_World_Topo_MapProvider : ArcGISMapMercatorProviderBase
{
public static readonly ArcGIS_World_Topo_MapProvider Instance;
 
ArcGIS_World_Topo_MapProvider()
{
}
 
static ArcGIS_World_Topo_MapProvider()
{
Instance = new ArcGIS_World_Topo_MapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("E0354A49-7447-4C9A-814F-A68565ED834B");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "ArcGIS_World_Topo_Map";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/0/0/0jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{0}/{1}/{2}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Bing/BingHybridMapProvider.cs
0,0 → 1,85

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// BingHybridMap provider
/// </summary>
public class BingHybridMapProvider : BingMapProviderBase
{
public static readonly BingHybridMapProvider Instance;
 
BingHybridMapProvider()
{
}
 
static BingHybridMapProvider()
{
Instance = new BingHybridMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("94E2FCB4-CAAC-45EA-A1F9-8147C4B14970");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "BingHybridMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
public override void OnInitialized()
{
base.OnInitialized();
 
if(!DisableDynamicTileUrlFormat)
{
//UrlFormat[AerialWithLabels]: http://ecn.{subdomain}.tiles.virtualearth.net/tiles/h{quadkey}.jpeg?g=3179&mkt={culture}
 
UrlDynamicFormat = GetTileUrl("AerialWithLabels");
if(!string.IsNullOrEmpty(UrlDynamicFormat))
{
UrlDynamicFormat = UrlDynamicFormat.Replace("{subdomain}", "t{0}").Replace("{quadkey}", "{1}").Replace("{culture}", "{2}");
}
}
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string key = TileXYToQuadKey(pos.X, pos.Y, zoom);
 
if(!DisableDynamicTileUrlFormat && !string.IsNullOrEmpty(UrlDynamicFormat))
{
return string.Format(UrlDynamicFormat, GetServerNum(pos, 4), key, language);
}
 
return string.Format(UrlFormat, GetServerNum(pos, 4), key, Version, language, ForceSessionIdOnTileAccess ? "&key=" + SessionId : string.Empty);
}
 
string UrlDynamicFormat = string.Empty;
 
// http://ecn.dynamic.t3.tiles.virtualearth.net/comp/CompositionHandler/12030012020203?mkt=en-us&it=A,G,L&n=z
 
static readonly string UrlFormat = "http://ecn.t{0}.tiles.virtualearth.net/tiles/h{1}.jpeg?g={2}&mkt={3}&n=z{4}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Bing/BingMapProvider.cs
0,0 → 1,779

namespace GMap.NET.MapProviders
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using GMap.NET.Internals;
using GMap.NET.Projections;
 
public abstract class BingMapProviderBase : GMapProvider, RoutingProvider, GeocodingProvider
{
public BingMapProviderBase()
{
MaxZoom = null;
RefererUrl = "http://www.bing.com/maps/";
Copyright = string.Format("©{0} Microsoft Corporation, ©{0} NAVTEQ, ©{0} Image courtesy of NASA", DateTime.Today.Year);
}
 
public string Version = "4810";
 
/// <summary>
/// Bing Maps Customer Identification.
/// |
/// FOR LEGAL AND COMMERCIAL USAGE SET YOUR OWN REGISTERED KEY
/// |
/// http://msdn.microsoft.com/en-us/library/ff428642.aspx
/// </summary>
public string ClientKey = string.Empty;
 
internal string SessionId = string.Empty;
 
/// <summary>
/// set true to append SessionId on requesting tiles
/// </summary>
public bool ForceSessionIdOnTileAccess = false;
 
/// <summary>
/// set true to avoid using dynamic tile url format
/// </summary>
public bool DisableDynamicTileUrlFormat = false;
 
/// <summary>
/// Converts tile XY coordinates into a QuadKey at a specified level of detail.
/// </summary>
/// <param name="tileX">Tile X coordinate.</param>
/// <param name="tileY">Tile Y coordinate.</param>
/// <param name="levelOfDetail">Level of detail, from 1 (lowest detail)
/// to 23 (highest detail).</param>
/// <returns>A string containing the QuadKey.</returns>
internal string TileXYToQuadKey(long tileX, long tileY, int levelOfDetail)
{
StringBuilder quadKey = new StringBuilder();
for(int i = levelOfDetail; i > 0; i--)
{
char digit = '0';
int mask = 1 << (i - 1);
if((tileX & mask) != 0)
{
digit++;
}
if((tileY & mask) != 0)
{
digit++;
digit++;
}
quadKey.Append(digit);
}
return quadKey.ToString();
}
 
/// <summary>
/// Converts a QuadKey into tile XY coordinates.
/// </summary>
/// <param name="quadKey">QuadKey of the tile.</param>
/// <param name="tileX">Output parameter receiving the tile X coordinate.</param>
/// <param name="tileY">Output parameter receiving the tile Y coordinate.</param>
/// <param name="levelOfDetail">Output parameter receiving the level of detail.</param>
internal void QuadKeyToTileXY(string quadKey, out int tileX, out int tileY, out int levelOfDetail)
{
tileX = tileY = 0;
levelOfDetail = quadKey.Length;
for(int i = levelOfDetail; i > 0; i--)
{
int mask = 1 << (i - 1);
switch(quadKey[levelOfDetail - i])
{
case '0':
break;
 
case '1':
tileX |= mask;
break;
 
case '2':
tileY |= mask;
break;
 
case '3':
tileX |= mask;
tileY |= mask;
break;
 
default:
throw new ArgumentException("Invalid QuadKey digit sequence.");
}
}
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
 
public bool TryCorrectVersion = true;
 
/// <summary>
/// set false to use your own key.
/// FOR LEGAL AND COMMERCIAL USAGE SET YOUR OWN REGISTERED KEY
/// http://msdn.microsoft.com/en-us/library/ff428642.aspx
/// </summary>
public bool TryGetDefaultKey = true;
static bool init = false;
 
public override void OnInitialized()
{
if(!init)
{
try
{
var key = ClientKey;
 
// to avoid registration stuff, default key
if(TryGetDefaultKey && string.IsNullOrEmpty(ClientKey))
{
//old: Vx8dmDflxzT02jJUG8bEjMU07Xr9QWRpPTeRuAZTC1uZFQdDCvK/jUbHKdyHEWj4LvccTPoKofDHtzHsWu/0xuo5u2Y9rj88
key = Stuff.GString("Jq7FrGTyaYqcrvv9ugBKv4OVSKnmzpigqZtdvtcDdgZexmOZ2RugOexFSmVzTAhOWiHrdhFoNCoySnNF3MyyIOo5u2Y9rj88");
}
 
#region -- try get sesion key --
if(!string.IsNullOrEmpty(key))
{
string keyResponse = GMaps.Instance.UseUrlCache ? Cache.Instance.GetContent("BingLoggingServiceV1" + key, CacheType.UrlCache, TimeSpan.FromHours(8)) : string.Empty;
 
if(string.IsNullOrEmpty(keyResponse))
{
// Bing Maps WPF Control
// http://dev.virtualearth.net/webservices/v1/LoggingService/LoggingService.svc/Log?entry=0&auth={0}&fmt=1&type=3&group=MapControl&name=WPF&version=1.0.0.0&session=00000000-0000-0000-0000-000000000000&mkt=en-US
 
keyResponse = GetContentUsingHttp(string.Format("http://dev.virtualearth.net/webservices/v1/LoggingService/LoggingService.svc/Log?entry=0&fmt=1&type=3&group=MapControl&name=AJAX&mkt=en-us&auth={0}&jsonp=microsoftMapsNetworkCallback", key));
 
if(!string.IsNullOrEmpty(keyResponse) && keyResponse.Contains("ValidCredentials"))
{
if(GMaps.Instance.UseUrlCache)
{
Cache.Instance.SaveContent("BingLoggingServiceV1" + key, CacheType.UrlCache, keyResponse);
}
}
}
 
if(!string.IsNullOrEmpty(keyResponse) && keyResponse.Contains("sessionId") && keyResponse.Contains("ValidCredentials"))
{
// microsoftMapsNetworkCallback({"sessionId" : "xxx", "authenticationResultCode" : "ValidCredentials"})
 
SessionId = keyResponse.Split(',')[0].Split(':')[1].Replace("\"", string.Empty).Replace(" ", string.Empty);
Debug.WriteLine("GMapProviders.BingMap.SessionId: " + SessionId);
}
else
{
Debug.WriteLine("BingLoggingServiceV1: " + keyResponse);
}
}
#endregion
 
// supporting old road
if(TryCorrectVersion && DisableDynamicTileUrlFormat)
{
#region -- get the version --
string url = @"http://www.bing.com/maps";
string html = GMaps.Instance.UseUrlCache ? Cache.Instance.GetContent(url, CacheType.UrlCache, TimeSpan.FromDays(7)) : string.Empty;
 
if(string.IsNullOrEmpty(html))
{
html = GetContentUsingHttp(url);
if(!string.IsNullOrEmpty(html))
{
if(GMaps.Instance.UseUrlCache)
{
Cache.Instance.SaveContent(url, CacheType.UrlCache, html);
}
}
}
 
if(!string.IsNullOrEmpty(html))
{
#region -- match versions --
 
Regex reg = new Regex("tilegeneration:(\\d*)", RegexOptions.IgnoreCase);
Match mat = reg.Match(html);
if(mat.Success)
{
GroupCollection gc = mat.Groups;
int count = gc.Count;
if(count == 2)
{
string ver = gc[1].Value;
string old = GMapProviders.BingMap.Version;
if(ver != old)
{
GMapProviders.BingMap.Version = ver;
GMapProviders.BingSatelliteMap.Version = ver;
GMapProviders.BingHybridMap.Version = ver;
#if DEBUG
Debug.WriteLine("GMapProviders.BingMap.Version: " + ver + ", old: " + old + ", consider updating source");
if(Debugger.IsAttached)
{
Thread.Sleep(5555);
}
#endif
}
else
{
Debug.WriteLine("GMapProviders.BingMap.Version: " + ver + ", OK");
}
}
}
#endregion
}
#endregion
}
 
init = true; // try it only once
}
catch(Exception ex)
{
Debug.WriteLine("TryCorrectBingVersions failed: " + ex);
}
}
}
 
protected override bool CheckTileImageHttpResponse(WebResponse response)
{
var pass = base.CheckTileImageHttpResponse(response);
if(pass)
{
var tileInfo = response.Headers.Get("X-VE-Tile-Info");
if(tileInfo != null)
{
return !tileInfo.Equals("no-tile");
}
}
return pass;
}
 
internal string GetTileUrl(string imageryType)
{
//Retrieve map tile URL from the Imagery Metadata service: http://msdn.microsoft.com/en-us/library/ff701716.aspx
//This ensures that the current tile URL is always used.
//This will prevent the app from breaking when the map tiles change.
 
string ret = string.Empty;
if(!string.IsNullOrEmpty(SessionId))
{
try
{
string url = "http://dev.virtualearth.net/REST/V1/Imagery/Metadata/" + imageryType + "?output=xml&key=" + SessionId;
 
string r = GMaps.Instance.UseUrlCache ? Cache.Instance.GetContent("GetTileUrl" + imageryType, CacheType.UrlCache, TimeSpan.FromDays(7)) : string.Empty;
bool cache = false;
 
if(string.IsNullOrEmpty(r))
{
r = GetContentUsingHttp(url);
cache = true;
}
 
if(!string.IsNullOrEmpty(r))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(r);
 
XmlNode xn = doc["Response"];
string statuscode = xn["StatusCode"].InnerText;
if(string.Compare(statuscode, "200", true) == 0)
{
xn = xn["ResourceSets"]["ResourceSet"]["Resources"];
XmlNodeList xnl = xn.ChildNodes;
foreach(XmlNode xno in xnl)
{
XmlNode imageUrl = xno["ImageUrl"];
 
if(imageUrl != null && !string.IsNullOrEmpty(imageUrl.InnerText))
{
if(cache && GMaps.Instance.UseUrlCache)
{
Cache.Instance.SaveContent("GetTileUrl" + imageryType, CacheType.UrlCache, r);
}
 
var baseTileUrl = imageUrl.InnerText;
 
if(baseTileUrl.Contains("{key}") || baseTileUrl.Contains("{token}"))
{
baseTileUrl.Replace("{key}", SessionId).Replace("{token}", SessionId);
}
else if(ForceSessionIdOnTileAccess)
{
// haven't seen anyone doing that, yet? ;/
baseTileUrl += "&key=" + SessionId;
}
 
Debug.WriteLine("GetTileUrl, UrlFormat[" + imageryType + "]: " + baseTileUrl);
 
ret = baseTileUrl;
break;
}
}
}
}
}
catch(Exception ex)
{
Debug.WriteLine("GetTileUrl: Error getting Bing Maps tile URL - " + ex);
}
}
return ret;
}
 
#region RoutingProvider
 
public MapRoute GetRoute(PointLatLng start, PointLatLng end, bool avoidHighways, bool walkingMode, int Zoom)
{
string tooltip;
int numLevels;
int zoomFactor;
MapRoute ret = null;
List<PointLatLng> points = GetRoutePoints(MakeRouteUrl(start, end, LanguageStr, avoidHighways, walkingMode), Zoom, out tooltip, out numLevels, out zoomFactor);
if(points != null)
{
ret = new MapRoute(points, tooltip);
}
return ret;
}
 
public MapRoute GetRoute(string start, string end, bool avoidHighways, bool walkingMode, int Zoom)
{
string tooltip;
int numLevels;
int zoomFactor;
MapRoute ret = null;
List<PointLatLng> points = GetRoutePoints(MakeRouteUrl(start, end, LanguageStr, avoidHighways, walkingMode), Zoom, out tooltip, out numLevels, out zoomFactor);
if(points != null)
{
ret = new MapRoute(points, tooltip);
}
return ret;
}
 
string MakeRouteUrl(string start, string end, string language, bool avoidHighways, bool walkingMode)
{
string addition = avoidHighways ? "&avoid=highways" : string.Empty;
string mode = walkingMode ? "Walking" : "Driving";
 
return string.Format(CultureInfo.InvariantCulture, RouteUrlFormatPointQueries, mode, start, end, addition, SessionId);
}
 
string MakeRouteUrl(PointLatLng start, PointLatLng end, string language, bool avoidHighways, bool walkingMode)
{
string addition = avoidHighways ? "&avoid=highways" : string.Empty;
string mode = walkingMode ? "Walking" : "Driving";
 
return string.Format(CultureInfo.InvariantCulture, RouteUrlFormatPointLatLng, mode, start.Lat, start.Lng, end.Lat, end.Lng, addition, SessionId);
}
 
List<PointLatLng> GetRoutePoints(string url, int zoom, out string tooltipHtml, out int numLevel, out int zoomFactor)
{
List<PointLatLng> points = null;
tooltipHtml = string.Empty;
numLevel = -1;
zoomFactor = -1;
try
{
string route = GMaps.Instance.UseRouteCache ? Cache.Instance.GetContent(url, CacheType.RouteCache) : string.Empty;
 
if(string.IsNullOrEmpty(route))
{
route = GetContentUsingHttp(url);
 
if(!string.IsNullOrEmpty(route))
{
if(GMaps.Instance.UseRouteCache)
{
Cache.Instance.SaveContent(url, CacheType.RouteCache, route);
}
}
}
 
// parse values
if(!string.IsNullOrEmpty(route))
{
#region -- title --
int tooltipEnd = 0;
{
int x = route.IndexOf("<RoutePath><Line>") + 17;
if(x >= 17)
{
tooltipEnd = route.IndexOf("</Line></RoutePath>", x + 1);
if(tooltipEnd > 0)
{
int l = tooltipEnd - x;
if(l > 0)
{
//tooltipHtml = route.Substring(x, l).Replace(@"\x26#160;", " ");
tooltipHtml = route.Substring(x, l);
}
}
}
}
#endregion
 
#region -- points --
XmlDocument doc = new XmlDocument();
doc.LoadXml(route);
XmlNode xn = doc["Response"];
string statuscode = xn["StatusCode"].InnerText;
switch(statuscode)
{
case "200":
{
xn = xn["ResourceSets"]["ResourceSet"]["Resources"]["Route"]["RoutePath"]["Line"];
XmlNodeList xnl = xn.ChildNodes;
if(xnl.Count > 0)
{
points = new List<PointLatLng>();
foreach(XmlNode xno in xnl)
{
XmlNode latitude = xno["Latitude"];
XmlNode longitude = xno["Longitude"];
points.Add(new PointLatLng(double.Parse(latitude.InnerText, CultureInfo.InvariantCulture),
double.Parse(longitude.InnerText, CultureInfo.InvariantCulture)));
}
}
break;
}
// no status implementation on routes yet although when introduced these are the codes. Exception will be catched.
case "400":
throw new Exception("Bad Request, The request contained an error.");
case "401":
throw new Exception("Unauthorized, Access was denied. You may have entered your credentials incorrectly, or you might not have access to the requested resource or operation.");
case "403":
throw new Exception("Forbidden, The request is for something forbidden. Authorization will not help.");
case "404":
throw new Exception("Not Found, The requested resource was not found.");
case "500":
throw new Exception("Internal Server Error, Your request could not be completed because there was a problem with the service.");
case "501":
throw new Exception("Service Unavailable, There's a problem with the service right now. Please try again later.");
default:
points = null;
break; // unknown, for possible future error codes
}
#endregion
}
}
catch(Exception ex)
{
points = null;
Debug.WriteLine("GetRoutePoints: " + ex);
}
return points;
}
 
// example : http://dev.virtualearth.net/REST/V1/Routes/Driving?o=xml&wp.0=44.979035,-93.26493&wp.1=44.943828508257866,-93.09332862496376&optmz=distance&rpo=Points&key=[PROVIDEYOUROWNKEY!!]
static readonly string RouteUrlFormatPointLatLng = "http://dev.virtualearth.net/REST/V1/Routes/{0}?o=xml&wp.0={1},{2}&wp.1={3},{4}{5}&optmz=distance&rpo=Points&key={6}";
static readonly string RouteUrlFormatPointQueries = "http://dev.virtualearth.net/REST/V1/Routes/{0}?o=xml&wp.0={1}&wp.1={2}{3}&optmz=distance&rpo=Points&key={4}";
 
#endregion RoutingProvider
 
#region GeocodingProvider
 
public GeoCoderStatusCode GetPoints(string keywords, out List<PointLatLng> pointList)
{
//Escape keywords to better handle special characters.
return GetLatLngFromGeocoderUrl(MakeGeocoderUrl("q=" + Uri.EscapeDataString(keywords)), out pointList);
}
 
public PointLatLng? GetPoint(string keywords, out GeoCoderStatusCode status)
{
List<PointLatLng> pointList;
status = GetPoints(keywords, out pointList);
return pointList != null && pointList.Count > 0 ? pointList[0] : (PointLatLng?)null;
}
 
public GeoCoderStatusCode GetPoints(Placemark placemark, out List<PointLatLng> pointList)
{
return GetLatLngFromGeocoderUrl(MakeGeocoderDetailedUrl(placemark), out pointList);
}
 
public PointLatLng? GetPoint(Placemark placemark, out GeoCoderStatusCode status)
{
List<PointLatLng> pointList;
status = GetLatLngFromGeocoderUrl(MakeGeocoderDetailedUrl(placemark), out pointList);
return pointList != null && pointList.Count > 0 ? pointList[0] : (PointLatLng?)null;
}
 
string MakeGeocoderDetailedUrl(Placemark placemark)
{
string parameters = string.Empty;
 
if(!AddFieldIfNotEmpty(ref parameters, "countryRegion", placemark.CountryNameCode))
AddFieldIfNotEmpty(ref parameters, "countryRegion", placemark.CountryName);
 
AddFieldIfNotEmpty(ref parameters, "adminDistrict", placemark.DistrictName);
AddFieldIfNotEmpty(ref parameters, "locality", placemark.LocalityName);
AddFieldIfNotEmpty(ref parameters, "postalCode", placemark.PostalCodeNumber);
 
if(!string.IsNullOrEmpty(placemark.HouseNo))
AddFieldIfNotEmpty(ref parameters, "addressLine", placemark.ThoroughfareName + " " + placemark.HouseNo);
else
AddFieldIfNotEmpty(ref parameters, "addressLine", placemark.ThoroughfareName);
 
return MakeGeocoderUrl(parameters);
}
 
bool AddFieldIfNotEmpty(ref string Input, string FieldName, string Value)
{
if(!string.IsNullOrEmpty(Value))
{
if(string.IsNullOrEmpty(Input))
Input = string.Empty;
else
Input = Input + "&";
 
Input = Input + FieldName + "=" + Value;
 
return true;
}
return false;
}
 
public GeoCoderStatusCode GetPlacemarks(PointLatLng location, out List<Placemark> placemarkList)
{
// http://msdn.microsoft.com/en-us/library/ff701713.aspx
throw new NotImplementedException();
}
 
public Placemark? GetPlacemark(PointLatLng location, out GeoCoderStatusCode status)
{
// http://msdn.microsoft.com/en-us/library/ff701713.aspx
throw new NotImplementedException();
}
 
string MakeGeocoderUrl(string keywords)
{
return string.Format(CultureInfo.InvariantCulture, GeocoderUrlFormat, keywords, SessionId);
}
 
GeoCoderStatusCode GetLatLngFromGeocoderUrl(string url, out List<PointLatLng> pointList)
{
var status = GeoCoderStatusCode.Unknow;
pointList = null;
 
try
{
string geo = GMaps.Instance.UseGeocoderCache ? Cache.Instance.GetContent(url, CacheType.GeocoderCache) : string.Empty;
 
bool cache = false;
 
if(string.IsNullOrEmpty(geo))
{
geo = GetContentUsingHttp(url);
 
if(!string.IsNullOrEmpty(geo))
{
cache = true;
}
}
 
status = GeoCoderStatusCode.Unknow;
if(!string.IsNullOrEmpty(geo))
{
if(geo.StartsWith("<?xml") && geo.Contains("<Response"))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(geo);
XmlNode xn = doc["Response"];
string statuscode = xn["StatusCode"].InnerText;
switch(statuscode)
{
case "200":
{
pointList = new List<PointLatLng>();
xn = xn["ResourceSets"]["ResourceSet"]["Resources"];
XmlNodeList xnl = xn.ChildNodes;
foreach(XmlNode xno in xnl)
{
XmlNode latitude = xno["Point"]["Latitude"];
XmlNode longitude = xno["Point"]["Longitude"];
pointList.Add(new PointLatLng(Double.Parse(latitude.InnerText, CultureInfo.InvariantCulture),
Double.Parse(longitude.InnerText, CultureInfo.InvariantCulture)));
}
 
if(pointList.Count > 0)
{
status = GeoCoderStatusCode.G_GEO_SUCCESS;
if(cache && GMaps.Instance.UseGeocoderCache)
{
Cache.Instance.SaveContent(url, CacheType.GeocoderCache, geo);
}
break;
}
 
status = GeoCoderStatusCode.G_GEO_UNKNOWN_ADDRESS;
break;
}
 
case "400":
status = GeoCoderStatusCode.G_GEO_BAD_REQUEST;
break; // bad request, The request contained an error.
case "401":
status = GeoCoderStatusCode.G_GEO_BAD_KEY;
break; // Unauthorized, Access was denied. You may have entered your credentials incorrectly, or you might not have access to the requested resource or operation.
case "403":
status = GeoCoderStatusCode.G_GEO_BAD_REQUEST;
break; // Forbidden, The request is for something forbidden. Authorization will not help.
case "404":
status = GeoCoderStatusCode.G_GEO_UNKNOWN_ADDRESS;
break; // Not Found, The requested resource was not found.
case "500":
status = GeoCoderStatusCode.G_GEO_SERVER_ERROR;
break; // Internal Server Error, Your request could not be completed because there was a problem with the service.
case "501":
status = GeoCoderStatusCode.Unknow;
break; // Service Unavailable, There's a problem with the service right now. Please try again later.
default:
status = GeoCoderStatusCode.Unknow;
break; // unknown, for possible future error codes
}
}
}
}
catch(Exception ex)
{
status = GeoCoderStatusCode.ExceptionInCode;
Debug.WriteLine("GetLatLngFromGeocoderUrl: " + ex);
}
 
return status;
}
 
// http://dev.virtualearth.net/REST/v1/Locations/1%20Microsoft%20Way%20Redmond%20WA%2098052?o=xml&key=BingMapsKey
static readonly string GeocoderUrlFormat = "http://dev.virtualearth.net/REST/v1/Locations?{0}&o=xml&key={1}";
 
#endregion GeocodingProvider
}
 
/// <summary>
/// BingMapProvider provider
/// </summary>
public class BingMapProvider : BingMapProviderBase
{
public static readonly BingMapProvider Instance;
 
BingMapProvider()
{
}
 
static BingMapProvider()
{
Instance = new BingMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("D0CEB371-F10A-4E12-A2C1-DF617D6674A8");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "BingMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
public override void OnInitialized()
{
base.OnInitialized();
 
if(!DisableDynamicTileUrlFormat)
{
//UrlFormat[Road]: http://ecn.{subdomain}.tiles.virtualearth.net/tiles/r{quadkey}.jpeg?g=3179&mkt={culture}&shading=hill
 
UrlDynamicFormat = GetTileUrl("Road");
if(!string.IsNullOrEmpty(UrlDynamicFormat))
{
UrlDynamicFormat = UrlDynamicFormat.Replace("{subdomain}", "t{0}").Replace("{quadkey}", "{1}").Replace("{culture}", "{2}");
}
}
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string key = TileXYToQuadKey(pos.X, pos.Y, zoom);
 
if(!DisableDynamicTileUrlFormat && !string.IsNullOrEmpty(UrlDynamicFormat))
{
return string.Format(UrlDynamicFormat, GetServerNum(pos, 4), key, language);
}
 
return string.Format(UrlFormat, GetServerNum(pos, 4), key, Version, language, ForceSessionIdOnTileAccess ? "&key=" + SessionId : string.Empty);
}
 
string UrlDynamicFormat = string.Empty;
 
// http://ecn.t0.tiles.virtualearth.net/tiles/r120030?g=875&mkt=en-us&lbl=l1&stl=h&shading=hill&n=z
 
static readonly string UrlFormat = "http://ecn.t{0}.tiles.virtualearth.net/tiles/r{1}?g={2}&mkt={3}&lbl=l1&stl=h&shading=hill&n=z{4}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Bing/BingSatelliteMapProvider.cs
0,0 → 1,85

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// BingSatelliteMapProvider provider
/// </summary>
public class BingSatelliteMapProvider : BingMapProviderBase
{
public static readonly BingSatelliteMapProvider Instance;
 
BingSatelliteMapProvider()
{
}
 
static BingSatelliteMapProvider()
{
Instance = new BingSatelliteMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("3AC742DD-966B-4CFB-B67D-33E7F82F2D37");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "BingSatelliteMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
public override void OnInitialized()
{
base.OnInitialized();
 
if(!DisableDynamicTileUrlFormat)
{
//UrlFormat[Aerial]: http://ecn.{subdomain}.tiles.virtualearth.net/tiles/a{quadkey}.jpeg?g=3179
 
UrlDynamicFormat = GetTileUrl("Aerial");
if(!string.IsNullOrEmpty(UrlDynamicFormat))
{
UrlDynamicFormat = UrlDynamicFormat.Replace("{subdomain}", "t{0}").Replace("{quadkey}", "{1}");
}
}
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string key = TileXYToQuadKey(pos.X, pos.Y, zoom);
 
if(!DisableDynamicTileUrlFormat && !string.IsNullOrEmpty(UrlDynamicFormat))
{
return string.Format(UrlDynamicFormat, GetServerNum(pos, 4), key);
}
 
return string.Format(UrlFormat, GetServerNum(pos, 4), key, Version, language, ForceSessionIdOnTileAccess ? "&key=" + SessionId : string.Empty);
}
 
string UrlDynamicFormat = string.Empty;
 
// http://ecn.t1.tiles.virtualearth.net/tiles/a12030003131321231.jpeg?g=875&mkt=en-us&n=z
 
static readonly string UrlFormat = "http://ecn.t{0}.tiles.virtualearth.net/tiles/a{1}.jpeg?g={2}&mkt={3}&n=z{4}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Czech/CzechGeographicMapProvider.cs
0,0 → 1,59
namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// CzechTuristMap provider, http://www.mapy.cz/
/// </summary>
public class CzechGeographicMapProvider : CzechMapProviderBase
{
public static readonly CzechGeographicMapProvider Instance;
 
CzechGeographicMapProvider()
{
}
 
static CzechGeographicMapProvider()
{
Instance = new CzechGeographicMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("50EC9FCC-E4D7-4F53-8700-2D1DB73A1D48");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechGeographicMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://m3.mapserver.mapy.czzemepis-m/14-8802-5528
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/zemepis-m/{1}-{2}-{3}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Czech/CzechHistoryMapProvider.cs
0,0 → 1,74

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// CzechHistoryMap provider, http://www.mapy.cz/
/// </summary>
public class CzechHistoryMapProvider : CzechMapProviderBase
{
public static readonly CzechHistoryMapProvider Instance;
 
CzechHistoryMapProvider()
{
MaxZoom = 15;
}
 
static CzechHistoryMapProvider()
{
Instance = new CzechHistoryMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("CD44C19D-5EED-4623-B367-FB39FDC55B8F");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechHistoryMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this, CzechHybridMapProvider.Instance };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://m3.mapserver.mapy.cz/army2-m/14-8802-5528
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/army2-m/{1}-{2}-{3}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Czech/CzechHybridMapProvider.cs
0,0 → 1,73

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// CzechHybridMap provider, http://www.mapy.cz/
/// </summary>
public class CzechHybridMapProvider : CzechMapProviderBase
{
public static readonly CzechHybridMapProvider Instance;
 
CzechHybridMapProvider()
{
}
 
static CzechHybridMapProvider()
{
Instance = new CzechHybridMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("7540CE5B-F634-41E9-B23E-A6E0A97526FD");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechHybridMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { CzechSatelliteMapProvider.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://m3.mapserver.mapy.cz/hybrid-m/14-8802-5528
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/hybrid-m/{1}-{2}-{3}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Czech/CzechMapProvider.cs
0,0 → 1,115

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
public abstract class CzechMapProviderBase : GMapProvider
{
public CzechMapProviderBase()
{
RefererUrl = "http://www.mapy.cz/";
Area = new RectLatLng(51.2024819920053, 11.8401353319027, 7.22833716731277, 2.78312271922872);
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
}
 
/// <summary>
/// CzechMap provider, http://www.mapy.cz/
/// </summary>
public class CzechMapProvider : CzechMapProviderBase
{
public static readonly CzechMapProvider Instance;
 
CzechMapProvider()
{
}
 
static CzechMapProvider()
{
Instance = new CzechMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("13AB92EF-8C3B-4FAC-B2CD-2594C05F8BFC");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// ['base-m','ophoto-m','turist-m','army2-m']
// http://m3.mapserver.mapy.cz/base-m/14-8802-5528
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/base-m/{1}-{2}-{3}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Czech/CzechSatelliteMapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// CzechSatelliteMap provider, http://www.mapy.cz/
/// </summary>
public class CzechSatelliteMapProvider : CzechMapProviderBase
{
public static readonly CzechSatelliteMapProvider Instance;
 
CzechSatelliteMapProvider()
{
}
 
static CzechSatelliteMapProvider()
{
Instance = new CzechSatelliteMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("30F433DB-BBF5-463D-9AB5-76383483B605");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechSatelliteMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://m3.mapserver.mapy.cz/ophoto-m/14-8802-5528
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/ophoto-m/{1}-{2}-{3}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Czech/CzechTuristMapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// CzechTuristMap provider, http://www.mapy.cz/
/// </summary>
public class CzechTuristMapProvider : CzechMapProviderBase
{
public static readonly CzechTuristMapProvider Instance;
 
CzechTuristMapProvider()
{
}
 
static CzechTuristMapProvider()
{
Instance = new CzechTuristMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("102A54BE-3894-439B-9C1F-CA6FF2EA1FE9");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechTuristMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://m3.mapserver.mapy.cz/wtourist-m/14-8802-5528
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/wturist-m/{1}-{2}-{3}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Czech/CzechTuristWinterMapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// CzechTuristMap provider, http://www.mapy.cz/
/// </summary>
public class CzechTuristWinterMapProvider : CzechMapProviderBase
{
public static readonly CzechTuristWinterMapProvider Instance;
 
CzechTuristWinterMapProvider()
{
}
 
static CzechTuristWinterMapProvider()
{
Instance = new CzechTuristWinterMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("F7B7FC9E-BDC2-4A9D-A1D3-A6BEC8FE0EB2");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechTuristWinterMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://m3.mapserver.mapy.cz/wturist_winter-m/14-8802-5528
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/wturist_winter-m/{1}-{2}-{3}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/CzechOld/CzechHistoryMapProvider.cs
0,0 → 1,76

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// CzechHistoryMap provider, http://www.mapy.cz/
/// </summary>
public class CzechHistoryMapProviderOld : CzechMapProviderBaseOld
{
public static readonly CzechHistoryMapProviderOld Instance;
 
CzechHistoryMapProviderOld()
{
}
 
static CzechHistoryMapProviderOld()
{
Instance = new CzechHistoryMapProviderOld();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("C666AAF4-9D27-418F-97CB-7F0D8CC44544");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechHistoryOldMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this, CzechHybridMapProviderOld.Instance };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://m4.mapserver.mapy.cz/army2/9_7d00000_8080000
 
long xx = pos.X << (28 - zoom);
long yy = ((((long)Math.Pow(2.0, (double)zoom)) - 1) - pos.Y) << (28 - zoom);
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, xx, yy);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/army2/{1}_{2:x7}_{3:x7}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/CzechOld/CzechHybridMapProvider.cs
0,0 → 1,76

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// CzechHybridMap provider, http://www.mapy.cz/
/// </summary>
public class CzechHybridMapProviderOld : CzechMapProviderBaseOld
{
public static readonly CzechHybridMapProviderOld Instance;
 
CzechHybridMapProviderOld()
{
}
 
static CzechHybridMapProviderOld()
{
Instance = new CzechHybridMapProviderOld();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("F785D98E-DD1D-46FD-8BC1-1AAB69604980");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechHybridOldMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { CzechSatelliteMapProviderOld.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://m2.mapserver.mapy.cz/hybrid/9_7d00000_7b80000
 
long xx = pos.X << (28 - zoom);
long yy = ((((long)Math.Pow(2.0, (double)zoom)) - 1) - pos.Y) << (28 - zoom);
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, xx, yy);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/hybrid/{1}_{2:x7}_{3:x7}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/CzechOld/CzechMapProvider.cs
0,0 → 1,118

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
public abstract class CzechMapProviderBaseOld : GMapProvider
{
public CzechMapProviderBaseOld()
{
RefererUrl = "http://www.mapy.cz/";
Area = new RectLatLng(51.2024819920053, 11.8401353319027, 7.22833716731277, 2.78312271922872);
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MapyCZProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
}
 
/// <summary>
/// CzechMap provider, http://www.mapy.cz/
/// </summary>
public class CzechMapProviderOld : CzechMapProviderBaseOld
{
public static readonly CzechMapProviderOld Instance;
 
CzechMapProviderOld()
{
}
 
static CzechMapProviderOld()
{
Instance = new CzechMapProviderOld();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("6A1AF99A-84C6-4EF6-91A5-77B9D03257C2");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechOldMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// ['base','ophoto','turist','army2']
// http://m1.mapserver.mapy.cz/base-n/3_8000000_8000000
 
long xx = pos.X << (28 - zoom);
long yy = ((((long)Math.Pow(2.0, (double)zoom)) - 1) - pos.Y) << (28 - zoom);
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, xx, yy);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/base-n/{1}_{2:x7}_{3:x7}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/CzechOld/CzechSatelliteMapProvider.cs
0,0 → 1,63

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// CzechSatelliteMap provider, http://www.mapy.cz/
/// </summary>
public class CzechSatelliteMapProviderOld : CzechMapProviderBaseOld
{
public static readonly CzechSatelliteMapProviderOld Instance;
 
CzechSatelliteMapProviderOld()
{
}
 
static CzechSatelliteMapProviderOld()
{
Instance = new CzechSatelliteMapProviderOld();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("7846D655-5F9C-4042-8652-60B6BF629C3C");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechSatelliteOldMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
//http://m3.mapserver.mapy.cz/ophoto/9_7a80000_7a80000
 
long xx = pos.X << (28 - zoom);
long yy = ((((long)Math.Pow(2.0, (double)zoom)) - 1) - pos.Y) << (28 - zoom);
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, xx, yy);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/ophoto/{1}_{2:x7}_{3:x7}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/CzechOld/CzechTuristMapProvider.cs
0,0 → 1,63

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// CzechTuristMap provider, http://www.mapy.cz/
/// </summary>
public class CzechTuristMapProviderOld : CzechMapProviderBaseOld
{
public static readonly CzechTuristMapProviderOld Instance;
 
CzechTuristMapProviderOld()
{
}
 
static CzechTuristMapProviderOld()
{
Instance = new CzechTuristMapProviderOld();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("B923C81D-880C-42EB-88AB-AF8FE42B564D");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CzechTuristOldMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://m1.mapserver.mapy.cz/turist/3_8000000_8000000
 
long xx = pos.X << (28 - zoom);
long yy = ((((long)Math.Pow(2.0, (double)zoom)) - 1) - pos.Y) << (28 - zoom);
 
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, xx, yy);
}
 
static readonly string UrlFormat = "http://m{0}.mapserver.mapy.cz/turist/{1}_{2:x7}_{3:x7}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Etc/CloudMadeMapProvider.cs
0,0 → 1,561

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
using System.Globalization;
using GMap.NET.Internals;
using System.Collections.Generic;
using System.Xml;
using System.Diagnostics;
 
public abstract class CloudMadeMapProviderBase : GMapProvider, RoutingProvider, DirectionsProvider
{
public readonly string ServerLetters = "abc";
public readonly string DoubleResolutionString = "@2x";
 
public bool DoubleResolution = true;
public string Key;
public int StyleID;
 
public string Version = "0.3";
 
public CloudMadeMapProviderBase()
{
MaxZoom = null;
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
 
#region RoutingProvider Members
 
public MapRoute GetRoute(PointLatLng start, PointLatLng end, bool avoidHighways, bool walkingMode, int Zoom)
{
List<PointLatLng> points = GetRoutePoints(MakeRoutingUrl(start, end, walkingMode ? TravelTypeFoot : TravelTypeMotorCar, LanguageStr, "km"));
MapRoute route = points != null ? new MapRoute(points, walkingMode ? WalkingStr : DrivingStr) : null;
return route;
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="avoidHighways"></param>
/// <param name="walkingMode"></param>
/// <param name="Zoom"></param>
/// <returns></returns>
public MapRoute GetRoute(string start, string end, bool avoidHighways, bool walkingMode, int Zoom)
{
throw new NotImplementedException();
}
 
#region -- internals --
 
string MakeRoutingUrl(PointLatLng start, PointLatLng end, string travelType, string language, string units)
{
// http://developers.cloudmade.com/projects/routing-http-api/examples/
// http://routes.cloudmade.com/YOUR-API-KEY-GOES-HERE/api/0.3/start_point,[[transit_point1,...,transit_pointN]],end_point/route_type[/route_type_modifier].output_format[?lang=(en|de)][&units=(km|miles)]
return string.Format(CultureInfo.InvariantCulture, UrlFormat, Key, Version, start.Lat, start.Lng, end.Lat, end.Lng, travelType, language, units);
}
 
List<PointLatLng> GetRoutePoints(string url)
{
List<PointLatLng> points = null;
try
{
string route = GMaps.Instance.UseRouteCache ? Cache.Instance.GetContent(url, CacheType.RouteCache) : string.Empty;
if(string.IsNullOrEmpty(route))
{
route = GetContentUsingHttp(url);
if(!string.IsNullOrEmpty(route))
{
if(GMaps.Instance.UseRouteCache)
{
Cache.Instance.SaveContent(url, CacheType.RouteCache, route);
}
}
}
 
#region -- gpx response --
//<?xml version="1.0" encoding="UTF-8"?>
//<gpx creator="" version="1.1" xmlns="http://www.topografix.com/GPX/1/1"
// xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
// xsi:schemaLocation="http://www.topografix.com/GPX/1/1 gpx.xsd ">
// <extensions>
// <distance>293</distance>
// <time>34</time>
// <start>Perckhoevelaan</start>
// <end>Goudenregenlaan</end>
// </extensions>
// <wpt lat="51.17702" lon="4.39630" />
// <wpt lat="51.17656" lon="4.39655" />
// <wpt lat="51.17639" lon="4.39670" />
// <wpt lat="51.17612" lon="4.39696" />
// <wpt lat="51.17640" lon="4.39767" />
// <wpt lat="51.17668" lon="4.39828" />
// <wpt lat="51.17628" lon="4.39874" />
// <wpt lat="51.17618" lon="4.39888" />
// <rte>
// <rtept lat="51.17702" lon="4.39630">
// <desc>Head south on Perckhoevelaan, 0.1 km</desc>
// <extensions>
// <distance>111</distance>
// <time>13</time>
// <offset>0</offset>
// <distance-text>0.1 km</distance-text>
// <direction>S</direction>
// <azimuth>160.6</azimuth>
// </extensions>
// </rtept>
// <rtept lat="51.17612" lon="4.39696">
// <desc>Turn left at Laarstraat, 0.1 km</desc>
// <extensions>
// <distance>112</distance>
// <time>13</time>
// <offset>3</offset>
// <distance-text>0.1 km</distance-text>
// <direction>NE</direction>
// <azimuth>58.1</azimuth>
// <turn>TL</turn>
// <turn-angle>269.0</turn-angle>
// </extensions>
// </rtept>
// <rtept lat="51.17668" lon="4.39828">
// <desc>Turn right at Goudenregenlaan, 70 m</desc>
// <extensions>
// <distance>70</distance>
// <time>8</time>
// <offset>5</offset>
// <distance-text>70 m</distance-text>
// <direction>SE</direction>
// <azimuth>143.4</azimuth>
// <turn>TR</turn>
// <turn-angle>89.8</turn-angle>
// </extensions>
// </rtept>
// </rte>
//</gpx>
#endregion
 
if(!string.IsNullOrEmpty(route))
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(route);
System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmldoc.NameTable);
xmlnsManager.AddNamespace("sm", "http://www.topografix.com/GPX/1/1");
 
XmlNodeList wpts = xmldoc.SelectNodes("/sm:gpx/sm:wpt", xmlnsManager);
if(wpts != null && wpts.Count > 0)
{
points = new List<PointLatLng>();
foreach(XmlNode w in wpts)
{
double lat = double.Parse(w.Attributes["lat"].InnerText, CultureInfo.InvariantCulture);
double lng = double.Parse(w.Attributes["lon"].InnerText, CultureInfo.InvariantCulture);
points.Add(new PointLatLng(lat, lng));
}
}
}
}
catch(Exception ex)
{
Debug.WriteLine("GetRoutePoints: " + ex);
}
 
return points;
}
 
static readonly string UrlFormat = "http://routes.cloudmade.com/{0}/api/{1}/{2},{3},{4},{5}/{6}.gpx?lang={7}&units={8}";
static readonly string TravelTypeFoot = "foot";
static readonly string TravelTypeMotorCar = "car";
static readonly string WalkingStr = "Walking";
static readonly string DrivingStr = "Driving";
 
#endregion
 
#endregion
 
#region DirectionsProvider Members
 
public DirectionsStatusCode GetDirections(out GDirections direction, PointLatLng start, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
return GetDirectionsUrl(MakeRoutingUrl(start, end, walkingMode ? TravelTypeFoot : TravelTypeMotorCar, LanguageStr, metric ? "km" : "miles"), out direction);
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="direction"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="avoidHighways"></param>
/// <param name="avoidTolls"></param>
/// <param name="walkingMode"></param>
/// <param name="sensor"></param>
/// <param name="metric"></param>
/// <returns></returns>
public DirectionsStatusCode GetDirections(out GDirections direction, string start, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
throw new NotImplementedException();
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="status"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="avoidHighways"></param>
/// <param name="avoidTolls"></param>
/// <param name="walkingMode"></param>
/// <param name="sensor"></param>
/// <param name="metric"></param>
/// <returns></returns>
public IEnumerable<GDirections> GetDirections(out DirectionsStatusCode status, string start, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
throw new NotImplementedException();
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="status"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="avoidHighways"></param>
/// <param name="avoidTolls"></param>
/// <param name="walkingMode"></param>
/// <param name="sensor"></param>
/// <param name="metric"></param>
/// <returns></returns>
public IEnumerable<GDirections> GetDirections(out DirectionsStatusCode status, PointLatLng start, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
throw new NotImplementedException();
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="direction"></param>
/// <param name="start"></param>
/// <param name="wayPoints"></param>
/// <param name="avoidHighways"></param>
/// <param name="avoidTolls"></param>
/// <param name="walkingMode"></param>
/// <param name="sensor"></param>
/// <param name="metric"></param>
/// <returns></returns>
public DirectionsStatusCode GetDirections(out GDirections direction, PointLatLng start, IEnumerable<PointLatLng> wayPoints, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
throw new NotImplementedException();
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="direction"></param>
/// <param name="start"></param>
/// <param name="wayPoints"></param>
/// <param name="avoidHighways"></param>
/// <param name="avoidTolls"></param>
/// <param name="walkingMode"></param>
/// <param name="sensor"></param>
/// <param name="metric"></param>
/// <returns></returns>
public DirectionsStatusCode GetDirections(out GDirections direction, string start, IEnumerable<string> wayPoints, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
throw new NotImplementedException();
}
 
#region -- internals --
 
DirectionsStatusCode GetDirectionsUrl(string url, out GDirections direction)
{
DirectionsStatusCode ret = DirectionsStatusCode.UNKNOWN_ERROR;
direction = null;
 
try
{
string route = GMaps.Instance.UseRouteCache ? Cache.Instance.GetContent(url, CacheType.DirectionsCache) : string.Empty;
if(string.IsNullOrEmpty(route))
{
route = GetContentUsingHttp(url);
if(!string.IsNullOrEmpty(route))
{
if(GMaps.Instance.UseRouteCache)
{
Cache.Instance.SaveContent(url, CacheType.DirectionsCache, route);
}
}
}
 
#region -- gpx response --
//<?xml version="1.0" encoding="UTF-8"?>
//<gpx creator="" version="1.1" xmlns="http://www.topografix.com/GPX/1/1"
// xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
// xsi:schemaLocation="http://www.topografix.com/GPX/1/1 gpx.xsd ">
// <extensions>
// <distance>293</distance>
// <time>34</time>
// <start>Perckhoevelaan</start>
// <end>Goudenregenlaan</end>
// </extensions>
// <wpt lat="51.17702" lon="4.39630" />
// <wpt lat="51.17656" lon="4.39655" />
// <wpt lat="51.17639" lon="4.39670" />
// <wpt lat="51.17612" lon="4.39696" />
// <wpt lat="51.17640" lon="4.39767" />
// <wpt lat="51.17668" lon="4.39828" />
// <wpt lat="51.17628" lon="4.39874" />
// <wpt lat="51.17618" lon="4.39888" />
// <rte>
// <rtept lat="51.17702" lon="4.39630">
// <desc>Head south on Perckhoevelaan, 0.1 km</desc>
// <extensions>
// <distance>111</distance>
// <time>13</time>
// <offset>0</offset>
// <distance-text>0.1 km</distance-text>
// <direction>S</direction>
// <azimuth>160.6</azimuth>
// </extensions>
// </rtept>
// <rtept lat="51.17612" lon="4.39696">
// <desc>Turn left at Laarstraat, 0.1 km</desc>
// <extensions>
// <distance>112</distance>
// <time>13</time>
// <offset>3</offset>
// <distance-text>0.1 km</distance-text>
// <direction>NE</direction>
// <azimuth>58.1</azimuth>
// <turn>TL</turn>
// <turn-angle>269.0</turn-angle>
// </extensions>
// </rtept>
// <rtept lat="51.17668" lon="4.39828">
// <desc>Turn right at Goudenregenlaan, 70 m</desc>
// <extensions>
// <distance>70</distance>
// <time>8</time>
// <offset>5</offset>
// <distance-text>70 m</distance-text>
// <direction>SE</direction>
// <azimuth>143.4</azimuth>
// <turn>TR</turn>
// <turn-angle>89.8</turn-angle>
// </extensions>
// </rtept>
// </rte>
//</gpx>
#endregion
 
if(!string.IsNullOrEmpty(route))
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(route);
System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmldoc.NameTable);
xmlnsManager.AddNamespace("sm", "http://www.topografix.com/GPX/1/1");
 
XmlNodeList wpts = xmldoc.SelectNodes("/sm:gpx/sm:wpt", xmlnsManager);
if(wpts != null && wpts.Count > 0)
{
ret = DirectionsStatusCode.OK;
 
direction = new GDirections();
direction.Route = new List<PointLatLng>();
 
foreach(XmlNode w in wpts)
{
double lat = double.Parse(w.Attributes["lat"].InnerText, CultureInfo.InvariantCulture);
double lng = double.Parse(w.Attributes["lon"].InnerText, CultureInfo.InvariantCulture);
direction.Route.Add(new PointLatLng(lat, lng));
}
 
if(direction.Route.Count > 0)
{
direction.StartLocation = direction.Route[0];
direction.EndLocation = direction.Route[direction.Route.Count - 1];
}
 
XmlNode n = xmldoc.SelectSingleNode("/sm:gpx/sm:metadata/sm:copyright/sm:license", xmlnsManager);
if(n != null)
{
direction.Copyrights = n.InnerText;
}
 
n = xmldoc.SelectSingleNode("/sm:gpx/sm:extensions/sm:distance", xmlnsManager);
if(n != null)
{
direction.Distance = n.InnerText + "m";
}
 
n = xmldoc.SelectSingleNode("/sm:gpx/sm:extensions/sm:time", xmlnsManager);
if(n != null)
{
direction.Duration = n.InnerText + "s";
}
 
n = xmldoc.SelectSingleNode("/sm:gpx/sm:extensions/sm:start", xmlnsManager);
if(n != null)
{
direction.StartAddress = n.InnerText;
}
 
n = xmldoc.SelectSingleNode("/sm:gpx/sm:extensions/sm:end", xmlnsManager);
if(n != null)
{
direction.EndAddress = n.InnerText;
}
 
wpts = xmldoc.SelectNodes("/sm:gpx/sm:rte/sm:rtept", xmlnsManager);
if(wpts != null && wpts.Count > 0)
{
direction.Steps = new List<GDirectionStep>();
 
foreach(XmlNode w in wpts)
{
GDirectionStep step = new GDirectionStep();
 
double lat = double.Parse(w.Attributes["lat"].InnerText, CultureInfo.InvariantCulture);
double lng = double.Parse(w.Attributes["lon"].InnerText, CultureInfo.InvariantCulture);
 
step.StartLocation = new PointLatLng(lat, lng);
 
XmlNode nn = w.SelectSingleNode("sm:desc", xmlnsManager);
if(nn != null)
{
step.HtmlInstructions = nn.InnerText;
}
 
nn = w.SelectSingleNode("sm:extensions/sm:distance-text", xmlnsManager);
if(nn != null)
{
step.Distance = nn.InnerText;
}
 
nn = w.SelectSingleNode("sm:extensions/sm:time", xmlnsManager);
if(nn != null)
{
step.Duration = nn.InnerText + "s";
}
 
direction.Steps.Add(step);
}
}
}
}
}
catch(Exception ex)
{
ret = DirectionsStatusCode.ExceptionInCode;
direction = null;
Debug.WriteLine("GetDirectionsUrl: " + ex);
}
 
return ret;
}
 
#endregion
 
#endregion
}
 
/// <summary>
/// CloudMadeMap demo provider, http://maps.cloudmade.com/
/// </summary>
public class CloudMadeMapProvider : CloudMadeMapProviderBase
{
public static readonly CloudMadeMapProvider Instance;
 
CloudMadeMapProvider()
{
Key = "5937c2bd907f4f4a92d8980a7c666ac0"; // demo key of CloudMade
StyleID = 45363; // grab your style here http://maps.cloudmade.com/?styleId=45363
}
 
static CloudMadeMapProvider()
{
Instance = new CloudMadeMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("00403A36-725F-4BC4-934F-BFC1C164D003");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "CloudMade, Demo";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, ServerLetters[GetServerNum(pos, 3)], Key, StyleID, (DoubleResolution ? DoubleResolutionString : string.Empty), zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://{0}.tile.cloudmade.com/{1}/{2}{3}/256/{4}/{5}/{6}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Etc/LatviaMapProvider.cs
0,0 → 1,119

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
public abstract class LatviaMapProviderBase : GMapProvider
{
public LatviaMapProviderBase()
{
RefererUrl = "http://www.ikarte.lv/default.aspx?lang=en";
Copyright = string.Format("©{0} Hnit-Baltic - Map data ©{0} LR Valsts zemes dieniests, SIA Envirotech", DateTime.Today.Year);
MaxZoom = 11;
Area = new RectLatLng(58.0794870805093, 20.3286067123543, 7.90883164336887, 2.506129113082);
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return LKS92Projection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
}
 
/// <summary>
/// LatviaMap provider, http://www.ikarte.lv/
/// </summary>
public class LatviaMapProvider : LatviaMapProviderBase
{
public static readonly LatviaMapProvider Instance;
 
LatviaMapProvider()
{
}
 
static LatviaMapProvider()
{
Instance = new LatviaMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("2A21CBB1-D37C-458D-905E-05F19536EF1F");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "LatviaMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://www.maps.lt/cache/ikartelv/map/_alllayers/L03/R00000037/C00000053.png
// http://www.maps.lt/arcgiscache/ikartelv/map/_alllayers/L02/R0000001c/C0000002a.png
// http://services.maps.lt/mapsk_services/rest/services/ikartelv/MapServer/tile/5/271/416.png?cl=ikrlv
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://services.maps.lt/mapsk_services/rest/services/ikartelv/MapServer/tile/{0}/{1}/{2}.png?cl=ikrlv";
//static readonly string UrlFormat = "http://www.maps.lt/arcgiscache/ikartelv/map/_alllayers/L{0:00}/R{1:x8}/C{2:x8}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Etc/MapBenderWMSProvider.cs
0,0 → 1,92

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
using System.Globalization;
 
/// <summary>
/// MapBender provider, WMS demo http://www.mapbender.org/
/// </summary>
public class MapBenderWMSProvider : GMapProvider
{
public static readonly MapBenderWMSProvider Instance;
 
MapBenderWMSProvider()
{
}
 
static MapBenderWMSProvider()
{
Instance = new MapBenderWMSProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("45742F8D-B552-4CAF-89AE-F20951BBDB2B");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "MapBender, WMS demo";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
var px1 = Projection.FromTileXYToPixel(pos);
var px2 = px1;
 
px1.Offset(0, Projection.TileSize.Height);
PointLatLng p1 = Projection.FromPixelToLatLng(px1, zoom);
 
px2.Offset(Projection.TileSize.Width, 0);
PointLatLng p2 = Projection.FromPixelToLatLng(px2, zoom);
 
var ret = string.Format(CultureInfo.InvariantCulture, UrlFormat, p1.Lng, p1.Lat, p2.Lng, p2.Lat, Projection.TileSize.Width, Projection.TileSize.Height);
 
return ret;
}
 
static readonly string UrlFormat = "http://mapbender.wheregroup.com/cgi-bin/mapserv?map=/data/umn/osm/osm_basic.map&VERSION=1.1.1&REQUEST=GetMap&SERVICE=WMS&LAYERS=OSM_Basic&styles=&bbox={0},{1},{2},{3}&width={4}&height={5}&srs=EPSG:4326&format=image/png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Etc/SpainMapProvider.cs
0,0 → 1,93

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
/// <summary>
/// SpainMap provider, http://sigpac.mapa.es/fega/visor/
/// </summary>
public class SpainMapProvider : GMapProvider
{
public static readonly SpainMapProvider Instance;
 
SpainMapProvider()
{
Copyright = string.Format("©{0} SIGPAC", DateTime.Today.Year);
MinZoom = 5;
Area = new RectLatLng(43.8741381814747, -9.700927734375, 14.34814453125, 7.8605775962932);
}
 
static SpainMapProvider()
{
Instance = new SpainMapProvider();
}
 
readonly string[] levels =
{
"0", "1", "2", "3", "4",
"MTNSIGPAC",
"MTN2000", "MTN2000", "MTN2000", "MTN2000", "MTN2000",
"MTN200", "MTN200", "MTN200",
"MTN25", "MTN25",
"ORTOFOTOS","ORTOFOTOS","ORTOFOTOS","ORTOFOTOS"
};
 
#region GMapProvider Members
 
readonly Guid id = new Guid("7B70ABB0-1265-4D34-9442-F0788F4F689F");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "SpainMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, levels[zoom], zoom, pos.X, ((2 << zoom - 1) - pos.Y - 1));
}
 
static readonly string UrlFormat = "http://sigpac.mapa.es/kmlserver/raster/{0}@3785/{1}.{2}.{3}.img";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Etc/SwedenMapProvider.cs
0,0 → 1,385

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
public abstract class SwedenMapProviderBase : GMapProvider
{
public SwedenMapProviderBase()
{
RefererUrl = "https://kso.etjanster.lantmateriet.se/?lang=en";
Copyright = string.Format("©{0} Lantmäteriet", DateTime.Today.Year);
MaxZoom = 11;
//Area = new RectLatLng(58.0794870805093, 20.3286067123543, 7.90883164336887, 2.506129113082);
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return SWEREF99_TMProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
}
 
/// <summary>
/// SwedenMap provider, https://kso.etjanster.lantmateriet.se/?lang=en#
/// </summary>
public class SwedenMapProvider : SwedenMapProviderBase
{
public static readonly SwedenMapProvider Instance;
 
SwedenMapProvider()
{
}
 
static SwedenMapProvider()
{
Instance = new SwedenMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("40890A96-6E82-4FA7-90A3-73D66B974F63");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "SwedenMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// https://kso.etjanster.lantmateriet.se/karta/topowebb/v1/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=topowebb&STYLE=default&TILEMATRIXSET=3006&TILEMATRIX=2&TILEROW=6&TILECOL=7&FORMAT=image%2Fpng
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://kso.etjanster.lantmateriet.se/karta/topowebb/v1/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=topowebb&STYLE=default&TILEMATRIXSET=3006&TILEMATRIX={0}&TILEROW={1}&TILECOL={2}&FORMAT=image%2Fpng";
}
}
 
/*
https://kso.etjanster.lantmateriet.se/?lang=en#
 
{
"analytics" : {
"account" : "UA-47513746-2"
},
"ortofotoServiceUrl" : "https://services-ver.lantmateriet.se/distribution/produkter/metabild/v1/ortofoto",
"metadata" : {
"password" : "wllZIV50DH2b",
"username" : "lant0181"
},
"minFastighetUrl" : "https://etjanster.lantmateriet.se/nyaminfastighet/?mode=TEXT&amp;module=sercxi-minafastigheter-module",
"enableKartvaljare" : false,
"frwebburl" : "https://etjanster.lantmateriet.se/frwebb/protect/index.jsp?information=FRW019&query=",
"previewServiceUrl" : "https://services-ver.lantmateriet.se/distribution/produkter/tumnagel/v1/",
"minaFastighetsArendenUrl" : "https://etjanster.lantmateriet.se/minafastighetsarenden",
"flygbildServiceUrl" : "https://services-ver.lantmateriet.se/distribution/produkter/metabild/v1/flygbild"
}
 
PROJCS["SWEREF99 TM",
GEOGCS["SWEREF99",
DATUM["SWEREF99",
SPHEROID["GRS 1980",6378137,298.257222101,
AUTHORITY["EPSG","7019"]],
TOWGS84[0,0,0,0,0,0,0],
AUTHORITY["EPSG","6619"]],
PRIMEM["Greenwich",0,
AUTHORITY["EPSG","8901"]],
UNIT["degree",0.01745329251994328,
AUTHORITY["EPSG","9122"]],
AUTHORITY["EPSG","4619"]],
UNIT["metre",1,
AUTHORITY["EPSG","9001"]],
PROJECTION["Transverse_Mercator"],
PARAMETER["latitude_of_origin",0],
PARAMETER["central_meridian",15],
PARAMETER["scale_factor",0.9996],
PARAMETER["false_easting",500000],
PARAMETER["false_northing",0],
AUTHORITY["EPSG","3006"],
AXIS["y",EAST],
AXIS["x",NORTH]]
 
{
"defaultLayer" : "topowebbwmts",
"extent" : {
"left" : -1200000,
"bottom" : 4700000,
"right" : 2600000,
"top" : 8500000
},
"projection" : "EPSG:3006",
"units" : "m",
"allOverlays" : true,
"resolutions" : [4096.0, 2048.0, 1024.0, 512.0, 256.0, 128.0, 64.0, 32.0, 16.0, 8.0, 4.0, 2.0, 1.0, 0.5, 0.25, 0.15, 0.1, 0.05, 0.01],
"initPosition" : {
"n" : 6607899,
"e" : 564931,
"zoom" : 2
},
"layers" : [{
"id" : "topowebbhydrografi",
"protocol" : "WMS",
"url" : ["https://kso.etjanster.lantmateriet.se/karta/topowebb-skikt/wms/v1.1"],
"exceptions" : "application/vnd.ogc.se_xml",
"format" : "image/png",
"layers" : "hydrografi",
"name" : "Hydrografi",
"fullmap" : "false",
"enabled" : "true",
"sheetFamily" : "",
"maxResolution" : 0.0,
"minResolution" : 0.0,
"visible" : "true",
"tileSize" : 512,
"maxScale" : 0,
"minScale" : 0,
"removeLayer" : "false",
"styles" : []
}, {
"id" : "orto",
"protocol" : "WMS",
"url" : ["https://kso.etjanster.lantmateriet.se/karta/ortofoto/wms/v1"],
"exceptions" : "application/vnd.ogc.se_xml",
"format" : "image/png",
"layers" : "orto",
"name" : "Ortofoton 0.5 m/pixel",
"fullmap" : "true",
"enabled" : "true",
"sheetFamily" : "",
"maxResolution" : 0.0,
"minResolution" : 0.0,
"visible" : "true",
"tileSize" : 512,
"maxScale" : 0,
"minScale" : 0,
"removeLayer" : "false",
"styles" : []
}, {
"id" : "topowebbwmts",
"protocol" : "WMTS",
"url" : ["https://kso.etjanster.lantmateriet.se/karta/topowebb/v1/wmts"],
"exceptions" : "application/vnd.ogc.se_xml",
"format" : "image/png",
"layers" : "topowebb",
"name" : "Topografisk webbkarta (cache)",
"fullmap" : "true",
"enabled" : "true",
"sheetFamily" : "",
"maxResolution" : 4096.0,
"minResolution" : 0.5,
"visible" : "false",
"tileSize" : 512,
"maxScale" : 0,
"minScale" : 0,
"removeLayer" : "false",
"styles" : []
}, {
"id" : "topowebbwms",
"protocol" : "WMS",
"url" : ["https://kso.etjanster.lantmateriet.se/karta/topowebb/wms/v1"],
"exceptions" : "application/vnd.ogc.se_xml",
"format" : "image/png",
"layers" : "topowebbkartan",
"name" : "Topografisk webbkarta",
"fullmap" : "true",
"enabled" : "true",
"sheetFamily" : "",
"maxResolution" : 0.0,
"minResolution" : 0.0,
"visible" : "true",
"tileSize" : 512,
"maxScale" : 0,
"minScale" : 0,
"removeLayer" : "false",
"styles" : []
}, {
"id" : "terrangskuggning",
"protocol" : "WMS",
"url" : ["https://kso.etjanster.lantmateriet.se/karta/hojdmodell/wms/v1"],
"exceptions" : "application/vnd.ogc.se_xml",
"format" : "image/png",
"layers" : "terrangskuggning",
"name" : "Terrängskuggning",
"fullmap" : "false",
"enabled" : "true",
"sheetFamily" : "",
"maxResolution" : 0.0,
"minResolution" : 0.0,
"visible" : "false",
"tileSize" : 2048,
"maxScale" : 0,
"minScale" : 0,
"removeLayer" : "false",
"styles" : []
}, {
"id" : "terrangkartan",
"protocol" : "WMS",
"url" : ["https://kso.etjanster.lantmateriet.se/karta/allmannakartor/wms/v1"],
"exceptions" : "application/vnd.ogc.se_xml",
"format" : "image/png",
"layers" : "terrangkartan",
"name" : "Terrängkartan",
"fullmap" : "true",
"enabled" : "true",
"sheetFamily" : "SE50",
"maxResolution" : 0.0,
"minResolution" : 0.0,
"visible" : "false",
"tileSize" : 512,
"maxScale" : 0,
"minScale" : 0,
"removeLayer" : "false",
"styles" : []
}, {
"id" : "fjallkartan",
"protocol" : "WMS",
"url" : ["https://kso.etjanster.lantmateriet.se/karta/allmannakartor/wms/v1"],
"exceptions" : "application/vnd.ogc.se_xml",
"format" : "image/png",
"layers" : "fjallkartan",
"name" : "Fjällkartan 1:100 000",
"fullmap" : "false",
"enabled" : "true",
"sheetFamily" : "SE100FJ",
"maxResolution" : 0.0,
"minResolution" : 0.0,
"visible" : "false",
"tileSize" : 512,
"maxScale" : 0,
"minScale" : 0,
"removeLayer" : "false",
"styles" : []
}, {
"id" : "vagkartan",
"protocol" : "WMS",
"url" : ["https://kso.etjanster.lantmateriet.se/karta/allmannakartor/wms/v1"],
"exceptions" : "application/vnd.ogc.se_xml",
"format" : "image/png",
"layers" : "vagkartan",
"name" : "Vägkartan",
"fullmap" : "true",
"enabled" : "true",
"sheetFamily" : "",
"maxResolution" : 0.0,
"minResolution" : 0.0,
"visible" : "false",
"tileSize" : 512,
"maxScale" : 0,
"minScale" : 0,
"removeLayer" : "false",
"styles" : []
}, {
"id" : "oversiktskartan",
"protocol" : "WMS",
"url" : ["https://kso.etjanster.lantmateriet.se/karta/geodata-intern/wms/v1"],
"exceptions" : "application/vnd.ogc.se_xml",
"format" : "image/png",
"layers" : "oversiktskartan",
"name" : "Översiktskartan",
"fullmap" : "true",
"enabled" : "true",
"sheetFamily" : "SE250",
"maxResolution" : 0.0,
"minResolution" : 0.0,
"visible" : "false",
"tileSize" : 512,
"maxScale" : 0,
"minScale" : 0,
"removeLayer" : "false",
"styles" : []
}, {
"id" : "sverigekartan",
"protocol" : "WMS",
"url" : ["https://kso.etjanster.lantmateriet.se/karta/allmannakartor/wms/v1"],
"exceptions" : "application/vnd.ogc.se_xml",
"format" : "image/png",
"layers" : "sverigekartan",
"name" : "Sverigekartan",
"fullmap" : "true",
"enabled" : "true",
"sheetFamily" : "",
"maxResolution" : 0.0,
"minResolution" : 0.0,
"visible" : "false",
"tileSize" : 512,
"maxScale" : 0,
"minScale" : 0,
"removeLayer" : "false",
"styles" : []
}
],
"profiles" : "[]",
"touchProfiles" : "[]",
"noAuthProfiles" : "[{'value':'default_background_noauth','text':'Topografisk','optgroup':'Standard'},{'value':'default_orto_noauth','text':'Ortofoto','optgroup':'Standard'},{'value':'default_terrangkartan_noauth','text':'Terrängkartan','optgroup':'Standard'},{'value':'default_fjallkartan_noauth','text':'Fjällkartan','optgroup':'Standard'},{'value':'default_vagkartan_noauth','text':'Vägkartan','optgroup':'Standard'},{'value':'default_sverigekartan_noauth','text':'Sverigekartan','optgroup':'Standard'},{'value':'default_terrangskuggning_noauth','text':'Terrängskuggning','optgroup':'Standard'}]",
"profileDescriptions" : {
"default_background" : "{'layers':[{'id':'topowebbwmts','index':0,'group':'','enabled':true,'visible':true,'style':'default','opacity':1.0}],'version':4}",
"default_terrangkartan_noauth" : "{'layers':[{'id':'terrangkartan','index':0,'group':'','enabled':true,'visible':true,'style':'default','opacity':1.0}],'version':4}",
"default_vagkartan_noauth" : "{'layers':[{'id':'vagkartan','index':0,'group':'','enabled':true,'visible':true,'style':'default','opacity':1.0}],'version':4}",
"default_orto_noauth" : "{'layers':[{'id':'orto025','index':0,'group':'','enabled':true,'visible':true,'style':'default','opacity':1.0},{'id':'orto','index':1,'group':'','enabled':true,'visible':true,'style':'default','opacity':1.0}],'version':4}",
"default_fjallkartan_noauth" : "{'layers':[{'id':'fjallkartan','index':0,'group':'','enabled':true,'visible':true,'style':'default','opacity':1.0}],'version':4}",
"default_sverigekartan_noauth" : "{'layers':[{'id':'sverigekartan','index':0,'group':'','enabled':true,'visible':true,'style':'default','opacity':1.0}],'version':4}",
"default_terrangskuggning_noauth" : "{'layers':[{'id':'topowebbhydrografi','index':0,'group':'','enabled':true,'visible':true,'style':'default','opacity':1.0},{'id':'terrangskuggning','index':1,'group':'','enabled':true,'visible':true,'style':'default','opacity':1.0}],'version':4}",
"default_background_noauth" : "{'layers':[{'id':'topowebbwmts','index':0,'group':'','enabled':true,'visible':true,'style':'default','opacity':1.0}],'version':4}"
}
}
*/
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Etc/TurkeyMapProvider.cs
0,0 → 1,99

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
/// <summary>
/// TurkeyMap provider, http://maps.pergo.com.tr/
/// </summary>
public class TurkeyMapProvider : GMapProvider
{
public static readonly TurkeyMapProvider Instance;
 
TurkeyMapProvider()
{
Copyright = string.Format("©{0} Pergo - Map data ©{0} Fideltus Advanced Technology", DateTime.Today.Year);
Area = new RectLatLng(42.5830078125, 25.48828125, 19.05029296875, 6.83349609375);
InvertedAxisY = true;
}
 
static TurkeyMapProvider()
{
Instance = new TurkeyMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("EDE895BD-756D-4BE4-8D03-D54DD8856F1D");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "TurkeyMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://{domain}/{layerName}/{zoomLevel}/{first3LetterOfTileX}/{second3LetterOfTileX}/{third3LetterOfTileX}/{first3LetterOfTileY}/{second3LetterOfTileY}/{third3LetterOfTileXY}.png
 
// http://map3.pergo.com.tr/tile/00/000/000/001/000/000/000.png
// That means: Zoom Level: 0 TileX: 1 TileY: 0
 
// http://domain/tile/14/000/019/371/000/011/825.png
// That means: Zoom Level: 14 TileX: 19371 TileY:11825
 
// updated version
// http://map1.pergo.com.tr/publish/tile/tile9913/06/000/000/038/000/000/039.png
 
string x = pos.X.ToString(Zeros).Insert(3, Slash).Insert(7, Slash); // - 000/000/001
string y = pos.Y.ToString(Zeros).Insert(3, Slash).Insert(7, Slash); // - 000/000/000
 
return string.Format(UrlFormat, GetServerNum(pos, 3), zoom, x, y);
}
 
static readonly string Zeros = "000000000";
static readonly string Slash = "/";
static readonly string UrlFormat = "http://map{0}.pergo.com.tr/publish/tile/tile9913/{1:00}/{2}/{3}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Etc/WikiMapiaMapProvider.cs
0,0 → 1,127

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
public abstract class WikiMapiaMapProviderBase : GMapProvider
{
public WikiMapiaMapProviderBase()
{
MaxZoom = 22;
RefererUrl = "http://wikimapia.org/";
Copyright = string.Format("© WikiMapia.org - Map data ©{0} WikiMapia", DateTime.Today.Year);
}
 
#region GMapProvider Members
 
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
public override GMapProvider[] Overlays
{
get
{
throw new NotImplementedException();
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
 
#endregion
 
public static int GetServerNum(GPoint pos)
{
return (int)(pos.X % 4 + (pos.Y % 4) * 4);
}
}
 
/// <summary>
/// WikiMapiaMap provider, http://wikimapia.org/
/// </summary>
public class WikiMapiaMapProvider : WikiMapiaMapProviderBase
{
public static readonly WikiMapiaMapProvider Instance;
 
WikiMapiaMapProvider()
{
}
 
static WikiMapiaMapProvider()
{
Instance = new WikiMapiaMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("7974022B-1AA6-41F1-8D01-F49940E4B48C");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "WikiMapiaMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, GetServerNum(pos), pos.X, pos.Y, zoom);
}
 
static readonly string UrlFormat = "http://i{0}.wikimapia.org/?x={1}&y={2}&zoom={3}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/GMapProvider.cs
0,0 → 1,703

namespace GMap.NET.MapProviders
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using GMap.NET.Internals;
using GMap.NET.Projections;
using System.Text;
using System.Security.Cryptography;
 
/// <summary>
/// providers that are already build in
/// </summary>
public class GMapProviders
{
static GMapProviders()
{
list = new List<GMapProvider>();
 
Type type = typeof(GMapProviders);
foreach (var p in type.GetFields())
{
var v = p.GetValue(null) as GMapProvider; // static classes cannot be instanced, so use null...
if (v != null)
{
list.Add(v);
}
}
 
Hash = new Dictionary<Guid, GMapProvider>();
foreach (var p in list)
{
Hash.Add(p.Id, p);
}
 
DbHash = new Dictionary<int, GMapProvider>();
foreach (var p in list)
{
DbHash.Add(p.DbId, p);
}
}
 
GMapProviders()
{
}
 
public static readonly EmptyProvider EmptyProvider = EmptyProvider.Instance;
 
public static readonly OpenStreetMapProvider OpenStreetMap = OpenStreetMapProvider.Instance;
 
public static readonly OpenStreet4UMapProvider OpenStreet4UMap = OpenStreet4UMapProvider.Instance;
 
public static readonly OpenCycleMapProvider OpenCycleMap = OpenCycleMapProvider.Instance;
public static readonly OpenCycleLandscapeMapProvider OpenCycleLandscapeMap = OpenCycleLandscapeMapProvider.Instance;
public static readonly OpenCycleTransportMapProvider OpenCycleTransportMap = OpenCycleTransportMapProvider.Instance;
 
public static readonly OpenStreetMapQuestProvider OpenStreetMapQuest = OpenStreetMapQuestProvider.Instance;
public static readonly OpenStreetMapQuestSatteliteProvider OpenStreetMapQuestSattelite = OpenStreetMapQuestSatteliteProvider.Instance;
public static readonly OpenStreetMapQuestHybridProvider OpenStreetMapQuestHybrid = OpenStreetMapQuestHybridProvider.Instance;
 
public static readonly OpenSeaMapHybridProvider OpenSeaMapHybrid = OpenSeaMapHybridProvider.Instance;
 
#if OpenStreetOsm
public static readonly OpenStreetOsmProvider OpenStreetOsm = OpenStreetOsmProvider.Instance;
#endif
 
#if OpenStreetMapSurfer
public static readonly OpenStreetMapSurferProvider OpenStreetMapSurfer = OpenStreetMapSurferProvider.Instance;
public static readonly OpenStreetMapSurferTerrainProvider OpenStreetMapSurferTerrain = OpenStreetMapSurferTerrainProvider.Instance;
#endif
public static readonly WikiMapiaMapProvider WikiMapiaMap = WikiMapiaMapProvider.Instance;
 
public static readonly BingMapProvider BingMap = BingMapProvider.Instance;
public static readonly BingSatelliteMapProvider BingSatelliteMap = BingSatelliteMapProvider.Instance;
public static readonly BingHybridMapProvider BingHybridMap = BingHybridMapProvider.Instance;
 
public static readonly YahooMapProvider YahooMap = YahooMapProvider.Instance;
public static readonly YahooSatelliteMapProvider YahooSatelliteMap = YahooSatelliteMapProvider.Instance;
public static readonly YahooHybridMapProvider YahooHybridMap = YahooHybridMapProvider.Instance;
 
public static readonly GoogleMapProvider GoogleMap = GoogleMapProvider.Instance;
public static readonly GoogleSatelliteMapProvider GoogleSatelliteMap = GoogleSatelliteMapProvider.Instance;
public static readonly GoogleHybridMapProvider GoogleHybridMap = GoogleHybridMapProvider.Instance;
public static readonly GoogleTerrainMapProvider GoogleTerrainMap = GoogleTerrainMapProvider.Instance;
 
public static readonly GoogleChinaMapProvider GoogleChinaMap = GoogleChinaMapProvider.Instance;
public static readonly GoogleChinaSatelliteMapProvider GoogleChinaSatelliteMap = GoogleChinaSatelliteMapProvider.Instance;
public static readonly GoogleChinaHybridMapProvider GoogleChinaHybridMap = GoogleChinaHybridMapProvider.Instance;
public static readonly GoogleChinaTerrainMapProvider GoogleChinaTerrainMap = GoogleChinaTerrainMapProvider.Instance;
 
public static readonly GoogleKoreaMapProvider GoogleKoreaMap = GoogleKoreaMapProvider.Instance;
public static readonly GoogleKoreaSatelliteMapProvider GoogleKoreaSatelliteMap = GoogleKoreaSatelliteMapProvider.Instance;
public static readonly GoogleKoreaHybridMapProvider GoogleKoreaHybridMap = GoogleKoreaHybridMapProvider.Instance;
 
public static readonly NearMapProvider NearMap = NearMapProvider.Instance;
public static readonly NearSatelliteMapProvider NearSatelliteMap = NearSatelliteMapProvider.Instance;
public static readonly NearHybridMapProvider NearHybridMap = NearHybridMapProvider.Instance;
 
public static readonly OviMapProvider OviMap = OviMapProvider.Instance;
public static readonly OviSatelliteMapProvider OviSatelliteMap = OviSatelliteMapProvider.Instance;
public static readonly OviHybridMapProvider OviHybridMap = OviHybridMapProvider.Instance;
public static readonly OviTerrainMapProvider OviTerrainMap = OviTerrainMapProvider.Instance;
 
public static readonly YandexMapProvider YandexMap = YandexMapProvider.Instance;
public static readonly YandexSatelliteMapProvider YandexSatelliteMap = YandexSatelliteMapProvider.Instance;
public static readonly YandexHybridMapProvider YandexHybridMap = YandexHybridMapProvider.Instance;
 
public static readonly LithuaniaMapProvider LithuaniaMap = LithuaniaMapProvider.Instance;
public static readonly LithuaniaReliefMapProvider LithuaniaReliefMap = LithuaniaReliefMapProvider.Instance;
public static readonly Lithuania3dMapProvider Lithuania3dMap = Lithuania3dMapProvider.Instance;
public static readonly LithuaniaOrtoFotoMapProvider LithuaniaOrtoFotoMap = LithuaniaOrtoFotoMapProvider.Instance;
public static readonly LithuaniaOrtoFotoOldMapProvider LithuaniaOrtoFotoOldMap = LithuaniaOrtoFotoOldMapProvider.Instance;
public static readonly LithuaniaHybridMapProvider LithuaniaHybridMap = LithuaniaHybridMapProvider.Instance;
public static readonly LithuaniaHybridOldMapProvider LithuaniaHybridOldMap = LithuaniaHybridOldMapProvider.Instance;
public static readonly LithuaniaTOP50 LithuaniaTOP50Map = LithuaniaTOP50.Instance;
 
public static readonly LatviaMapProvider LatviaMap = LatviaMapProvider.Instance;
 
public static readonly MapBenderWMSProvider MapBenderWMSdemoMap = MapBenderWMSProvider.Instance;
 
public static readonly TurkeyMapProvider TurkeyMap = TurkeyMapProvider.Instance;
 
public static readonly CloudMadeMapProvider CloudMadeMap = CloudMadeMapProvider.Instance;
 
public static readonly SpainMapProvider SpainMap = SpainMapProvider.Instance;
 
public static readonly CzechMapProviderOld CzechOldMap = CzechMapProviderOld.Instance;
public static readonly CzechSatelliteMapProviderOld CzechSatelliteOldMap = CzechSatelliteMapProviderOld.Instance;
public static readonly CzechHybridMapProviderOld CzechHybridOldMap = CzechHybridMapProviderOld.Instance;
public static readonly CzechTuristMapProviderOld CzechTuristOldMap = CzechTuristMapProviderOld.Instance;
public static readonly CzechHistoryMapProviderOld CzechHistoryOldMap = CzechHistoryMapProviderOld.Instance;
 
public static readonly CzechMapProvider CzechMap = CzechMapProvider.Instance;
public static readonly CzechSatelliteMapProvider CzechSatelliteMap = CzechSatelliteMapProvider.Instance;
public static readonly CzechHybridMapProvider CzechHybridMap = CzechHybridMapProvider.Instance;
public static readonly CzechTuristMapProvider CzechTuristMap = CzechTuristMapProvider.Instance;
public static readonly CzechTuristWinterMapProvider CzechTuristWinterMap = CzechTuristWinterMapProvider.Instance;
public static readonly CzechHistoryMapProvider CzechHistoryMap = CzechHistoryMapProvider.Instance;
public static readonly CzechGeographicMapProvider CzechGeographicMap = CzechGeographicMapProvider.Instance;
public static readonly ArcGIS_Imagery_World_2D_MapProvider ArcGIS_Imagery_World_2D_Map = ArcGIS_Imagery_World_2D_MapProvider.Instance;
public static readonly ArcGIS_ShadedRelief_World_2D_MapProvider ArcGIS_ShadedRelief_World_2D_Map = ArcGIS_ShadedRelief_World_2D_MapProvider.Instance;
public static readonly ArcGIS_StreetMap_World_2D_MapProvider ArcGIS_StreetMap_World_2D_Map = ArcGIS_StreetMap_World_2D_MapProvider.Instance;
public static readonly ArcGIS_Topo_US_2D_MapProvider ArcGIS_Topo_US_2D_Map = ArcGIS_Topo_US_2D_MapProvider.Instance;
 
public static readonly ArcGIS_World_Physical_MapProvider ArcGIS_World_Physical_Map = ArcGIS_World_Physical_MapProvider.Instance;
public static readonly ArcGIS_World_Shaded_Relief_MapProvider ArcGIS_World_Shaded_Relief_Map = ArcGIS_World_Shaded_Relief_MapProvider.Instance;
public static readonly ArcGIS_World_Street_MapProvider ArcGIS_World_Street_Map = ArcGIS_World_Street_MapProvider.Instance;
public static readonly ArcGIS_World_Terrain_Base_MapProvider ArcGIS_World_Terrain_Base_Map = ArcGIS_World_Terrain_Base_MapProvider.Instance;
public static readonly ArcGIS_World_Topo_MapProvider ArcGIS_World_Topo_Map = ArcGIS_World_Topo_MapProvider.Instance;
 
public static readonly ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_MapProvider ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_Map = ArcGIS_DarbAE_Q2_2011_NAVTQ_Eng_V5_MapProvider.Instance;
 
public static readonly SwedenMapProvider SwedenMap = SwedenMapProvider.Instance;
 
static List<GMapProvider> list;
 
/// <summary>
/// get all instances of the supported providers
/// </summary>
public static List<GMapProvider> List
{
get
{
return list;
}
}
 
static Dictionary<Guid, GMapProvider> Hash;
 
public static GMapProvider TryGetProvider(Guid id)
{
GMapProvider ret;
if (Hash.TryGetValue(id, out ret))
{
return ret;
}
return null;
}
 
static Dictionary<int, GMapProvider> DbHash;
 
public static GMapProvider TryGetProvider(int DbId)
{
GMapProvider ret;
if (DbHash.TryGetValue(DbId, out ret))
{
return ret;
}
return null;
}
}
 
/// <summary>
/// base class for each map provider
/// </summary>
public abstract class GMapProvider
{
/// <summary>
/// unique provider id
/// </summary>
public abstract Guid Id
{
get;
}
 
/// <summary>
/// provider name
/// </summary>
public abstract string Name
{
get;
}
 
/// <summary>
/// provider projection
/// </summary>
public abstract PureProjection Projection
{
get;
}
 
/// <summary>
/// provider overlays
/// </summary>
public abstract GMapProvider[] Overlays
{
get;
}
 
/// <summary>
/// gets tile image using implmented provider
/// </summary>
/// <param name="pos"></param>
/// <param name="zoom"></param>
/// <returns></returns>
public abstract PureImage GetTileImage(GPoint pos, int zoom);
 
static readonly List<GMapProvider> MapProviders = new List<GMapProvider>();
 
protected GMapProvider()
{
using (var HashProvider = new SHA1CryptoServiceProvider())
{
DbId = Math.Abs(BitConverter.ToInt32(HashProvider.ComputeHash(Id.ToByteArray()), 0));
}
 
if (MapProviders.Exists(p => p.Id == Id || p.DbId == DbId))
{
throw new Exception("such provider id already exsists, try regenerate your provider guid...");
}
MapProviders.Add(this);
}
 
static GMapProvider()
{
WebProxy = EmptyWebProxy.Instance;
}
 
bool isInitialized = false;
 
/// <summary>
/// was provider initialized
/// </summary>
public bool IsInitialized
{
get
{
return isInitialized;
}
internal set
{
isInitialized = value;
}
}
 
/// <summary>
/// called before first use
/// </summary>
public virtual void OnInitialized()
{
// nice place to detect current provider version
}
 
/// <summary>
/// id for database, a hash of provider guid
/// </summary>
public readonly int DbId;
 
/// <summary>
/// area of map
/// </summary>
public RectLatLng? Area;
 
/// <summary>
/// minimum level of zoom
/// </summary>
public int MinZoom;
 
/// <summary>
/// maximum level of zoom
/// </summary>
public int? MaxZoom = 17;
 
/// <summary>
/// proxy for net access
/// </summary>
public static IWebProxy WebProxy;
 
/// <summary>
/// Connect trough a SOCKS 4/5 proxy server
/// </summary>
public static bool IsSocksProxy = false;
 
/// <summary>
/// NetworkCredential for tile http access
/// </summary>
public static ICredentials Credential;
 
/// <summary>
/// Gets or sets the value of the User-agent HTTP header.
/// It's pseudo-randomized to avoid blockages...
/// </summary>
public static string UserAgent = string.Format("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:{0}.0) Gecko/{2}{3:00}{4:00} Firefox/{0}.0.{1}", Stuff.random.Next(3, 14), Stuff.random.Next(1, 10), Stuff.random.Next(DateTime.Today.Year - 4, DateTime.Today.Year), Stuff.random.Next(12), Stuff.random.Next(30));
 
/// <summary>
/// timeout for provider connections
/// </summary>
#if !PocketPC
public static int TimeoutMs = 5 * 1000;
#else
public static int TimeoutMs = 44 * 1000;
#endif
/// <summary>
/// Gets or sets the value of the Referer HTTP header.
/// </summary>
public string RefererUrl = string.Empty;
 
public string Copyright = string.Empty;
 
/// <summary>
/// true if tile origin at BottomLeft, WMS-C
/// </summary>
public bool InvertedAxisY = false;
 
static string languageStr = "en";
public static string LanguageStr
{
get
{
return languageStr;
}
}
static LanguageType language = LanguageType.English;
 
/// <summary>
/// map language
/// </summary>
public static LanguageType Language
{
get
{
return language;
}
set
{
language = value;
languageStr = Stuff.EnumToString(Language);
}
}
 
/// <summary>
/// to bypass the cache, set to true
/// </summary>
public bool BypassCache = false;
 
/// <summary>
/// internal proxy for image managment
/// </summary>
internal static PureImageProxy TileImageProxy;
 
static readonly string requestAccept = "*/*";
static readonly string responseContentType = "image";
 
protected virtual bool CheckTileImageHttpResponse(WebResponse response)
{
//Debug.WriteLine(response.StatusCode + "/" + response.StatusDescription + "/" + response.ContentType + " -> " + response.ResponseUri);
return response.ContentType.Contains(responseContentType);
}
string Authorization = string.Empty;
/// <summary>
/// http://blog.kowalczyk.info/article/at3/Forcing-basic-http-authentication-for-HttpWebReq.html
/// </summary>
/// <param name="userName"></param>
/// <param name="userPassword"></param>
public void ForceBasicHttpAuthentication(string userName, string userPassword)
{
Authorization = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + userPassword));
}
 
protected PureImage GetTileImageUsingHttp(string url)
{
PureImage ret = null;
 
#if !PocketPC
WebRequest request = IsSocksProxy ? SocksHttpWebRequest.Create(url) : WebRequest.Create(url);
#else
WebRequest request = WebRequest.Create(url);
#endif
if (WebProxy != null)
{
request.Proxy = WebProxy;
}
 
if (Credential != null)
{
request.PreAuthenticate = true;
request.Credentials = Credential;
}
if(!string.IsNullOrEmpty(Authorization))
{
request.Headers.Set("Authorization", Authorization);
}
if (request is HttpWebRequest)
{
var r = request as HttpWebRequest;
r.UserAgent = UserAgent;
r.ReadWriteTimeout = TimeoutMs * 6;
r.Accept = requestAccept;
r.Referer = RefererUrl;
r.Timeout = TimeoutMs;
}
#if !PocketPC
else if (request is SocksHttpWebRequest)
{
var r = request as SocksHttpWebRequest;
 
if (!string.IsNullOrEmpty(UserAgent))
{
r.Headers.Add("User-Agent", UserAgent);
}
 
if (!string.IsNullOrEmpty(requestAccept))
{
r.Headers.Add("Accept", requestAccept);
}
 
if (!string.IsNullOrEmpty(RefererUrl))
{
r.Headers.Add("Referer", RefererUrl);
}
}
#endif
using (var response = request.GetResponse())
{
if (CheckTileImageHttpResponse(response))
{
using (Stream responseStream = response.GetResponseStream())
{
MemoryStream data = Stuff.CopyStream(responseStream, false);
 
Debug.WriteLine("Response[" + data.Length + " bytes]: " + url);
 
if (data.Length > 0)
{
ret = TileImageProxy.FromStream(data);
 
if (ret != null)
{
ret.Data = data;
ret.Data.Position = 0;
}
else
{
data.Dispose();
}
}
data = null;
}
}
else
{
Debug.WriteLine("CheckTileImageHttpResponse[false]: " + url);
}
#if PocketPC
request.Abort();
#endif
response.Close();
}
return ret;
}
 
protected string GetContentUsingHttp(string url)
{
string ret = string.Empty;
 
#if !PocketPC
WebRequest request = IsSocksProxy ? SocksHttpWebRequest.Create(url) : WebRequest.Create(url);
#else
WebRequest request = WebRequest.Create(url);
#endif
 
if (WebProxy != null)
{
request.Proxy = WebProxy;
}
 
if (Credential != null)
{
request.PreAuthenticate = true;
request.Credentials = Credential;
}
if(!string.IsNullOrEmpty(Authorization))
{
request.Headers.Set("Authorization", Authorization);
}
 
if (request is HttpWebRequest)
{
var r = request as HttpWebRequest;
r.UserAgent = UserAgent;
r.ReadWriteTimeout = TimeoutMs * 6;
r.Accept = requestAccept;
r.Referer = RefererUrl;
r.Timeout = TimeoutMs;
}
#if !PocketPC
else if (request is SocksHttpWebRequest)
{
var r = request as SocksHttpWebRequest;
 
if (!string.IsNullOrEmpty(UserAgent))
{
r.Headers.Add("User-Agent", UserAgent);
}
 
if (!string.IsNullOrEmpty(requestAccept))
{
r.Headers.Add("Accept", requestAccept);
}
 
if (!string.IsNullOrEmpty(RefererUrl))
{
r.Headers.Add("Referer", RefererUrl);
}
}
#endif
using (var response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader read = new StreamReader(responseStream, Encoding.UTF8))
{
ret = read.ReadToEnd();
}
}
#if PocketPC
request.Abort();
#endif
response.Close();
}
 
return ret;
}
 
#if !PocketPC
/// <summary>
/// use at your own risk, storing tiles in files is slow and hard on the file system
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
protected virtual PureImage GetTileImageFromFile(string fileName)
{
return GetTileImageFromArray(File.ReadAllBytes(fileName));
}
#endif
protected virtual PureImage GetTileImageFromArray(byte [] data)
{
return TileImageProxy.FromArray(data);
}
protected static int GetServerNum(GPoint pos, int max)
{
return (int)(pos.X + 2 * pos.Y) % max;
}
 
public override int GetHashCode()
{
return (int)DbId;
}
 
public override bool Equals(object obj)
{
if (obj is GMapProvider)
{
return Id.Equals((obj as GMapProvider).Id);
}
return false;
}
 
public override string ToString()
{
return Name;
}
}
 
/// <summary>
/// represents empty provider
/// </summary>
public class EmptyProvider : GMapProvider
{
public static readonly EmptyProvider Instance;
 
EmptyProvider()
{
MaxZoom = null;
}
 
static EmptyProvider()
{
Instance = new EmptyProvider();
}
 
#region GMapProvider Members
 
public override Guid Id
{
get
{
return Guid.Empty;
}
}
 
readonly string name = "None";
public override string Name
{
get
{
return name;
}
}
 
readonly MercatorProjection projection = MercatorProjection.Instance;
public override PureProjection Projection
{
get
{
return projection;
}
}
 
public override GMapProvider[] Overlays
{
get
{
return null;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
return null;
}
 
#endregion
}
 
public sealed class EmptyWebProxy : IWebProxy
{
public static readonly EmptyWebProxy Instance = new EmptyWebProxy();
 
private ICredentials m_credentials;
public ICredentials Credentials
{
get
{
return this.m_credentials;
}
set
{
this.m_credentials = value;
}
}
 
public Uri GetProxy(Uri uri)
{
return uri;
}
 
public bool IsBypassed(Uri uri)
{
return true;
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/China/GoogleChinaHybridMapProvider.cs
0,0 → 1,81

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// GoogleChinaHybridMap provider
/// </summary>
public class GoogleChinaHybridMapProvider : GoogleMapProviderBase
{
public static readonly GoogleChinaHybridMapProvider Instance;
 
GoogleChinaHybridMapProvider()
{
RefererUrl = string.Format("http://ditu.{0}/", ServerChina);
}
 
static GoogleChinaHybridMapProvider()
{
Instance = new GoogleChinaHybridMapProvider();
}
 
public string Version = "h@298";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("B8A2A78D-1C49-45D0-8F03-9B95C83116B7");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleChinaHybridMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { GoogleChinaSatelliteMapProvider.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty; // after &x=...
string sec2 = string.Empty; // after &zoom=...
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, ChinaLanguage, pos.X, sec1, pos.Y, zoom, sec2, ServerChina);
}
 
static readonly string ChinaLanguage = "zh-CN";
static readonly string UrlFormatServer = "mt";
static readonly string UrlFormatRequest = "vt";
static readonly string UrlFormat = "http://{0}{1}.{10}/{2}/imgtp=png32&lyrs={3}&hl={4}&gl=cn&x={5}{6}&y={7}&z={8}&s={9}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/China/GoogleChinaMapProvider.cs
0,0 → 1,68

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// GoogleChinaMap provider
/// </summary>
public class GoogleChinaMapProvider : GoogleMapProviderBase
{
public static readonly GoogleChinaMapProvider Instance;
 
GoogleChinaMapProvider()
{
RefererUrl = string.Format("http://ditu.{0}/", ServerChina);
}
 
static GoogleChinaMapProvider()
{
Instance = new GoogleChinaMapProvider();
}
 
public string Version = "m@298";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("1213F763-64EE-4AB6-A14A-D84D6BCC3426");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleChinaMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty; // after &x=...
string sec2 = string.Empty; // after &zoom=...
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, ChinaLanguage, pos.X, sec1, pos.Y, zoom, sec2, ServerChina);
}
 
static readonly string ChinaLanguage = "zh-CN";
static readonly string UrlFormatServer = "mt";
static readonly string UrlFormatRequest = "vt";
static readonly string UrlFormat = "http://{0}{1}.{10}/{2}/lyrs={3}&hl={4}&gl=cn&x={5}{6}&y={7}&z={8}&s={9}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/China/GoogleChinaSatelliteMapProvider.cs
0,0 → 1,67

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// GoogleChinaSatelliteMap provider
/// </summary>
public class GoogleChinaSatelliteMapProvider : GoogleMapProviderBase
{
public static readonly GoogleChinaSatelliteMapProvider Instance;
 
GoogleChinaSatelliteMapProvider()
{
RefererUrl = string.Format("http://ditu.{0}/", ServerChina);
}
 
static GoogleChinaSatelliteMapProvider()
{
Instance = new GoogleChinaSatelliteMapProvider();
}
 
public string Version = "s@170";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("543009AC-3379-4893-B580-DBE6372B1753");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleChinaSatelliteMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty; // after &x=...
string sec2 = string.Empty; // after &zoom=...
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, pos.X, sec1, pos.Y, zoom, sec2, ServerChina);
}
 
static readonly string UrlFormatServer = "mt";
static readonly string UrlFormatRequest = "vt";
static readonly string UrlFormat = "http://{0}{1}.{9}/{2}/lyrs={3}&gl=cn&x={4}{5}&y={6}&z={7}&s={8}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/China/GoogleChinaTerrainMapProvider.cs
0,0 → 1,68

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// GoogleChinaTerrainMap provider
/// </summary>
public class GoogleChinaTerrainMapProvider : GoogleMapProviderBase
{
public static readonly GoogleChinaTerrainMapProvider Instance;
 
GoogleChinaTerrainMapProvider()
{
RefererUrl = string.Format("http://ditu.{0}/", ServerChina);
}
 
static GoogleChinaTerrainMapProvider()
{
Instance = new GoogleChinaTerrainMapProvider();
}
 
public string Version = "t@132,r@298";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("831EC3CC-B044-4097-B4B7-FC9D9F6D2CFC");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleChinaTerrainMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty; // after &x=...
string sec2 = string.Empty; // after &zoom=...
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, ChinaLanguage, pos.X, sec1, pos.Y, zoom, sec2, ServerChina);
}
 
static readonly string ChinaLanguage = "zh-CN";
static readonly string UrlFormatServer = "mt";
static readonly string UrlFormatRequest = "vt";
static readonly string UrlFormat = "http://{0}{1}.{10}/{2}/lyrs={3}&hl={4}&gl=cn&x={5}{6}&y={7}&z={8}&s={9}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/GoogleHybridMapProvider.cs
0,0 → 1,79

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// GoogleHybridMap provider
/// </summary>
public class GoogleHybridMapProvider : GoogleMapProviderBase
{
public static readonly GoogleHybridMapProvider Instance;
 
GoogleHybridMapProvider()
{
}
 
static GoogleHybridMapProvider()
{
Instance = new GoogleHybridMapProvider();
}
 
public string Version = "h@365000000"; //"h@333000000";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("B076C255-6D12-4466-AAE0-4A73D20A7E6A");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleHybridMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { GoogleSatelliteMapProvider.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty; // after &x=...
string sec2 = string.Empty; // after &zoom=...
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, language, pos.X, sec1, pos.Y, zoom, sec2, Server);
}
 
static readonly string UrlFormatServer = "mt";
static readonly string UrlFormatRequest = "vt";
static readonly string UrlFormat = "http://{0}{1}.{10}/maps/{2}/lyrs={3}&hl={4}&x={5}{6}&y={7}&z={8}&s={9}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/GoogleMapProvider.cs
0,0 → 1,2191

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using GMap.NET.Internals;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using System.Text;
#if PocketPC
using OpenNETCF.Security.Cryptography;
#endif
 
public abstract class GoogleMapProviderBase : GMapProvider, RoutingProvider, GeocodingProvider, DirectionsProvider
{
public GoogleMapProviderBase()
{
MaxZoom = null;
RefererUrl = string.Format("http://maps.{0}/", Server);
Copyright = string.Format("©{0} Google - Map data ©{0} Tele Atlas, Imagery ©{0} TerraMetrics", DateTime.Today.Year);
}
 
public readonly string ServerAPIs /* ;}~~ */ = Stuff.GString(/*{^_^}*/"9gERyvblybF8iMuCt/LD6w=="/*d{'_'}b*/);
public readonly string Server /* ;}~~~~ */ = Stuff.GString(/*{^_^}*/"gosr2U13BoS+bXaIxt6XWg=="/*d{'_'}b*/);
public readonly string ServerChina /* ;}~ */ = Stuff.GString(/*{^_^}*/"gosr2U13BoTEJoJJuO25gQ=="/*d{'_'}b*/);
public readonly string ServerKorea /* ;}~~ */ = Stuff.GString(/*{^_^}*/"8ZVBOEsBinzi+zmP7y7pPA=="/*d{'_'}b*/);
public readonly string ServerKoreaKr /* ;}~ */ = Stuff.GString(/*{^_^}*/"gosr2U13BoQyz1gkC4QLfg=="/*d{'_'}b*/);
 
public string SecureWord = "Galileo";
 
/// <summary>
/// Your application's API key, obtained from the Google Developers Console.
/// This key identifies your application for purposes of quota management.
/// Must provide either API key or Maps for Work credentials.
/// </summary>
public string ApiKey = string.Empty;
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
GMapProvider [] overlays;
public override GMapProvider [] Overlays
{
get
{
if (overlays == null)
{
overlays = new GMapProvider [] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
 
public bool TryCorrectVersion = true;
static bool init = false;
 
public override void OnInitialized()
{
if (!init && TryCorrectVersion)
{
string url = string.Format("https://maps.{0}/maps/api/js?client=google-maps-lite&amp;libraries=search&amp;language=en&amp;region=", ServerAPIs);
try
{
string html = GMaps.Instance.UseUrlCache ? Cache.Instance.GetContent(url, CacheType.UrlCache, TimeSpan.FromHours(8)) : string.Empty;
 
if (string.IsNullOrEmpty(html))
{
html = GetContentUsingHttp(url);
if (!string.IsNullOrEmpty(html))
{
if (GMaps.Instance.UseUrlCache)
{
Cache.Instance.SaveContent(url, CacheType.UrlCache, html);
}
}
}
 
if (!string.IsNullOrEmpty(html))
{
#region -- match versions --
Regex reg = new Regex(string.Format(@"https?://mts?\d.{0}/maps/vt\?lyrs=m@(\d*)", Server), RegexOptions.IgnoreCase);
Match mat = reg.Match(html);
if (mat.Success)
{
GroupCollection gc = mat.Groups;
int count = gc.Count;
if (count > 0)
{
string ver = string.Format("m@{0}", gc [1].Value);
string old = GMapProviders.GoogleMap.Version;
 
GMapProviders.GoogleMap.Version = ver;
GMapProviders.GoogleChinaMap.Version = ver;
string verh = string.Format("h@{0}", gc [1].Value);
string oldh = GMapProviders.GoogleHybridMap.Version;
 
GMapProviders.GoogleHybridMap.Version = verh;
GMapProviders.GoogleChinaHybridMap.Version = verh;
#if DEBUG
Debug.WriteLine("GMapProviders.GoogleMap.Version: " + ver + ", " + (ver == old ? "OK" : "old: " + old + ", consider updating source"));
Debug.WriteLine("GMapProviders.GoogleHybridMap.Version: " + verh + ", " + (verh == oldh ? "OK" : "old: " + oldh + ", consider updating source"));
 
if (Debugger.IsAttached && ver != old)
{
Thread.Sleep(1111);
}
#endif
}
}
 
reg = new Regex(string.Format(@"https?://khms?\d.{0}/kh\?v=(\d*)", Server), RegexOptions.IgnoreCase);
mat = reg.Match(html);
if (mat.Success)
{
GroupCollection gc = mat.Groups;
int count = gc.Count;
if (count > 0)
{
string ver = gc [1].Value;
string old = GMapProviders.GoogleSatelliteMap.Version;
 
GMapProviders.GoogleSatelliteMap.Version = ver;
GMapProviders.GoogleKoreaSatelliteMap.Version = ver;
GMapProviders.GoogleChinaSatelliteMap.Version = "s@" + ver;
#if DEBUG
Debug.WriteLine("GMapProviders.GoogleSatelliteMap.Version: " + ver + ", " + (ver == old ? "OK" : "old: " + old + ", consider updating source"));
if (Debugger.IsAttached && ver != old)
{
Thread.Sleep(1111);
}
#endif
}
}
 
reg = new Regex(string.Format(@"https?://mts?\d.{0}/maps/vt\?lyrs=t@(\d*),r@(\d*)", Server), RegexOptions.IgnoreCase);
mat = reg.Match(html);
if (mat.Success)
{
GroupCollection gc = mat.Groups;
int count = gc.Count;
if (count > 1)
{
string ver = string.Format("t@{0},r@{1}", gc [1].Value, gc [2].Value);
string old = GMapProviders.GoogleTerrainMap.Version;
 
GMapProviders.GoogleTerrainMap.Version = ver;
GMapProviders.GoogleChinaTerrainMap.Version = ver;
#if DEBUG
Debug.WriteLine("GMapProviders.GoogleTerrainMap.Version: " + ver + ", " + (ver == old ? "OK" : "old: " + old + ", consider updating source"));
if (Debugger.IsAttached && ver != old)
{
Thread.Sleep(1111);
}
#endif
}
}
#endregion
}
 
init = true; // try it only once
}
catch (Exception ex)
{
Debug.WriteLine("TryCorrectGoogleVersions failed: " + ex.ToString());
}
}
}
 
internal void GetSecureWords(GPoint pos, out string sec1, out string sec2)
{
sec1 = string.Empty; // after &x=...
sec2 = string.Empty; // after &zoom=...
int seclen = (int)((pos.X * 3) + pos.Y) % 8;
sec2 = SecureWord.Substring(0, seclen);
if (pos.Y >= 10000 && pos.Y < 100000)
{
sec1 = Sec1;
}
}
 
static readonly string Sec1 = "&s=";
 
#region RoutingProvider Members
 
public MapRoute GetRoute(PointLatLng start, PointLatLng end, bool avoidHighways, bool walkingMode, int Zoom)
{
string tooltip;
int numLevels;
int zoomFactor;
MapRoute ret = null;
List<PointLatLng> points = GetRoutePoints(MakeRouteUrl(start, end, LanguageStr, avoidHighways, walkingMode), Zoom, out tooltip, out numLevels, out zoomFactor);
if (points != null)
{
ret = new MapRoute(points, tooltip);
}
return ret;
}
 
public MapRoute GetRoute(string start, string end, bool avoidHighways, bool walkingMode, int Zoom)
{
string tooltip;
int numLevels;
int zoomFactor;
MapRoute ret = null;
List<PointLatLng> points = GetRoutePoints(MakeRouteUrl(start, end, LanguageStr, avoidHighways, walkingMode), Zoom, out tooltip, out numLevels, out zoomFactor);
if (points != null)
{
ret = new MapRoute(points, tooltip);
}
return ret;
}
 
#region -- internals --
 
string MakeRouteUrl(PointLatLng start, PointLatLng end, string language, bool avoidHighways, bool walkingMode)
{
string opt = walkingMode ? WalkingStr : (avoidHighways ? RouteWithoutHighwaysStr : RouteStr);
return string.Format(CultureInfo.InvariantCulture, RouteUrlFormatPointLatLng, language, opt, start.Lat, start.Lng, end.Lat, end.Lng, Server);
}
 
string MakeRouteUrl(string start, string end, string language, bool avoidHighways, bool walkingMode)
{
string opt = walkingMode ? WalkingStr : (avoidHighways ? RouteWithoutHighwaysStr : RouteStr);
return string.Format(RouteUrlFormatStr, language, opt, start.Replace(' ', '+'), end.Replace(' ', '+'), Server);
}
 
List<PointLatLng> GetRoutePoints(string url, int zoom, out string tooltipHtml, out int numLevel, out int zoomFactor)
{
List<PointLatLng> points = null;
tooltipHtml = string.Empty;
numLevel = -1;
zoomFactor = -1;
try
{
string route = GMaps.Instance.UseRouteCache ? Cache.Instance.GetContent(url, CacheType.RouteCache) : string.Empty;
 
if (string.IsNullOrEmpty(route))
{
route = GetContentUsingHttp(url);
 
if (!string.IsNullOrEmpty(route))
{
if (GMaps.Instance.UseRouteCache)
{
Cache.Instance.SaveContent(url, CacheType.RouteCache, route);
}
}
}
 
// parse values
if (!string.IsNullOrEmpty(route))
{
//{
//tooltipHtml:" (300\x26#160;km / 2 valandos 59 min.)",
//polylines:
//[{
// id:"route0",
// points:"cy~rIcvp`ClJ~v@jHpu@N|BB~A?tA_@`J@nAJrB|AhEf@h@~@^pANh@Mr@a@`@_@x@cBPk@ZiBHeDQ{C]wAc@mAqCeEoA_C{@_Cy@iDoEaW}AsJcJ}t@iWowB{C_Vyw@gvGyTyjBu@gHwDoZ{W_zBsX}~BiA_MmAyOcAwOs@yNy@eTk@mVUmTE}PJ_W`@cVd@cQ`@}KjA_V`AeOn@oItAkOdAaKfBaOhDiVbD}RpBuKtEkTtP}q@fr@ypCfCmK|CmNvEqVvCuQ`BgLnAmJ`CgTpA_N~@sLlBwYh@yLp@cSj@e]zFkzKHaVViSf@wZjFwqBt@{Wr@qS`AaUjAgStBkYrEwe@xIuw@`Gmj@rFok@~BkYtCy_@|KccBvBgZjC}[tD__@pDaYjB_MpBuLhGi[fC}KfFcSnEkObFgOrFkOzEoLt[ys@tJeUlIsSbKqXtFiPfKi]rG_W|CiNhDkPfDuQlDoShEuXrEy[nOgiAxF{`@|DoVzFk[fDwPlXupA~CoPfDuQxGcd@l@yEdH{r@xDam@`AiWz@mYtAq~@p@uqAfAqx@|@kZxA}^lBq\\|Be\\lAaO~Dm`@|Gsj@tS_~AhCyUrCeZrByWv@uLlUiyDpA}NdHkn@pGmb@LkAtAoIjDqR`I{`@`BcH|I_b@zJcd@lKig@\\_CbBaIlJ}g@lIoj@pAuJtFoh@~Eqs@hDmv@h@qOfF{jBn@gSxCio@dAuQn@gIVoBjAiOlCqWbCiT`PekAzKiu@~EgYfIya@fA{ExGwWnDkMdHiU|G}R`HgQhRsa@hW}g@jVsg@|a@cbAbJkUxKoYxLa_@`IiZzHu[`DoOXsBhBuJbCwNdBaL`EkYvAwM`CeVtEwj@nDqj@BkAnB{YpGgeAn@eJ`CmYvEid@tBkQpGkd@rE}UxB}JdJo_@nDcNfSan@nS}j@lCeIvDsMbC{J|CyNbAwFfCgPz@uGvBiSdD}`@rFon@nKaqAxDmc@xBuT|Fqc@nC_PrEcUtC_MpFcT`GqQxJmXfXwq@jQgh@hBeGhG_U|BaK|G}[nRikAzIam@tDsYfE}^v@_MbAwKn@oIr@yLrBub@jAoa@b@sRdDmjBx@aZdA}XnAqVpAgTlAqPn@oGvFye@dCeRzGwb@xT_}A`BcPrAoOvCad@jAmXv@eV`BieA~@a[fBg_@`CiZ~A_OhHqk@hHcn@tEwe@rDub@nBoW~@sN|BeZnAgMvDm\\hFs^hSigArFaY`Gc\\`C}OhD}YfByQdAaNbAkOtOu~Cn@wKz@uLfCeY|CkW~B}OhCmO|AcI~A_IvDoPpEyPdImWrDuKnL_YjI{Ptl@qfAle@u|@xI}PbImQvFwMbGgOxFkOpdAosCdD_KxGsU|E}RxFcXhCwNjDwTvBiPfBqOrAyMfBcTxAaVhAwVrCy_Al@iPt@_OtA}Q`AuJ`AgIzAkK`EoUtBsJhCaKxCaKdDaKhQeg@jGiRfGaSrFyR`HsWvL}f@xp@grC`Sq|@pEsVdAoGjF{XlkAgwHxHgj@|Jex@fg@qlEjQs{AdHwh@zDkVhEkVzI_e@v}AgzHpK_l@tE}YtEy[rC}TpFme@jg@cpEbF{d@~BoXfBqUbAyOx@yN|Ao]bAo[tIazC`@iLb@aJ~AkWbBgRdBgPjA{IdCePlAmHfBmJdCiL~CuM|DoNxhDezKdDkLvBoInFqVbCuMxBqNnAeJ~CwXdBoSb^crElFsl@`Dy[zDu^xBiRzc@aaE|Fsd@vCkShDmTpG}^lD}QzDoR|zAcdHvIob@dKoj@jDmSlKiq@xVacBhEqXnBqL|Ga^zJke@`y@ktD~Mop@tP}_AdOg`AtCiQxCyOlDkPfDoN`GiTfGkRjEwLvEsL|HkQtEkJdE{HrwAkaCrT{a@rpDiuHtE_KvLuV|{AwaDzAqCb@mAf{Ac`D~FqL~y@_fBlNmZbGaNtF}Mpn@s~AlYss@dFgK|DoGhBoCrDuE~AcBtGaGnByAnDwBnCwAfDwAnFaBjGkA~[{E`iEkn@pQaDvIwBnIiCl\\qLn}J{pDhMcGrFcDhGeEvoDehC|AsArCwChBaC`C_EzC_HbBcFd@uB`@qAn@gDdB}Kz@}Hn@iPjByx@jDcvAj@}RDsEn@yTv@a]VcPtEamFBcHT_LNkEdAiShDsi@`GudAbFgx@`@iKdP}yFhBgs@p@yRjCo_AJwCXeEb@uEz@_H|@yEnBqHrCiIpAmE`o@qhBxC_IjIuVdIcXh{AgmG`i@_{BfCuLrhAssGfFeXxbBklInCsN|_AoiGpGs_@pl@w}Czy@_kEvG{]h}@ieFbQehAdHye@lPagA|Eu\\tAmI|CwWjn@mwGj@eH|]azFl@kPjAqd@jJe|DlD}vAxAeh@@eBvVk}JzIkqDfE_aBfA{YbBk[zp@e}LhAaObCeUlAuIzAeJrb@q`CjCcOnAaIpBwOtBkTjDsg@~AiPvBwOlAcH|AkIlCkLlYudApDoN`BgHhBaJvAeIvAqJbAuHrBqQbAsLx@oL`MwrCXkFr@uJh@{FhBsOvXwoB|EqVdBmHxC}KtCcJtDgKjDoIxE}JdHcMdCuDdIoKlmB}|BjJuMfFgIlE{HlEyIdEeJ~FaOvCgInCuI`EmN`J}]rEsP`EuMzCoIxGwPpi@cnAhGgPzCiJvFmRrEwQbDyOtCoPbDwTxDq\\rAsK`BgLhB{KxBoLfCgLjDqKdBqEfEkJtSy^`EcJnDuJjAwDrCeK\\}AjCaNr@qEjAaJtNaqAdCqQ`BsItS}bAbQs{@|Kor@xBmKz}@}uDze@{zAjk@}fBjTsq@r@uCd@aDFyCIwCWcCY}Aq_@w|A{AwF_DyHgHwOgu@m_BSb@nFhL",
// levels:"B?@?????@?@???A???@?@????@??@????????@????@???A????@????@??@???@??@???A???@??@???A??@???@????A??@???@??@????@??@???@????@???@??A@?@???@????A????@??@?@???@???????@??@?@????@????@?A??@???@????@??@?A??????@???????@??A???@??@???@??@????@??@?@?????@?@?A?@????@???@??@??@????@?@??@?@??@??????@???@?@????@???B???@??@??????@??@???A?????@????@???A??@??????@??@??A?@???@???@??A????@???@???@????A????@@??A???@???@??@??A????@??????@??@???@???B????@?@????????@????@????A?????@????@??A???@???@???B???@?????@???@????@????@???A???????@??A@??@?@??@@?????A?@@????????@??@?A????@?????@???@???@???@???@?@?A???@??@?@??@???@?????@???A??@???????@????@???@????@????@@???A????@?@??@?B",
// numLevels:4,
// zoomFactor:16
//}]
//}
 
#region -- title --
int tooltipEnd = 0;
{
int x = route.IndexOf("tooltipHtml:") + 13;
if (x >= 13)
{
tooltipEnd = route.IndexOf("\"", x + 1);
if (tooltipEnd > 0)
{
int l = tooltipEnd - x;
if (l > 0)
{
tooltipHtml = route.Substring(x, l).Replace(@"\x26#160;", " ");
}
}
}
}
#endregion
 
#region -- points --
int pointsEnd = 0;
{
int x = route.IndexOf("points:", tooltipEnd >= 0 ? tooltipEnd : 0) + 8;
if (x >= 8)
{
pointsEnd = route.IndexOf("\"", x + 1);
if (pointsEnd > 0)
{
int l = pointsEnd - x;
if (l > 0)
{
/*
while(l % 5 != 0)
{
l--;
}
*/
 
points = new List<PointLatLng>();
DecodePointsInto(points, route.Substring(x, l));
}
}
}
}
#endregion
 
#region -- levels --
string levels = string.Empty;
int levelsEnd = 0;
{
int x = route.IndexOf("levels:", pointsEnd >= 0 ? pointsEnd : 0) + 8;
if (x >= 8)
{
levelsEnd = route.IndexOf("\"", x + 1);
if (levelsEnd > 0)
{
int l = levelsEnd - x;
if (l > 0)
{
levels = route.Substring(x, l);
}
}
}
}
#endregion
 
#region -- numLevel --
int numLevelsEnd = 0;
{
int x = route.IndexOf("numLevels:", levelsEnd >= 0 ? levelsEnd : 0) + 10;
if (x >= 10)
{
numLevelsEnd = route.IndexOf(",", x);
if (numLevelsEnd > 0)
{
int l = numLevelsEnd - x;
if (l > 0)
{
numLevel = int.Parse(route.Substring(x, l));
}
}
}
}
#endregion
 
#region -- zoomFactor --
{
int x = route.IndexOf("zoomFactor:", numLevelsEnd >= 0 ? numLevelsEnd : 0) + 11;
if (x >= 11)
{
int end = route.IndexOf("}", x);
if (end > 0)
{
int l = end - x;
if (l > 0)
{
zoomFactor = int.Parse(route.Substring(x, l));
}
}
}
}
#endregion
 
#region -- trim point overload --
if (points != null && numLevel > 0 && !string.IsNullOrEmpty(levels))
{
if (points.Count - levels.Length > 0)
{
points.RemoveRange(levels.Length, points.Count - levels.Length);
}
 
//http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/description.html
//
string allZlevels = "TSRPONMLKJIHGFEDCBA@?";
if (numLevel > allZlevels.Length)
{
numLevel = allZlevels.Length;
}
 
// used letters in levels string
string pLevels = allZlevels.Substring(allZlevels.Length - numLevel);
 
// remove useless points at zoom
{
List<PointLatLng> removedPoints = new List<PointLatLng>();
 
for (int i = 0; i < levels.Length; i++)
{
int zi = pLevels.IndexOf(levels [i]);
if (zi > 0)
{
if (zi * numLevel > zoom)
{
removedPoints.Add(points [i]);
}
}
}
 
foreach (var v in removedPoints)
{
points.Remove(v);
}
removedPoints.Clear();
removedPoints = null;
}
}
#endregion
}
}
catch (Exception ex)
{
points = null;
Debug.WriteLine("GetRoutePoints: " + ex);
}
return points;
}
 
static readonly string RouteUrlFormatPointLatLng = "http://maps.{6}/maps?f=q&output=dragdir&doflg=p&hl={0}{1}&q=&saddr=@{2},{3}&daddr=@{4},{5}";
static readonly string RouteUrlFormatStr = "http://maps.{4}/maps?f=q&output=dragdir&doflg=p&hl={0}{1}&q=&saddr=@{2}&daddr=@{3}";
 
static readonly string WalkingStr = "&mra=ls&dirflg=w";
static readonly string RouteWithoutHighwaysStr = "&mra=ls&dirflg=dh";
static readonly string RouteStr = "&mra=ls&dirflg=d";
 
#endregion
 
#endregion
 
#region GeocodingProvider Members
 
public GeoCoderStatusCode GetPoints(string keywords, out List<PointLatLng> pointList)
{
return GetLatLngFromGeocoderUrl(MakeGeocoderUrl(keywords, LanguageStr), out pointList);
}
 
public PointLatLng? GetPoint(string keywords, out GeoCoderStatusCode status)
{
List<PointLatLng> pointList;
status = GetPoints(keywords, out pointList);
return pointList != null && pointList.Count > 0 ? pointList [0] : (PointLatLng?)null;
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="placemark"></param>
/// <param name="pointList"></param>
/// <returns></returns>
public GeoCoderStatusCode GetPoints(Placemark placemark, out List<PointLatLng> pointList)
{
throw new NotImplementedException("use GetPoints(string keywords...");
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="placemark"></param>
/// <param name="status"></param>
/// <returns></returns>
public PointLatLng? GetPoint(Placemark placemark, out GeoCoderStatusCode status)
{
throw new NotImplementedException("use GetPoint(string keywords...");
}
 
public GeoCoderStatusCode GetPlacemarks(PointLatLng location, out List<Placemark> placemarkList)
{
return GetPlacemarkFromReverseGeocoderUrl(MakeReverseGeocoderUrl(location, LanguageStr), out placemarkList);
}
 
public Placemark? GetPlacemark(PointLatLng location, out GeoCoderStatusCode status)
{
List<Placemark> pointList;
status = GetPlacemarks(location, out pointList);
return pointList != null && pointList.Count > 0 ? pointList [0] : (Placemark?)null;
}
 
#region -- internals --
 
// The Coogle Geocoding API: http://tinyurl.com/cdlj889
 
string MakeGeocoderUrl(string keywords, string language)
{
return string.Format(CultureInfo.InvariantCulture, GeocoderUrlFormat, ServerAPIs, Uri.EscapeDataString(keywords).Replace(' ', '+'), language);
}
 
string MakeReverseGeocoderUrl(PointLatLng pt, string language)
{
return string.Format(CultureInfo.InvariantCulture, ReverseGeocoderUrlFormat, ServerAPIs, pt.Lat, pt.Lng, language);
}
 
GeoCoderStatusCode GetLatLngFromGeocoderUrl(string url, out List<PointLatLng> pointList)
{
var status = GeoCoderStatusCode.Unknow;
pointList = null;
 
try
{
string geo = GMaps.Instance.UseGeocoderCache ? Cache.Instance.GetContent(url, CacheType.GeocoderCache) : string.Empty;
 
bool cache = false;
 
if (string.IsNullOrEmpty(geo))
{
string urls = url;
 
// Must provide either API key or Maps for Work credentials.
if (!string.IsNullOrEmpty(ClientId))
{
urls = GetSignedUri(url);
}
else if (!string.IsNullOrEmpty(ApiKey))
{
urls += "&key=" + ApiKey;
}
 
geo = GetContentUsingHttp(urls);
 
if (!string.IsNullOrEmpty(geo))
{
cache = true;
}
}
 
if (!string.IsNullOrEmpty(geo))
{
if (geo.StartsWith("<?xml"))
{
#region -- xml response --
//<?xml version="1.0" encoding="UTF-8"?>
//<GeocodeResponse>
// <status>OK</status>
// <result>
// <type>locality</type>
// <type>political</type>
// <formatted_address>Vilnius, Lithuania</formatted_address>
// <address_component>
// <long_name>Vilnius</long_name>
// <short_name>Vilnius</short_name>
// <type>locality</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilniaus miesto savivaldyb??</long_name>
// <short_name>Vilniaus m. sav.</short_name>
// <type>administrative_area_level_2</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilnius County</long_name>
// <short_name>Vilnius County</short_name>
// <type>administrative_area_level_1</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Lithuania</long_name>
// <short_name>LT</short_name>
// <type>country</type>
// <type>political</type>
// </address_component>
// <geometry>
// <location>
// <lat>54.6871555</lat>
// <lng>25.2796514</lng>
// </location>
// <location_type>APPROXIMATE</location_type>
// <viewport>
// <southwest>
// <lat>54.5677980</lat>
// <lng>25.0243760</lng>
// </southwest>
// <northeast>
// <lat>54.8325440</lat>
// <lng>25.4814883</lng>
// </northeast>
// </viewport>
// <bounds>
// <southwest>
// <lat>54.5677980</lat>
// <lng>25.0243760</lng>
// </southwest>
// <northeast>
// <lat>54.8325440</lat>
// <lng>25.4814883</lng>
// </northeast>
// </bounds>
// </geometry>
// </result>
// <result>
// <type>airport</type>
// <type>transit_station</type>
// <type>establishment</type>
// <formatted_address>Vilnius International Airport (VNO), 10A, Vilnius, Lithuania</formatted_address>
// <address_component>
// <long_name>Vilnius International Airport</long_name>
// <short_name>Vilnius International Airport</short_name>
// <type>establishment</type>
// </address_component>
// <address_component>
// <long_name>10A</long_name>
// <short_name>10A</short_name>
// <type>street_number</type>
// </address_component>
// <address_component>
// <long_name>Vilnius</long_name>
// <short_name>Vilnius</short_name>
// <type>locality</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilniaus miesto savivaldyb??</long_name>
// <short_name>Vilniaus m. sav.</short_name>
// <type>administrative_area_level_2</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilnius County</long_name>
// <short_name>Vilnius County</short_name>
// <type>administrative_area_level_1</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Lithuania</long_name>
// <short_name>LT</short_name>
// <type>country</type>
// <type>political</type>
// </address_component>
// <geometry>
// <location>
// <lat>54.6369440</lat>
// <lng>25.2877780</lng>
// </location>
// <location_type>APPROXIMATE</location_type>
// <viewport>
// <southwest>
// <lat>54.6158331</lat>
// <lng>25.2723832</lng>
// </southwest>
// <northeast>
// <lat>54.6538331</lat>
// <lng>25.3034219</lng>
// </northeast>
// </viewport>
// <bounds>
// <southwest>
// <lat>54.6158331</lat>
// <lng>25.2723832</lng>
// </southwest>
// <northeast>
// <lat>54.6538331</lat>
// <lng>25.3034219</lng>
// </northeast>
// </bounds>
// </geometry>
// </result>
//</GeocodeResponse>
 
#endregion
 
XmlDocument doc = new XmlDocument();
doc.LoadXml(geo);
 
XmlNode nn = doc.SelectSingleNode("//status");
if (nn != null)
{
if (nn.InnerText != "OK")
{
Debug.WriteLine("GetLatLngFromGeocoderUrl: " + nn.InnerText);
}
else
{
status = GeoCoderStatusCode.G_GEO_SUCCESS;
 
if (cache && GMaps.Instance.UseGeocoderCache)
{
Cache.Instance.SaveContent(url, CacheType.GeocoderCache, geo);
}
 
pointList = new List<PointLatLng>();
 
XmlNodeList l = doc.SelectNodes("//result");
if (l != null)
{
foreach (XmlNode n in l)
{
nn = n.SelectSingleNode("geometry/location/lat");
if (nn != null)
{
double lat = double.Parse(nn.InnerText, CultureInfo.InvariantCulture);
 
nn = n.SelectSingleNode("geometry/location/lng");
if (nn != null)
{
double lng = double.Parse(nn.InnerText, CultureInfo.InvariantCulture);
pointList.Add(new PointLatLng(lat, lng));
}
}
}
}
}
}
}
}
}
catch (Exception ex)
{
status = GeoCoderStatusCode.ExceptionInCode;
Debug.WriteLine("GetLatLngFromGeocoderUrl: " + ex);
}
 
return status;
}
 
GeoCoderStatusCode GetPlacemarkFromReverseGeocoderUrl(string url, out List<Placemark> placemarkList)
{
GeoCoderStatusCode status = GeoCoderStatusCode.Unknow;
placemarkList = null;
 
try
{
string reverse = GMaps.Instance.UsePlacemarkCache ? Cache.Instance.GetContent(url, CacheType.PlacemarkCache) : string.Empty;
 
bool cache = false;
 
if (string.IsNullOrEmpty(reverse))
{
string urls = url;
 
// Must provide either API key or Maps for Work credentials.
if (!string.IsNullOrEmpty(ClientId))
{
urls = GetSignedUri(url);
}
else if (!string.IsNullOrEmpty(ApiKey))
{
urls += "&key=" + ApiKey;
}
 
reverse = GetContentUsingHttp(urls);
 
if (!string.IsNullOrEmpty(reverse))
{
cache = true;
}
}
 
if (!string.IsNullOrEmpty(reverse))
{
if (reverse.StartsWith("<?xml"))
{
#region -- xml response --
//<?xml version="1.0" encoding="UTF-8"?>
//<GeocodeResponse>
// <status>OK</status>
// <result>
// <type>street_address</type>
// <formatted_address>Tuskul??n?? gatv?? 2, Vilnius 09213, Lithuania</formatted_address>
// <address_component>
// <long_name>2</long_name>
// <short_name>2</short_name>
// <type>street_number</type>
// </address_component>
// <address_component>
// <long_name>Tuskul??n?? gatv??</long_name>
// <short_name>Tuskul??n?? g.</short_name>
// <type>route</type>
// </address_component>
// <address_component>
// <long_name>Vilnius</long_name>
// <short_name>Vilnius</short_name>
// <type>locality</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilniaus miesto savivaldyb??</long_name>
// <short_name>Vilniaus m. sav.</short_name>
// <type>administrative_area_level_2</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilnius County</long_name>
// <short_name>Vilnius County</short_name>
// <type>administrative_area_level_1</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Lithuania</long_name>
// <short_name>LT</short_name>
// <type>country</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>09213</long_name>
// <short_name>09213</short_name>
// <type>postal_code</type>
// </address_component>
// <geometry>
// <location>
// <lat>54.6963339</lat>
// <lng>25.2968939</lng>
// </location>
// <location_type>ROOFTOP</location_type>
// <viewport>
// <southwest>
// <lat>54.6949849</lat>
// <lng>25.2955449</lng>
// </southwest>
// <northeast>
// <lat>54.6976829</lat>
// <lng>25.2982429</lng>
// </northeast>
// </viewport>
// </geometry>
// </result>
// <result>
// <type>postal_code</type>
// <formatted_address>Vilnius 09213, Lithuania</formatted_address>
// <address_component>
// <long_name>09213</long_name>
// <short_name>09213</short_name>
// <type>postal_code</type>
// </address_component>
// <address_component>
// <long_name>Vilnius</long_name>
// <short_name>Vilnius</short_name>
// <type>locality</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilniaus miesto savivaldyb??</long_name>
// <short_name>Vilniaus m. sav.</short_name>
// <type>administrative_area_level_2</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilnius County</long_name>
// <short_name>Vilnius County</short_name>
// <type>administrative_area_level_1</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Lithuania</long_name>
// <short_name>LT</short_name>
// <type>country</type>
// <type>political</type>
// </address_component>
// <geometry>
// <location>
// <lat>54.6963032</lat>
// <lng>25.2967390</lng>
// </location>
// <location_type>APPROXIMATE</location_type>
// <viewport>
// <southwest>
// <lat>54.6950889</lat>
// <lng>25.2958851</lng>
// </southwest>
// <northeast>
// <lat>54.6977869</lat>
// <lng>25.2985830</lng>
// </northeast>
// </viewport>
// <bounds>
// <southwest>
// <lat>54.6956179</lat>
// <lng>25.2958871</lng>
// </southwest>
// <northeast>
// <lat>54.6972579</lat>
// <lng>25.2985810</lng>
// </northeast>
// </bounds>
// </geometry>
// </result>
// <result>
// <type>neighborhood</type>
// <type>political</type>
// <formatted_address>??irm??nai, Vilnius, Lithuania</formatted_address>
// <address_component>
// <long_name>??irm??nai</long_name>
// <short_name>??irm??nai</short_name>
// <type>neighborhood</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilnius</long_name>
// <short_name>Vilnius</short_name>
// <type>locality</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilniaus miesto savivaldyb??</long_name>
// <short_name>Vilniaus m. sav.</short_name>
// <type>administrative_area_level_2</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilnius County</long_name>
// <short_name>Vilnius County</short_name>
// <type>administrative_area_level_1</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Lithuania</long_name>
// <short_name>LT</short_name>
// <type>country</type>
// <type>political</type>
// </address_component>
// <geometry>
// <location>
// <lat>54.7117424</lat>
// <lng>25.2974345</lng>
// </location>
// <location_type>APPROXIMATE</location_type>
// <viewport>
// <southwest>
// <lat>54.6888939</lat>
// <lng>25.2838700</lng>
// </southwest>
// <northeast>
// <lat>54.7304441</lat>
// <lng>25.3133630</lng>
// </northeast>
// </viewport>
// <bounds>
// <southwest>
// <lat>54.6888939</lat>
// <lng>25.2838700</lng>
// </southwest>
// <northeast>
// <lat>54.7304441</lat>
// <lng>25.3133630</lng>
// </northeast>
// </bounds>
// </geometry>
// </result>
// <result>
// <type>administrative_area_level_3</type>
// <type>political</type>
// <formatted_address>??irm??n?? seni??nija, Lithuania</formatted_address>
// <address_component>
// <long_name>??irm??n?? seni??nija</long_name>
// <short_name>??irm??n?? sen.</short_name>
// <type>administrative_area_level_3</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilniaus miesto savivaldyb??</long_name>
// <short_name>Vilniaus m. sav.</short_name>
// <type>administrative_area_level_2</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilnius County</long_name>
// <short_name>Vilnius County</short_name>
// <type>administrative_area_level_1</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Lithuania</long_name>
// <short_name>LT</short_name>
// <type>country</type>
// <type>political</type>
// </address_component>
// <geometry>
// <location>
// <lat>54.7117424</lat>
// <lng>25.2974345</lng>
// </location>
// <location_type>APPROXIMATE</location_type>
// <viewport>
// <southwest>
// <lat>54.6892135</lat>
// <lng>25.2837150</lng>
// </southwest>
// <northeast>
// <lat>54.7305878</lat>
// <lng>25.3135630</lng>
// </northeast>
// </viewport>
// <bounds>
// <southwest>
// <lat>54.6892135</lat>
// <lng>25.2837150</lng>
// </southwest>
// <northeast>
// <lat>54.7305878</lat>
// <lng>25.3135630</lng>
// </northeast>
// </bounds>
// </geometry>
// </result>
// <result>
// <type>locality</type>
// <type>political</type>
// <formatted_address>Vilnius, Lithuania</formatted_address>
// <address_component>
// <long_name>Vilnius</long_name>
// <short_name>Vilnius</short_name>
// <type>locality</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilniaus miesto savivaldyb??</long_name>
// <short_name>Vilniaus m. sav.</short_name>
// <type>administrative_area_level_2</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilnius County</long_name>
// <short_name>Vilnius County</short_name>
// <type>administrative_area_level_1</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Lithuania</long_name>
// <short_name>LT</short_name>
// <type>country</type>
// <type>political</type>
// </address_component>
// <geometry>
// <location>
// <lat>54.6871555</lat>
// <lng>25.2796514</lng>
// </location>
// <location_type>APPROXIMATE</location_type>
// <viewport>
// <southwest>
// <lat>54.5677980</lat>
// <lng>25.0243760</lng>
// </southwest>
// <northeast>
// <lat>54.8325440</lat>
// <lng>25.4814883</lng>
// </northeast>
// </viewport>
// <bounds>
// <southwest>
// <lat>54.5677980</lat>
// <lng>25.0243760</lng>
// </southwest>
// <northeast>
// <lat>54.8325440</lat>
// <lng>25.4814883</lng>
// </northeast>
// </bounds>
// </geometry>
// </result>
// <result>
// <type>administrative_area_level_2</type>
// <type>political</type>
// <formatted_address>Vilniaus miesto savivaldyb??, Lithuania</formatted_address>
// <address_component>
// <long_name>Vilniaus miesto savivaldyb??</long_name>
// <short_name>Vilniaus m. sav.</short_name>
// <type>administrative_area_level_2</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Vilnius County</long_name>
// <short_name>Vilnius County</short_name>
// <type>administrative_area_level_1</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Lithuania</long_name>
// <short_name>LT</short_name>
// <type>country</type>
// <type>political</type>
// </address_component>
// <geometry>
// <location>
// <lat>54.6759715</lat>
// <lng>25.2867413</lng>
// </location>
// <location_type>APPROXIMATE</location_type>
// <viewport>
// <southwest>
// <lat>54.5677980</lat>
// <lng>25.0243760</lng>
// </southwest>
// <northeast>
// <lat>54.8325440</lat>
// <lng>25.4814883</lng>
// </northeast>
// </viewport>
// <bounds>
// <southwest>
// <lat>54.5677980</lat>
// <lng>25.0243760</lng>
// </southwest>
// <northeast>
// <lat>54.8325440</lat>
// <lng>25.4814883</lng>
// </northeast>
// </bounds>
// </geometry>
// </result>
// <result>
// <type>administrative_area_level_1</type>
// <type>political</type>
// <formatted_address>Vilnius County, Lithuania</formatted_address>
// <address_component>
// <long_name>Vilnius County</long_name>
// <short_name>Vilnius County</short_name>
// <type>administrative_area_level_1</type>
// <type>political</type>
// </address_component>
// <address_component>
// <long_name>Lithuania</long_name>
// <short_name>LT</short_name>
// <type>country</type>
// <type>political</type>
// </address_component>
// <geometry>
// <location>
// <lat>54.8086502</lat>
// <lng>25.2182138</lng>
// </location>
// <location_type>APPROXIMATE</location_type>
// <viewport>
// <southwest>
// <lat>54.1276599</lat>
// <lng>24.3863751</lng>
// </southwest>
// <northeast>
// <lat>55.5174369</lat>
// <lng>26.7602130</lng>
// </northeast>
// </viewport>
// <bounds>
// <southwest>
// <lat>54.1276599</lat>
// <lng>24.3863751</lng>
// </southwest>
// <northeast>
// <lat>55.5174369</lat>
// <lng>26.7602130</lng>
// </northeast>
// </bounds>
// </geometry>
// </result>
// <result>
// <type>country</type>
// <type>political</type>
// <formatted_address>Lithuania</formatted_address>
// <address_component>
// <long_name>Lithuania</long_name>
// <short_name>LT</short_name>
// <type>country</type>
// <type>political</type>
// </address_component>
// <geometry>
// <location>
// <lat>55.1694380</lat>
// <lng>23.8812750</lng>
// </location>
// <location_type>APPROXIMATE</location_type>
// <viewport>
// <southwest>
// <lat>53.8968787</lat>
// <lng>20.9543679</lng>
// </southwest>
// <northeast>
// <lat>56.4503209</lat>
// <lng>26.8355913</lng>
// </northeast>
// </viewport>
// <bounds>
// <southwest>
// <lat>53.8968787</lat>
// <lng>20.9543679</lng>
// </southwest>
// <northeast>
// <lat>56.4503209</lat>
// <lng>26.8355913</lng>
// </northeast>
// </bounds>
// </geometry>
// </result>
//</GeocodeResponse>
 
#endregion
 
XmlDocument doc = new XmlDocument();
doc.LoadXml(reverse);
 
XmlNode nn = doc.SelectSingleNode("//status");
if (nn != null)
{
if (nn.InnerText != "OK")
{
Debug.WriteLine("GetPlacemarkFromReverseGeocoderUrl: " + nn.InnerText);
}
else
{
status = GeoCoderStatusCode.G_GEO_SUCCESS;
 
if (cache && GMaps.Instance.UsePlacemarkCache)
{
Cache.Instance.SaveContent(url, CacheType.PlacemarkCache, reverse);
}
 
placemarkList = new List<Placemark>();
 
#region -- placemarks --
XmlNodeList l = doc.SelectNodes("//result");
if (l != null)
{
foreach (XmlNode n in l)
{
Debug.WriteLine("---------------------");
 
nn = n.SelectSingleNode("formatted_address");
if (nn != null)
{
var ret = new Placemark(nn.InnerText);
 
Debug.WriteLine("formatted_address: [" + nn.InnerText + "]");
 
nn = n.SelectSingleNode("type");
if (nn != null)
{
Debug.WriteLine("type: " + nn.InnerText);
}
 
// TODO: fill Placemark details
 
XmlNodeList acl = n.SelectNodes("address_component");
foreach (XmlNode ac in acl)
{
nn = ac.SelectSingleNode("type");
if (nn != null)
{
var type = nn.InnerText;
Debug.Write(" - [" + type + "], ");
 
nn = ac.SelectSingleNode("long_name");
if (nn != null)
{
Debug.WriteLine("long_name: [" + nn.InnerText + "]");
 
switch (type)
{
case "street_address":
{
ret.StreetNumber = nn.InnerText;
}
break;
 
case "route":
{
ret.ThoroughfareName = nn.InnerText;
}
break;
 
case "postal_code":
{
ret.PostalCodeNumber = nn.InnerText;
}
break;
 
case "country":
{
ret.CountryName = nn.InnerText;
}
break;
 
case "locality":
{
ret.LocalityName = nn.InnerText;
}
break;
 
case "administrative_area_level_2":
{
ret.DistrictName = nn.InnerText;
}
break;
 
case "administrative_area_level_1":
{
ret.AdministrativeAreaName = nn.InnerText;
}
break;
 
case "administrative_area_level_3":
{
ret.SubAdministrativeAreaName = nn.InnerText;
}
break;
 
case "neighborhood":
{
ret.Neighborhood = nn.InnerText;
}
break;
}
}
}
}
 
placemarkList.Add(ret);
}
}
}
#endregion
}
}
#endregion
}
}
}
catch (Exception ex)
{
status = GeoCoderStatusCode.ExceptionInCode;
placemarkList = null;
Debug.WriteLine("GetPlacemarkReverseGeocoderUrl: " + ex.ToString());
}
 
return status;
}
 
static readonly string ReverseGeocoderUrlFormat = "http://maps.{0}/maps/api/geocode/xml?latlng={1},{2}&language={3}&sensor=false";
static readonly string GeocoderUrlFormat = "http://maps.{0}/maps/api/geocode/xml?address={1}&language={2}&sensor=false";
 
#endregion
 
#region DirectionsProvider Members
 
public DirectionsStatusCode GetDirections(out GDirections direction, PointLatLng start, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
return GetDirectionsUrl(MakeDirectionsUrl(start, end, LanguageStr, avoidHighways, avoidTolls, walkingMode, sensor, metric), out direction);
}
 
public DirectionsStatusCode GetDirections(out GDirections direction, string start, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
return GetDirectionsUrl(MakeDirectionsUrl(start, end, LanguageStr, avoidHighways, avoidTolls, walkingMode, sensor, metric), out direction);
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="status"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="avoidHighways"></param>
/// <param name="avoidTolls"></param>
/// <param name="walkingMode"></param>
/// <param name="sensor"></param>
/// <param name="metric"></param>
/// <returns></returns>
public IEnumerable<GDirections> GetDirections(out DirectionsStatusCode status, string start, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
// TODO: add alternative directions
 
throw new NotImplementedException();
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="status"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="avoidHighways"></param>
/// <param name="avoidTolls"></param>
/// <param name="walkingMode"></param>
/// <param name="sensor"></param>
/// <param name="metric"></param>
/// <returns></returns>
public IEnumerable<GDirections> GetDirections(out DirectionsStatusCode status, PointLatLng start, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
// TODO: add alternative directions
 
throw new NotImplementedException();
}
 
public DirectionsStatusCode GetDirections(out GDirections direction, PointLatLng start, IEnumerable<PointLatLng> wayPoints, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
return GetDirectionsUrl(MakeDirectionsUrl(start, wayPoints, end, LanguageStr, avoidHighways, avoidTolls, walkingMode, sensor, metric), out direction);
}
 
public DirectionsStatusCode GetDirections(out GDirections direction, string start, IEnumerable<string> wayPoints, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
return GetDirectionsUrl(MakeDirectionsUrl(start, wayPoints, end, LanguageStr, avoidHighways, avoidTolls, walkingMode, sensor, metric), out direction);
}
 
#region -- internals --
 
// The Coogle Directions API: http://tinyurl.com/6vv4cac
 
string MakeDirectionsUrl(PointLatLng start, PointLatLng end, string language, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
string av = (avoidHighways ? "&avoid=highways" : string.Empty) + (avoidTolls ? "&avoid=tolls" : string.Empty); // 6
string mt = "&units=" + (metric ? "metric" : "imperial"); // 7
string wk = "&mode=" + (walkingMode ? "walking" : "driving"); // 8
 
return string.Format(CultureInfo.InvariantCulture, DirectionUrlFormatPoint, start.Lat, start.Lng, end.Lat, end.Lng, sensor.ToString().ToLower(), language, av, mt, wk, ServerAPIs);
}
 
string MakeDirectionsUrl(string start, string end, string language, bool avoidHighways, bool walkingMode, bool avoidTolls, bool sensor, bool metric)
{
string av = (avoidHighways ? "&avoid=highways" : string.Empty) + (avoidTolls ? "&avoid=tolls" : string.Empty); // 4
string mt = "&units=" + (metric ? "metric" : "imperial"); // 5
string wk = "&mode=" + (walkingMode ? "walking" : "driving"); // 6
 
return string.Format(DirectionUrlFormatStr, start.Replace(' ', '+'), end.Replace(' ', '+'), sensor.ToString().ToLower(), language, av, mt, wk, ServerAPIs);
}
 
string MakeDirectionsUrl(PointLatLng start, IEnumerable<PointLatLng> wayPoints, PointLatLng end, string language, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
string av = (avoidHighways ? "&avoid=highways" : string.Empty) + (avoidTolls ? "&avoid=tolls" : string.Empty); // 6
string mt = "&units=" + (metric ? "metric" : "imperial"); // 7
string wk = "&mode=" + (walkingMode ? "walking" : "driving"); // 8
 
string wpLatLng = string.Empty;
int i = 0;
foreach (var wp in wayPoints)
{
wpLatLng += string.Format(CultureInfo.InvariantCulture, i++ == 0 ? "{0},{1}" : "|{0},{1}", wp.Lat, wp.Lng);
}
 
return string.Format(CultureInfo.InvariantCulture, DirectionUrlFormatWaypoint, start.Lat, start.Lng, wpLatLng, sensor.ToString().ToLower(), language, av, mt, wk, ServerAPIs, end.Lat, end.Lng);
}
 
string MakeDirectionsUrl(string start, IEnumerable<string> wayPoints, string end, string language, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric)
{
string av = (avoidHighways ? "&avoid=highways" : string.Empty) + (avoidTolls ? "&avoid=tolls" : string.Empty); // 6
string mt = "&units=" + (metric ? "metric" : "imperial"); // 7
string wk = "&mode=" + (walkingMode ? "walking" : "driving"); // 8
 
string wpLatLng = string.Empty;
int i = 0;
foreach (var wp in wayPoints)
{
wpLatLng += string.Format(CultureInfo.InvariantCulture, i++ == 0 ? "{0}" : "|{0}", wp.Replace(' ', '+'));
}
 
return string.Format(CultureInfo.InvariantCulture, DirectionUrlFormatWaypointStr, start.Replace(' ', '+'), wpLatLng, sensor.ToString().ToLower(), language, av, mt, wk, ServerAPIs, end.Replace(' ', '+'));
}
 
DirectionsStatusCode GetDirectionsUrl(string url, out GDirections direction)
{
DirectionsStatusCode ret = DirectionsStatusCode.UNKNOWN_ERROR;
direction = null;
 
try
{
string kml = GMaps.Instance.UseDirectionsCache ? Cache.Instance.GetContent(url, CacheType.DirectionsCache) : string.Empty;
 
bool cache = false;
 
if (string.IsNullOrEmpty(kml))
{
string urls = url;
 
// Must provide either API key or Maps for Work credentials.
if (!string.IsNullOrEmpty(ClientId))
{
urls = GetSignedUri(url);
}
else if (!string.IsNullOrEmpty(ApiKey))
{
urls += "&key=" + ApiKey;
}
 
kml = GetContentUsingHttp(urls);
 
if (!string.IsNullOrEmpty(kml))
{
cache = true;
}
}
 
if (!string.IsNullOrEmpty(kml))
{
#region -- kml response --
//<?xml version="1.0" encoding="UTF-8"?>
//<DirectionsResponse>
// <status>OK</status>
// <route>
// <summary>A1/E85</summary>
// <leg>
// <step>
// <travel_mode>DRIVING</travel_mode>
// <start_location>
// <lat>54.6893800</lat>
// <lng>25.2800500</lng>
// </start_location>
// <end_location>
// <lat>54.6907800</lat>
// <lng>25.2798000</lng>
// </end_location>
// <polyline>
// <points>soxlIiohyCYLkCJ}@Vs@?</points>
// </polyline>
// <duration>
// <value>32</value>
// <text>1 min</text>
// </duration>
// <html_instructions>Head &lt;b&gt;north&lt;/b&gt; on &lt;b&gt;Vilniaus gatvė&lt;/b&gt; toward &lt;b&gt;Tilto gatvė&lt;/b&gt;</html_instructions>
// <distance>
// <value>157</value>
// <text>0.2 km</text>
// </distance>
// </step>
// <step>
// <travel_mode>DRIVING</travel_mode>
// <start_location>
// <lat>54.6907800</lat>
// <lng>25.2798000</lng>
// </start_location>
// <end_location>
// <lat>54.6942500</lat>
// <lng>25.2621300</lng>
// </end_location>
// <polyline>
// <points>kxxlIwmhyCmApUF`@GvAYpD{@dGcCjIoIvOuAhDwAtEa@vBUnDAhB?~AThDRxAh@hBtAdC</points>
// </polyline>
// <duration>
// <value>133</value>
// <text>2 mins</text>
// </duration>
// <html_instructions>Turn &lt;b&gt;left&lt;/b&gt; onto &lt;b&gt;A. Goštauto gatvė&lt;/b&gt;</html_instructions>
// <distance>
// <value>1326</value>
// <text>1.3 km</text>
// </distance>
// </step>
// <step>
// <travel_mode>DRIVING</travel_mode>
// <start_location>
// <lat>54.6942500</lat>
// <lng>25.2621300</lng>
// </start_location>
// <end_location>
// <lat>54.6681200</lat>
// <lng>25.2377500</lng>
// </end_location>
// <polyline>
// <points>anylIi_eyC`AwD~@oBLKr@K`U|FdF|@`J^~E[j@Lh@\hB~Bn@tBZhBLrC?zIJ~DzA~OVrELlG^lDdAtDh@hAfApA`EzCvAp@jUpIpAl@bBpAdBpBxA|BdLpV`BxClAbBhBlBbChBpBhAdAXjBHlE_@t@?|@Lt@X</points>
// </polyline>
// <duration>
// <value>277</value>
// <text>5 mins</text>
// </duration>
// <html_instructions>Turn &lt;b&gt;left&lt;/b&gt; to merge onto &lt;b&gt;Geležinio Vilko gatvė&lt;/b&gt;</html_instructions>
// <distance>
// <value>3806</value>
// <text>3.8 km</text>
// </distance>
// </step>
// <step>
// <travel_mode>DRIVING</travel_mode>
// <start_location>
// <lat>54.6681200</lat>
// <lng>25.2377500</lng>
// </start_location>
// <end_location>
// <lat>54.6584100</lat>
// <lng>25.1411300</lng>
// </end_location>
// <polyline>
// <points>wjtlI}f`yC~FhBlFr@jD|A~EbC~VjNxBbBdA`BnvA|zCba@l`Bt@tDTbBJpBBfBMvDaAzF}bBjiF{HnXiHxZ</points>
// </polyline>
// <duration>
// <value>539</value>
// <text>9 mins</text>
// </duration>
// <html_instructions>Continue onto &lt;b&gt;Savanorių prospektas&lt;/b&gt;</html_instructions>
// <distance>
// <value>8465</value>
// <text>8.5 km</text>
// </distance>
// </step>
// <step>
// <travel_mode>DRIVING</travel_mode>
// <start_location>
// <lat>54.6584100</lat>
// <lng>25.1411300</lng>
// </start_location>
// <end_location>
// <lat>54.9358200</lat>
// <lng>23.9260000</lng>
// </end_location>
// <polyline>
// <points>anrlIakmxCiq@|qCuBbLcK~n@wUrkAcPnw@gCnPoQt}AoB`MuAdHmAdFoCtJqClImBxE{DrIkQ|ZcEvIkDzIcDhKyBxJ{EdXuCtS_G`g@mF|\eF`WyDhOiE~NiErMaGpOoj@ppAoE|K_EzKeDtKkEnOsLnd@mDzLgI~U{FrNsEvJoEtI_FpI{J`O_EjFooBf_C{GdJ_FjIsH`OoFhMwH`UcDtL{CzMeDlQmAzHuU~bBiArIwApNaBfWaLfiCoBpYsDf\qChR_FlVqEpQ_ZbfA}CfN{A~HwCtRiAfKmBlVwBx[gBfRcBxMaLdp@sXrzAaE~UqCzRyC`[_q@z|LgC|e@m@vNqp@b}WuLraFo@jPaS~bDmJryAeo@v|G}CnWsm@~`EoKvo@kv@lkEkqBrlKwBvLkNj|@cu@`~EgCnNuiBpcJakAx|GyB`KqdC~fKoIfYicAxtCiDrLu@hDyBjQm@xKoGdxBmQhoGuUn|Dc@nJ[`OW|VaEn|Ee@`X</points>
// </polyline>
// <duration>
// <value>3506</value>
// <text>58 mins</text>
// </duration>
// <html_instructions>Continue onto &lt;b&gt;A1/E85&lt;/b&gt;</html_instructions>
// <distance>
// <value>85824</value>
// <text>85.8 km</text>
// </distance>
// </step>
// <step>
// <travel_mode>DRIVING</travel_mode>
// <start_location>
// <lat>54.9358200</lat>
// <lng>23.9260000</lng>
// </start_location>
// <end_location>
// <lat>54.9376500</lat>
// <lng>23.9195600</lng>
// </end_location>
// <polyline>
// <points>{shnIo``qCQ^MnD[lBgA`DqBdEu@xB}@zJCjB</points>
// </polyline>
// <duration>
// <value>39</value>
// <text>1 min</text>
// </duration>
// <html_instructions>Take the exit toward &lt;b&gt;Senamiestis/Aleksotas&lt;/b&gt;</html_instructions>
// <distance>
// <value>476</value>
// <text>0.5 km</text>
// </distance>
// </step>
// <step>
// <travel_mode>DRIVING</travel_mode>
// <start_location>
// <lat>54.9376500</lat>
// <lng>23.9195600</lng>
// </start_location>
// <end_location>
// <lat>54.9361300</lat>
// <lng>23.9189700</lng>
// </end_location>
// <polyline>
// <points>i_inIgx~pCnHtB</points>
// </polyline>
// <duration>
// <value>28</value>
// <text>1 min</text>
// </duration>
// <html_instructions>Turn &lt;b&gt;left&lt;/b&gt; onto &lt;b&gt;Kleboniškio gatvė&lt;/b&gt;</html_instructions>
// <distance>
// <value>173</value>
// <text>0.2 km</text>
// </distance>
// </step>
// <step>
// <travel_mode>DRIVING</travel_mode>
// <start_location>
// <lat>54.9361300</lat>
// <lng>23.9189700</lng>
// </start_location>
// <end_location>
// <lat>54.9018900</lat>
// <lng>23.8937000</lng>
// </end_location>
// <polyline>
// <points>yuhnIqt~pCvAb@JLrOvExSdHvDdAv`@pIpHnAdl@hLdB`@nDvAtEjDdCvCjLzOvAzBhC`GpHfRbQd^`JpMPt@ClA</points>
// </polyline>
// <duration>
// <value>412</value>
// <text>7 mins</text>
// </duration>
// <html_instructions>Continue onto &lt;b&gt;Jonavos gatvė&lt;/b&gt;</html_instructions>
// <distance>
// <value>4302</value>
// <text>4.3 km</text>
// </distance>
// </step>
// <step>
// <travel_mode>DRIVING</travel_mode>
// <start_location>
// <lat>54.9018900</lat>
// <lng>23.8937000</lng>
// </start_location>
// <end_location>
// <lat>54.8985600</lat>
// <lng>23.8933400</lng>
// </end_location>
// <polyline>
// <points>y_bnIsvypCMf@FnARlAf@zAl@^v@EZ_@pAe@x@k@xBPpA@pAQNSf@oB</points>
// </polyline>
// <duration>
// <value>69</value>
// <text>1 min</text>
// </duration>
// <html_instructions>At the roundabout, take the &lt;b&gt;3rd&lt;/b&gt; exit and stay on &lt;b&gt;Jonavos gatvė&lt;/b&gt;</html_instructions>
// <distance>
// <value>478</value>
// <text>0.5 km</text>
// </distance>
// </step>
// <step>
// <travel_mode>DRIVING</travel_mode>
// <start_location>
// <lat>54.8985600</lat>
// <lng>23.8933400</lng>
// </start_location>
// <end_location>
// <lat>54.8968500</lat>
// <lng>23.8930000</lng>
// </end_location>
// <polyline>
// <points>_kanIktypCbEx@pCH</points>
// </polyline>
// <duration>
// <value>38</value>
// <text>1 min</text>
// </duration>
// <html_instructions>Turn &lt;b&gt;right&lt;/b&gt; onto &lt;b&gt;A. Mapu gatvė&lt;/b&gt;&lt;div style=&quot;font-size:0.9em&quot;&gt;Destination will be on the right&lt;/div&gt;</html_instructions>
// <distance>
// <value>192</value>
// <text>0.2 km</text>
// </distance>
// </step>
// <duration>
// <value>5073</value>
// <text>1 hour 25 mins</text>
// </duration>
// <distance>
// <value>105199</value>
// <text>105 km</text>
// </distance>
// <start_location>
// <lat>54.6893800</lat>
// <lng>25.2800500</lng>
// </start_location>
// <end_location>
// <lat>54.8968500</lat>
// <lng>23.8930000</lng>
// </end_location>
// <start_address>Vilnius, Lithuania</start_address>
// <end_address>Kaunas, Lithuania</end_address>
// </leg>
// <copyrights>Map data ©2011 Tele Atlas</copyrights>
// <overview_polyline>
// <points>soxlIiohyCYL}Fb@mApUF`@GvAYpD{@dGcCjIoIvOwBpFy@xC]jBSxCC~E^~Er@lCtAdC`AwD~@oB`AW`U|FdF|@`J^~E[tAj@hB~BjA~ELrCJzOzA~Od@`N^lDdAtDt@xAjAnApDlCbXbKpAl@bBpAdBpBxA|BdLpV`BxCvDpEbChBpBhAdAXjBHbG_@|@LtHbClFr@jK`F~VjNxBbB`@h@rwAt|Cba@l`BjAxGNxEMvDaAzF}bBjiFcFbQ_y@|gD{CxMeBnJcK~n@wh@dkCkAlIoQt}AeEfV}EzQqClImBxE{DrIkQ|ZcEvIkDzIcDhKyBxJ{EdXuCtS_G`g@mF|\eF`WyDhOiE~NiErMaGpOoj@ppAoE|K_EzKeDtKmXzbAgI~U{FrNsEvJoLfT{J`O_EjFooBf_C{GdJkLtSwI`SyClI}CrJcDtL{CzMeDlQcXzlBiArIwApNaBfWaLfiCoBpYsDf\qChR_FlVqEpQ_ZbfAyFfXwCtRiAfKeFfs@gBfRcBxMaLdp@sXrzAaE~UqCzRyC`[_q@z|LuDtu@qp@b}WuLraFo@jPo^r}Faq@pfHaBtMsm@~`EoKvo@kv@lkEcuBjzKkNj|@cu@`~EgCnNuiBpcJakAx|GyB`KqdC~fKoIfYidAbwCoD|MeAbHcA|Im@xK}YnhKyV~gEs@~f@aEn|Ee@`XQ^MnD[lBoF`N}@zJCjBfKxCJLdj@bQv`@pIpHnAdl@hLdB`@nDvAtEjDdCvCbOvSzLhZbQd^`JpMPt@QtBFnAz@hDl@^j@?f@e@pAe@x@k@xBPfCEf@Uj@wBbEx@pCH</points>
// </overview_polyline>
// <bounds>
// <southwest>
// <lat>54.6389500</lat>
// <lng>23.8920900</lng>
// </southwest>
// <northeast>
// <lat>54.9376500</lat>
// <lng>25.2800500</lng>
// </northeast>
// </bounds>
// </route>
//</DirectionsResponse>
#endregion
 
XmlDocument doc = new XmlDocument();
doc.LoadXml(kml);
 
XmlNode nn = doc.SelectSingleNode("/DirectionsResponse/status");
if (nn != null)
{
ret = (DirectionsStatusCode)Enum.Parse(typeof(DirectionsStatusCode), nn.InnerText, false);
if (ret == DirectionsStatusCode.OK)
{
if (cache && GMaps.Instance.UseDirectionsCache)
{
Cache.Instance.SaveContent(url, CacheType.DirectionsCache, kml);
}
 
direction = new GDirections();
 
nn = doc.SelectSingleNode("/DirectionsResponse/route/summary");
if (nn != null)
{
direction.Summary = nn.InnerText;
Debug.WriteLine("summary: " + direction.Summary);
}
 
nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/duration");
if (nn != null)
{
var t = nn.SelectSingleNode("text");
if (t != null)
{
direction.Duration = t.InnerText;
Debug.WriteLine("duration: " + direction.Duration);
}
 
t = nn.SelectSingleNode("value");
if (t != null)
{
if (!string.IsNullOrEmpty(t.InnerText))
{
direction.DurationValue = uint.Parse(t.InnerText);
Debug.WriteLine("value: " + direction.DurationValue);
}
}
}
 
nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/distance");
if (nn != null)
{
var t = nn.SelectSingleNode("text");
if (t != null)
{
direction.Distance = t.InnerText;
Debug.WriteLine("distance: " + direction.Distance);
}
 
t = nn.SelectSingleNode("value");
if (t != null)
{
if (!string.IsNullOrEmpty(t.InnerText))
{
direction.DistanceValue = uint.Parse(t.InnerText);
Debug.WriteLine("value: " + direction.DistanceValue);
}
}
}
 
nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/start_location");
if (nn != null)
{
var pt = nn.SelectSingleNode("lat");
if (pt != null)
{
direction.StartLocation.Lat = double.Parse(pt.InnerText, CultureInfo.InvariantCulture);
}
 
pt = nn.SelectSingleNode("lng");
if (pt != null)
{
direction.StartLocation.Lng = double.Parse(pt.InnerText, CultureInfo.InvariantCulture);
}
}
 
nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/end_location");
if (nn != null)
{
var pt = nn.SelectSingleNode("lat");
if (pt != null)
{
direction.EndLocation.Lat = double.Parse(pt.InnerText, CultureInfo.InvariantCulture);
}
 
pt = nn.SelectSingleNode("lng");
if (pt != null)
{
direction.EndLocation.Lng = double.Parse(pt.InnerText, CultureInfo.InvariantCulture);
}
}
 
nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/start_address");
if (nn != null)
{
direction.StartAddress = nn.InnerText;
Debug.WriteLine("start_address: " + direction.StartAddress);
}
 
nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/end_address");
if (nn != null)
{
direction.EndAddress = nn.InnerText;
Debug.WriteLine("end_address: " + direction.EndAddress);
}
 
nn = doc.SelectSingleNode("/DirectionsResponse/route/copyrights");
if (nn != null)
{
direction.Copyrights = nn.InnerText;
Debug.WriteLine("copyrights: " + direction.Copyrights);
}
 
nn = doc.SelectSingleNode("/DirectionsResponse/route/overview_polyline/points");
if (nn != null)
{
direction.Route = new List<PointLatLng>();
DecodePointsInto(direction.Route, nn.InnerText);
}
 
XmlNodeList steps = doc.SelectNodes("/DirectionsResponse/route/leg/step");
if (steps != null)
{
if (steps.Count > 0)
{
direction.Steps = new List<GDirectionStep>();
}
 
foreach (XmlNode s in steps)
{
GDirectionStep step = new GDirectionStep();
 
Debug.WriteLine("----------------------");
nn = s.SelectSingleNode("travel_mode");
if (nn != null)
{
step.TravelMode = nn.InnerText;
Debug.WriteLine("travel_mode: " + step.TravelMode);
}
 
nn = s.SelectSingleNode("start_location");
if (nn != null)
{
var pt = nn.SelectSingleNode("lat");
if (pt != null)
{
step.StartLocation.Lat = double.Parse(pt.InnerText, CultureInfo.InvariantCulture);
}
 
pt = nn.SelectSingleNode("lng");
if (pt != null)
{
step.StartLocation.Lng = double.Parse(pt.InnerText, CultureInfo.InvariantCulture);
}
}
 
nn = s.SelectSingleNode("end_location");
if (nn != null)
{
var pt = nn.SelectSingleNode("lat");
if (pt != null)
{
step.EndLocation.Lat = double.Parse(pt.InnerText, CultureInfo.InvariantCulture);
}
 
pt = nn.SelectSingleNode("lng");
if (pt != null)
{
step.EndLocation.Lng = double.Parse(pt.InnerText, CultureInfo.InvariantCulture);
}
}
 
nn = s.SelectSingleNode("duration");
if (nn != null)
{
nn = nn.SelectSingleNode("text");
if (nn != null)
{
step.Duration = nn.InnerText;
Debug.WriteLine("duration: " + step.Duration);
}
}
 
nn = s.SelectSingleNode("distance");
if (nn != null)
{
nn = nn.SelectSingleNode("text");
if (nn != null)
{
step.Distance = nn.InnerText;
Debug.WriteLine("distance: " + step.Distance);
}
}
 
nn = s.SelectSingleNode("html_instructions");
if (nn != null)
{
step.HtmlInstructions = nn.InnerText;
Debug.WriteLine("html_instructions: " + step.HtmlInstructions);
}
 
nn = s.SelectSingleNode("polyline");
if (nn != null)
{
nn = nn.SelectSingleNode("points");
if (nn != null)
{
step.Points = new List<PointLatLng>();
DecodePointsInto(step.Points, nn.InnerText);
}
}
 
direction.Steps.Add(step);
}
}
}
}
}
}
catch (Exception ex)
{
direction = null;
ret = DirectionsStatusCode.ExceptionInCode;
Debug.WriteLine("GetDirectionsUrl: " + ex);
}
return ret;
}
 
static void DecodePointsInto(List<PointLatLng> path, string encodedPath)
{
// https://github.com/googlemaps/google-maps-services-java/blob/master/src/main/java/com/google/maps/internal/PolylineEncoding.java
int len = encodedPath.Length;
int index = 0;
int lat = 0;
int lng = 0;
while (index < len)
{
int result = 1;
int shift = 0;
int b;
do
{
b = encodedPath[index++] - 63 - 1;
result += b << shift;
shift += 5;
} while (b >= 0x1f && index < len);
lat += (result & 1) != 0 ? ~(result >> 1) : (result >> 1);
 
result = 1;
shift = 0;
 
if (index < len)
{
do
{
b = encodedPath[index++] - 63 - 1;
result += b << shift;
shift += 5;
} while (b >= 0x1f && index < len);
lng += (result & 1) != 0 ? ~(result >> 1) : (result >> 1);
}
 
path.Add(new PointLatLng(lat * 1e-5, lng * 1e-5));
}
}
 
static readonly string DirectionUrlFormatStr = "http://maps.{7}/maps/api/directions/xml?origin={0}&destination={1}&sensor={2}&language={3}{4}{5}{6}";
static readonly string DirectionUrlFormatPoint = "http://maps.{9}/maps/api/directions/xml?origin={0},{1}&destination={2},{3}&sensor={4}&language={5}{6}{7}{8}";
static readonly string DirectionUrlFormatWaypoint = "http://maps.{8}/maps/api/directions/xml?origin={0},{1}&waypoints={2}&destination={9},{10}&sensor={3}&language={4}{5}{6}{7}";
static readonly string DirectionUrlFormatWaypointStr = "http://maps.{7}/maps/api/directions/xml?origin={0}&waypoints={1}&destination={8}&sensor={2}&language={3}{4}{5}{6}";
 
#endregion
 
#endregion
 
#region -- Maps API for Work --
/// <summary>
/// https://developers.google.com/maps/documentation/business/webservices/auth#how_do_i_get_my_signing_key
/// To access the special features of the Google Maps API for Work you must provide a client ID
/// when accessing any of the API libraries or services.
/// When registering for Google Google Maps API for Work you will receive this client ID from Enterprise Support.
/// All client IDs begin with a gme- prefix. Your client ID is passed as the value of the client parameter.
/// Generally, you should store your private key someplace safe and read them into your code
/// </summary>
/// <param name="clientId"></param>
/// <param name="privateKey"></param>
public void SetEnterpriseCredentials(string clientId, string privateKey)
{
privateKey = privateKey.Replace("-", "+").Replace("_", "/");
_privateKeyBytes = Convert.FromBase64String(privateKey);
_clientId = clientId;
}
private byte[] _privateKeyBytes;
 
private string _clientId = string.Empty;
 
/// <summary>
/// Your client ID. To access the special features of the Google Maps API for Work
/// you must provide a client ID when accessing any of the API libraries or services.
/// When registering for Google Google Maps API for Work you will receive this client ID
/// from Enterprise Support. All client IDs begin with a gme- prefix.
/// </summary>
public string ClientId
{
get
{
return _clientId;
}
}
 
string GetSignedUri(Uri uri)
{
var builder = new UriBuilder(uri);
builder.Query = builder.Query.Substring(1) + "&client=" + _clientId;
uri = builder.Uri;
string signature = GetSignature(uri);
 
return uri.Scheme + "://" + uri.Host + uri.LocalPath + uri.Query + "&signature=" + signature;
}
 
string GetSignedUri(string url)
{
return GetSignedUri(new Uri(url));
}
 
string GetSignature(Uri uri)
{
byte[] encodedPathQuery = Encoding.ASCII.GetBytes(uri.LocalPath + uri.Query);
var hashAlgorithm = new HMACSHA1(_privateKeyBytes);
byte[] hashed = hashAlgorithm.ComputeHash(encodedPathQuery);
return Convert.ToBase64String(hashed).Replace("+", "-").Replace("/", "_");
}
#endregion
}
 
/// <summary>
/// GoogleMap provider
/// </summary>
public class GoogleMapProvider : GoogleMapProviderBase
{
public static readonly GoogleMapProvider Instance;
 
GoogleMapProvider()
{
}
 
static GoogleMapProvider()
{
Instance = new GoogleMapProvider();
}
 
public string Version = "m@365000000"; //"m@333000000";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("D7287DA0-A7FF-405F-8166-B6BAF26D066C");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty; // after &x=...
string sec2 = string.Empty; // after &zoom=...
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, language, pos.X, sec1, pos.Y, zoom, sec2, Server);
}
 
static readonly string UrlFormatServer = "mt";
static readonly string UrlFormatRequest = "vt";
static readonly string UrlFormat = "http://{0}{1}.{10}/maps/{2}/lyrs={3}&hl={4}&x={5}{6}&y={7}&z={8}&s={9}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/GoogleSatelliteMapProvider.cs
0,0 → 1,66

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// GoogleSatelliteMap provider
/// </summary>
public class GoogleSatelliteMapProvider : GoogleMapProviderBase
{
public static readonly GoogleSatelliteMapProvider Instance;
 
GoogleSatelliteMapProvider()
{
}
 
static GoogleSatelliteMapProvider()
{
Instance = new GoogleSatelliteMapProvider();
}
 
public string Version = "701";//"192";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("9CB89D76-67E9-47CF-8137-B9EE9FC46388");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleSatelliteMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty; // after &x=...
string sec2 = string.Empty; // after &zoom=...
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, language, pos.X, sec1, pos.Y, zoom, sec2, Server);
}
 
static readonly string UrlFormatServer = "khm";
static readonly string UrlFormatRequest = "kh";
static readonly string UrlFormat = "http://{0}{1}.{10}/{2}/v={3}&hl={4}&x={5}{6}&y={7}&z={8}&s={9}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/GoogleTerrainMapProvider.cs
0,0 → 1,66

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// GoogleTerrainMap provider
/// </summary>
public class GoogleTerrainMapProvider : GoogleMapProviderBase
{
public static readonly GoogleTerrainMapProvider Instance;
 
GoogleTerrainMapProvider()
{
}
 
static GoogleTerrainMapProvider()
{
Instance = new GoogleTerrainMapProvider();
}
 
public string Version = "t@365,r@365000000"; // "t@132,r@333000000";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("A42EDF2E-63C5-4967-9DBF-4EFB3AF7BC11");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleTerrainMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty; // after &x=...
string sec2 = string.Empty; // after &zoom=...
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, language, pos.X, sec1, pos.Y, zoom, sec2, Server);
}
 
static readonly string UrlFormatServer = "mt";
static readonly string UrlFormatRequest = "vt";
static readonly string UrlFormat = "http://{0}{1}.{10}/maps/{2}/lyrs={3}&hl={4}&x={5}{6}&y={7}&z={8}&s={9}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/Korea/GoogleKoreaHybridMapProvider.cs
0,0 → 1,79

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// GoogleKoreaHybridMap provider
/// </summary>
public class GoogleKoreaHybridMapProvider : GoogleMapProviderBase
{
public static readonly GoogleKoreaHybridMapProvider Instance;
 
GoogleKoreaHybridMapProvider()
{
}
 
static GoogleKoreaHybridMapProvider()
{
Instance = new GoogleKoreaHybridMapProvider();
}
 
public string Version = "kr1t.12";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("41A91842-04BC-442B-9AC8-042156238A5B");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleKoreaHybridMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { GoogleKoreaSatelliteMapProvider.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty;
string sec2 = string.Empty;
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, language, pos.X, sec1, pos.Y, zoom, sec2, ServerKorea);
}
 
static readonly string UrlFormatServer = "mt";
static readonly string UrlFormatRequest = "mt";
static readonly string UrlFormat = "http://{0}{1}.{10}/{2}/v={3}&hl={4}&x={5}{6}&y={7}&z={8}&s={9}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/Korea/GoogleKoreaMapProvider.cs
0,0 → 1,67

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// GoogleKoreaMap provider
/// </summary>
public class GoogleKoreaMapProvider : GoogleMapProviderBase
{
public static readonly GoogleKoreaMapProvider Instance;
 
GoogleKoreaMapProvider()
{
Area = new RectLatLng(38.6597777307125, 125.738525390625, 4.02099609375, 4.42072406219614);
}
 
static GoogleKoreaMapProvider()
{
Instance = new GoogleKoreaMapProvider();
}
 
public string Version = "kr1.12";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("0079D360-CB1B-4986-93D5-AD299C8E20E6");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleKoreaMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty;
string sec2 = string.Empty;
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, language, pos.X, sec1, pos.Y, zoom, sec2, ServerKorea);
}
 
static readonly string UrlFormatServer = "mt";
static readonly string UrlFormatRequest = "mt";
static readonly string UrlFormat = "http://{0}{1}.{10}/{2}/v={3}&hl={4}&x={5}{6}&y={7}&z={8}&s={9}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Google/Korea/GoogleKoreaSatelliteMapProvider.cs
0,0 → 1,66

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// GoogleKoreaSatelliteMap provider
/// </summary>
public class GoogleKoreaSatelliteMapProvider : GoogleMapProviderBase
{
public static readonly GoogleKoreaSatelliteMapProvider Instance;
 
GoogleKoreaSatelliteMapProvider()
{
}
 
static GoogleKoreaSatelliteMapProvider()
{
Instance = new GoogleKoreaSatelliteMapProvider();
}
 
public string Version = "170";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("70370941-D70C-4123-BE4A-AEE6754047F5");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "GoogleKoreaSatelliteMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
string sec1 = string.Empty;
string sec2 = string.Empty;
GetSecureWords(pos, out sec1, out sec2);
 
return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, language, pos.X, sec1, pos.Y, zoom, sec2, ServerKoreaKr);
}
 
static readonly string UrlFormatServer = "khm";
static readonly string UrlFormatRequest = "kh";
static readonly string UrlFormat = "http://{0}{1}.{10}/{2}/v={3}&hl={4}&x={5}{6}&y={7}&z={8}&s={9}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Lithuania/Lithuania3dMapProvider.cs
0,0 → 1,65

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// Lithuania3dMap (2.5d) provider
/// </summary>
public class Lithuania3dMapProvider : LithuaniaMapProviderBase
{
public static readonly Lithuania3dMapProvider Instance;
 
Lithuania3dMapProvider()
{
}
 
static Lithuania3dMapProvider()
{
Instance = new Lithuania3dMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("CCC5B65F-C8BC-47CE-B39D-5E262E6BF083");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "Lithuania 2.5d Map";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://dc1.maps.lt/cache/mapslt_25d_vkkp/map/_alllayers/L01/R00007194/C0000a481.png
int z = zoom;
if(zoom >= 10)
{
z -= 10;
}
 
return string.Format(UrlFormat, z, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://dc1.maps.lt/cache/mapslt_25d_vkkp/map/_alllayers/L{0:00}/R{1:x8}/C{2:x8}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Lithuania/LithuaniaHybridMapProvider.cs
0,0 → 1,73

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// LithuaniaHybridMap provider
/// </summary>
public class LithuaniaHybridMapProvider : LithuaniaMapProviderBase
{
public static readonly LithuaniaHybridMapProvider Instance;
 
LithuaniaHybridMapProvider()
{
}
 
static LithuaniaHybridMapProvider()
{
Instance = new LithuaniaHybridMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("279AB0E0-4704-4AA6-86AD-87D13B1F8975");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "LithuaniaHybridMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { LithuaniaOrtoFotoMapProvider.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://dc5.maps.lt/cache/mapslt_ortofoto_overlay/map/_alllayers/L09/R000016b1/C000020e1.jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
internal static readonly string UrlFormat = "http://dc5.maps.lt/cache/mapslt_ortofoto_overlay/map/_alllayers/L{0:00}/R{1:x8}/C{2:x8}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Lithuania/LithuaniaHybridOldMapProvider.cs
0,0 → 1,57

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// LithuaniaHybridOldMap, from 2010 data, provider
/// </summary>
public class LithuaniaHybridOldMapProvider : LithuaniaMapProviderBase
{
public static readonly LithuaniaHybridOldMapProvider Instance;
 
LithuaniaHybridOldMapProvider()
{
}
 
static LithuaniaHybridOldMapProvider()
{
Instance = new LithuaniaHybridOldMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("35C5C685-E868-4AC7-97BE-10A9A37A81B5");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "LithuaniaHybridMapOld";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { LithuaniaOrtoFotoOldMapProvider.Instance, LithuaniaHybridMapProvider.Instance };
}
return overlays;
}
}
 
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Lithuania/LithuaniaMapProvider.cs
0,0 → 1,116

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
public abstract class LithuaniaMapProviderBase : GMapProvider
{
public LithuaniaMapProviderBase()
{
RefererUrl = "http://www.maps.lt/map/";
Copyright = string.Format("©{0} Hnit-Baltic - Map data ©{0} ESRI", DateTime.Today.Year);
MaxZoom = 12;
Area = new RectLatLng(56.431489960361, 20.8962105239809, 5.8924169643369, 2.58940626652217);
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return LKS94Projection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
}
 
/// <summary>
/// LithuaniaMap provider, http://www.maps.lt/map/
/// </summary>
public class LithuaniaMapProvider : LithuaniaMapProviderBase
{
public static readonly LithuaniaMapProvider Instance;
 
LithuaniaMapProvider()
{
}
 
static LithuaniaMapProvider()
{
Instance = new LithuaniaMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("5859079F-1B5E-484B-B05C-41CE664D8A93");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "LithuaniaMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://dc5.maps.lt/cache/mapslt/map/_alllayers/L08/R00000912/C00000d25.png
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://dc5.maps.lt/cache/mapslt/map/_alllayers/L{0:00}/R{1:x8}/C{2:x8}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Lithuania/LithuaniaOrtoFotoMapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// LithuaniaOrtoFotoMap provider
/// </summary>
public class LithuaniaOrtoFotoMapProvider : LithuaniaMapProviderBase
{
public static readonly LithuaniaOrtoFotoMapProvider Instance;
 
LithuaniaOrtoFotoMapProvider()
{
}
 
static LithuaniaOrtoFotoMapProvider()
{
Instance = new LithuaniaOrtoFotoMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("043FF9EF-612C-411F-943C-32C787A88D6A");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "LithuaniaOrtoFotoMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://dc5.maps.lt/cache/mapslt_ortofoto/map/_alllayers/L08/R00000914/C00000d28.jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://dc5.maps.lt/cache/mapslt_ortofoto/map/_alllayers/L{0:00}/R{1:x8}/C{2:x8}.jpg";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Lithuania/LithuaniaOrtoFotoOldMapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// LithuaniaOrtoFotoNewMap, from 2010 data, provider
/// </summary>
public class LithuaniaOrtoFotoOldMapProvider : LithuaniaMapProviderBase
{
public static readonly LithuaniaOrtoFotoOldMapProvider Instance;
 
LithuaniaOrtoFotoOldMapProvider()
{
}
 
static LithuaniaOrtoFotoOldMapProvider()
{
Instance = new LithuaniaOrtoFotoOldMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("C37A148E-0A7D-4123-BE4E-D0D3603BE46B");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "LithuaniaOrtoFotoMapOld";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://dc1.maps.lt/cache/mapslt_ortofoto_2010/map/_alllayers/L09/R000016b1/C000020e2.jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://dc1.maps.lt/cache/mapslt_ortofoto_2010/map/_alllayers/L{0:00}/R{1:x8}/C{2:x8}.jpg";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Lithuania/LithuaniaReliefMapProvider.cs
0,0 → 1,70

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
/// <summary>
/// LithuaniaReliefMap provider, http://www.maps.lt/map/
/// </summary>
public class LithuaniaReliefMapProvider : LithuaniaMapProviderBase
{
public static readonly LithuaniaReliefMapProvider Instance;
 
LithuaniaReliefMapProvider()
{
 
}
 
static LithuaniaReliefMapProvider()
{
Instance = new LithuaniaReliefMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("85F89205-1062-4F10-B536-90CD8B2F1B7D");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "LithuaniaReliefMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureProjection Projection
{
get
{
return LKS94rProjection.Instance;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://dc5.maps.lt/cache/mapslt_relief_vector/map/_alllayers/L09/R00001892/C000020df.jpg
 
return string.Format(UrlFormat, zoom, pos.Y, pos.X);
}
 
static readonly string UrlFormat = "http://dc5.maps.lt/cache/mapslt_relief_vector/map/_alllayers/L{0:00}/R{1:x8}/C{2:x8}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Lithuania/LithuaniaTOP50.cs
0,0 → 1,67

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
public class LithuaniaTOP50 : GMapProvider
{
public static readonly LithuaniaTOP50 Instance;
 
LithuaniaTOP50()
{
MaxZoom = 15;
}
 
static LithuaniaTOP50()
{
Instance = new LithuaniaTOP50();
}
 
#region GMapProvider Members
 
Guid id = new Guid("2920B1AF-6D57-4895-9A21-D5837CBF1049");
public override Guid Id
{
get
{
return id;
}
}
 
public override string Name
{
get
{
return "LithuaniaTOP50";
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if (overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
return null;
}
#endregion
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/NearMap/NearHybridMapProvider.cs
0,0 → 1,74

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// NearHybridMap provider - http://www.nearmap.com/
/// </summary>
public class NearHybridMapProvider : NearMapProviderBase
{
public static readonly NearHybridMapProvider Instance;
 
NearHybridMapProvider()
{
}
 
static NearHybridMapProvider()
{
Instance = new NearHybridMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("4BF8819A-635D-4A94-8DC7-94C0E0F04BFD");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "NearHybridMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { NearSatelliteMapProvider.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://web1.nearmap.com/maps/hl=en&x=37&y=19&z=6&nml=MapT&nmg=1&s=2KbhmZZ
// http://web1.nearmap.com/maps/hl=en&x=36&y=19&z=6&nml=MapT&nmg=1&s=2YKWhQi
 
return string.Format(UrlFormat, GetServerNum(pos, 3), pos.X, pos.Y, zoom);
}
 
static readonly string UrlFormat = "http://web{0}.nearmap.com/maps/hl=en&x={1}&y={2}&z={3}&nml=MapT&nmg=1";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/NearMap/NearMapProvider.cs
0,0 → 1,184

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
using System.Net;
using System.Text;
 
/// <summary>
/// http://en.wikipedia.org/wiki/NearMap
/// nearmap originally allowed personal use of images for free for non-enterprise users.
/// However this free access ended in December 2012, when the company modified its business model to user-pay
/// </summary>
public abstract class NearMapProviderBase : GMapProvider
{
public NearMapProviderBase()
{
// credentials doesn't work ;/
//Credential = new NetworkCredential("greatmaps", "greatmaps");
//try ForceBasicHttpAuthentication(...);
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
 
public new static int GetServerNum(GPoint pos, int max)
{
// var hostNum=((opts.nodes!==0)?((tileCoords.x&2)%opts.nodes):0)+opts.nodeStart;
return (int)(pos.X & 2) % max;
}
 
static readonly string SecureStr = "Vk52edzNRYKbGjF8Ur0WhmQlZs4wgipDETyL1oOMXIAvqtxJBuf7H36acCnS9P";
 
public string GetSafeString(GPoint pos)
{
#region -- source --
/*
TileLayer.prototype.differenceEngine=function(s,a)
{
var offset=0,result="",alen=a.length,v,p;
for(var i=0; i<alen; i++)
{
v=parseInt(a.charAt(i),10);
if(!isNaN(v))
{
offset+=v;
p=s.charAt(offset%s.length);
result+=p
}
}
return result
};
TileLayer.prototype.getSafeString=function(x,y,nmd)
{
var arg=x.toString()+y.toString()+((3*x)+y).toString();
if(nmd)
{
arg+=nmd
}
return this.differenceEngine(TileLayer._substring,arg)
};
*/
#endregion
 
var arg = pos.X.ToString() + pos.Y.ToString() + ((3 * pos.X) + pos.Y).ToString();
 
string ret = "&s=";
int offset = 0;
for(int i = 0; i < arg.Length; i++)
{
offset += int.Parse(arg[i].ToString());
ret += SecureStr[offset % SecureStr.Length];
}
 
return ret;
}
}
 
/// <summary>
/// NearMap provider - http://www.nearmap.com/
/// </summary>
public class NearMapProvider : NearMapProviderBase
{
public static readonly NearMapProvider Instance;
 
NearMapProvider()
{
RefererUrl = "http://www.nearmap.com/";
}
 
static NearMapProvider()
{
Instance = new NearMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("E33803DF-22CB-4FFA-B8E3-15383ED9969D");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "NearMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://web1.nearmap.com/maps/hl=en&x=18681&y=10415&z=15&nml=Map_&nmg=1&s=kY8lZssipLIJ7c5
// http://web1.nearmap.com/kh/v=nm&hl=en&x=20&y=8&z=5&nml=Map_&s=55KUZ
//http://maps.au.nearmap.com/api/0/authentication/checkticket?nmf=json&return200=true&callback=jQuery110206126813754172529_1431499242400&_=1431499242401
//jQuery110206126813754172529_1431499242400({"IncidentId":null,"AccountContext":{"AccountId":"account2574457","Username":"demo"},"Result":{"Ticket":{"Ticket":"1637726D061CB8B8A28BC98064443C96FB07008C16531B2F5100F98B9EBFE69C4083C88C920D3BF4C0768A27ADE9ECADF324A380DBF80C3C0982DC83374FE8EBF0F70868735351FC7","Expires":"\/Date(1432103400000)\/","CookieName":"nearmap_web3_app"},"Status":"Ok","Username":"demo","AccountId":"account2574457"}})
// http://web1.au.nearmap.com/maps/hl=en&x=1855837&y=1265913&z=21&nml=V&httpauth=false&version=2
// http://web2.au.nearmap.com/maps/hl=en&x=231977&y=158238&z=18&nml=Dem&httpauth=false&version=2
return string.Format(UrlFormat, GetServerNum(pos, 3), pos.X, pos.Y, zoom, GetSafeString(pos));
}
 
static readonly string UrlFormat = "http://web{0}.nearmap.com/kh/v=nm&hl=en&x={1}&y={2}&z={3}&nml=Map_{4}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/NearMap/NearSatelliteMapProvider.cs
0,0 → 1,63

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// NearSatelliteMap provider - http://www.nearmap.com/
/// </summary>
public class NearSatelliteMapProvider : NearMapProviderBase
{
public static readonly NearSatelliteMapProvider Instance;
 
NearSatelliteMapProvider()
{
}
 
static NearSatelliteMapProvider()
{
Instance = new NearSatelliteMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("56D00148-05B7-408D-8F7A-8D7250FF8121");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "NearSatelliteMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://web2.nearmap.com/maps/hl=en&x=14&y=8&z=5&nml=Vert&s=kdj00
// http://web2.nearmap.com/maps/hl=en&x=6&y=4&z=4&nml=Vert
// http://web2.nearmap.com/maps/hl=en&x=3&y=1&z=3&nml=Vert&s=2edd
// http://web0.nearmap.com/maps/hl=en&x=69&y=39&z=7&nml=Vert&s=z80wiTM
 
return string.Format(UrlFormat, GetServerNum(pos, 4), pos.X, pos.Y, zoom, GetSafeString(pos));
}
 
static readonly string UrlFormat = "http://web{0}.nearmap.com/maps/hl=en&x={1}&y={2}&z={3}&nml=Vert{4}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenCycleLandscapeMapProvider.cs
0,0 → 1,74

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OpenCycleMap Landscape provider - http://www.opencyclemap.org
/// </summary>
public class OpenCycleLandscapeMapProvider : OpenStreetMapProviderBase
{
public static readonly OpenCycleLandscapeMapProvider Instance;
 
OpenCycleLandscapeMapProvider()
{
RefererUrl = "http://www.opencyclemap.org/";
}
 
static OpenCycleLandscapeMapProvider()
{
Instance = new OpenCycleLandscapeMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("BDBAA939-6597-4D87-8F4F-261C49E35F56");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenCycleLandscapeMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
char letter = ServerLetters[GMapProvider.GetServerNum(pos, 3)];
return string.Format(UrlFormat, letter, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://{0}.tile3.opencyclemap.org/landscape/{1}/{2}/{3}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenCycleMapProvider.cs
0,0 → 1,73

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OpenCycleMap provider - http://www.opencyclemap.org
/// </summary>
public class OpenCycleMapProvider : OpenStreetMapProviderBase
{
public static readonly OpenCycleMapProvider Instance;
 
OpenCycleMapProvider()
{
RefererUrl = "http://www.opencyclemap.org/";
}
 
static OpenCycleMapProvider()
{
Instance = new OpenCycleMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("D7E1826E-EE1E-4441-9F15-7C2DE0FE0B0A");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenCycleMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
char letter = ServerLetters[GMapProvider.GetServerNum(pos, 3)];
return string.Format(UrlFormat, letter, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://{0}.tile.opencyclemap.org/cycle/{1}/{2}/{3}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenCycleTransportMapProvider.cs
0,0 → 1,73

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OpenCycleMap Transport provider - http://www.opencyclemap.org
/// </summary>
public class OpenCycleTransportMapProvider : OpenStreetMapProviderBase
{
public static readonly OpenCycleTransportMapProvider Instance;
 
OpenCycleTransportMapProvider()
{
RefererUrl = "http://www.opencyclemap.org/";
}
 
static OpenCycleTransportMapProvider()
{
Instance = new OpenCycleTransportMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("AF66DF88-AD25-43A9-8F82-56FCA49A748A");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenCycleTransportMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
char letter = ServerLetters[GMapProvider.GetServerNum(pos, 3)];
return string.Format(UrlFormat, letter, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://{0}.tile2.opencyclemap.org/transport/{1}/{2}/{3}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenSeaMapHybridProvider.cs
0,0 → 1,72

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OpenSeaMapHybrid provider - http://openseamap.org
/// </summary>
public class OpenSeaMapHybridProvider : OpenStreetMapProviderBase
{
public static readonly OpenSeaMapHybridProvider Instance;
 
OpenSeaMapHybridProvider()
{
RefererUrl = "http://openseamap.org/";
}
 
static OpenSeaMapHybridProvider()
{
Instance = new OpenSeaMapHybridProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("FAACDE73-4B90-4AE6-BB4A-ADE4F3545592");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenSeaMapHybrid";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { OpenStreetMapProvider.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://tiles.openseamap.org/seamark/{0}/{1}/{2}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenStreet4UMapProvider.cs
0,0 → 1,79

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OpenStreet4UMap provider
/// http://www.4umaps.eu
///
/// 4UMaps are topographic outdoor maps based on OpenStreetmap data.
/// The map contains everything you need for any kind of back country activity like hiking,
/// mountain biking, cycling, climbing etc. 4UMaps has elevation lines, hill shading,
/// peak height and name, streets, ways, tracks and trails, as well as springs, supermarkets,
/// restaurants, hotels, shelters etc.
/// </summary>
public class OpenStreet4UMapProvider : OpenStreetMapProviderBase
{
public static readonly OpenStreet4UMapProvider Instance;
 
OpenStreet4UMapProvider()
{
RefererUrl = "http://www.4umaps.eu/map.htm";
Copyright = string.Format("© 4UMaps.eu, © OpenStreetMap - Map data ©{0} OpenStreetMap", DateTime.Today.Year);
}
 
static OpenStreet4UMapProvider()
{
Instance = new OpenStreet4UMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("3E3D919E-9814-4978-B430-6AAB2C1E41B2");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenStreet4UMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom);
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom)
{
return string.Format(UrlFormat, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://4umaps.eu/{0}/{1}/{2}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenStreetMapProvider.cs
0,0 → 1,547
 
namespace GMap.NET.MapProviders
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
using GMap.NET.Internals;
using GMap.NET.Projections;
 
public abstract class OpenStreetMapProviderBase : GMapProvider, RoutingProvider, GeocodingProvider
{
public OpenStreetMapProviderBase()
{
MaxZoom = null;
RefererUrl = "http://www.openstreetmap.org/";
Copyright = string.Format("© OpenStreetMap - Map data ©{0} OpenStreetMap", DateTime.Today.Year);
}
 
public readonly string ServerLetters = "abc";
public int MinExpectedRank = 0;
 
#region GMapProvider Members
 
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
public override GMapProvider[] Overlays
{
get
{
throw new NotImplementedException();
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
 
#endregion
 
#region GMapRoutingProvider Members
 
public MapRoute GetRoute(PointLatLng start, PointLatLng end, bool avoidHighways, bool walkingMode, int Zoom)
{
List<PointLatLng> points = GetRoutePoints(MakeRoutingUrl(start, end, walkingMode ? TravelTypeFoot : TravelTypeMotorCar));
MapRoute route = points != null ? new MapRoute(points, walkingMode ? WalkingStr : DrivingStr) : null;
return route;
}
 
/// <summary>
/// NotImplemented
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="avoidHighways"></param>
/// <param name="walkingMode"></param>
/// <param name="Zoom"></param>
/// <returns></returns>
public MapRoute GetRoute(string start, string end, bool avoidHighways, bool walkingMode, int Zoom)
{
throw new NotImplementedException("use GetRoute(PointLatLng start, PointLatLng end...");
}
 
#region -- internals --
string MakeRoutingUrl(PointLatLng start, PointLatLng end, string travelType)
{
return string.Format(CultureInfo.InvariantCulture, RoutingUrlFormat, start.Lat, start.Lng, end.Lat, end.Lng, travelType);
}
 
List<PointLatLng> GetRoutePoints(string url)
{
List<PointLatLng> points = null;
try
{
string route = GMaps.Instance.UseRouteCache ? Cache.Instance.GetContent(url, CacheType.RouteCache) : string.Empty;
if(string.IsNullOrEmpty(route))
{
route = GetContentUsingHttp(url);
if(!string.IsNullOrEmpty(route))
{
if(GMaps.Instance.UseRouteCache)
{
Cache.Instance.SaveContent(url, CacheType.RouteCache, route);
}
}
}
 
if(!string.IsNullOrEmpty(route))
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(route);
System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmldoc.NameTable);
xmlnsManager.AddNamespace("sm", "http://earth.google.com/kml/2.0");
 
///Folder/Placemark/LineString/coordinates
var coordNode = xmldoc.SelectSingleNode("/sm:kml/sm:Document/sm:Folder/sm:Placemark/sm:LineString/sm:coordinates", xmlnsManager);
 
string[] coordinates = coordNode.InnerText.Split('\n');
 
if(coordinates.Length > 0)
{
points = new List<PointLatLng>();
 
foreach(string coordinate in coordinates)
{
if(coordinate != string.Empty)
{
string[] XY = coordinate.Split(',');
if(XY.Length == 2)
{
double lat = double.Parse(XY[1], CultureInfo.InvariantCulture);
double lng = double.Parse(XY[0], CultureInfo.InvariantCulture);
points.Add(new PointLatLng(lat, lng));
}
}
}
}
}
}
catch(Exception ex)
{
Debug.WriteLine("GetRoutePoints: " + ex);
}
 
return points;
}
 
static readonly string RoutingUrlFormat = "http://www.yournavigation.org/api/1.0/gosmore.php?format=kml&flat={0}&flon={1}&tlat={2}&tlon={3}&v={4}&fast=1&layer=mapnik";
static readonly string TravelTypeFoot = "foot";
static readonly string TravelTypeMotorCar = "motorcar";
 
static readonly string WalkingStr = "Walking";
static readonly string DrivingStr = "Driving";
#endregion
 
#endregion
 
#region GeocodingProvider Members
 
public GeoCoderStatusCode GetPoints(string keywords, out List<PointLatLng> pointList)
{
// http://nominatim.openstreetmap.org/search?q=lithuania,vilnius&format=xml
 
#region -- response --
//<searchresults timestamp="Wed, 01 Feb 12 09:46:00 -0500" attribution="Data Copyright OpenStreetMap Contributors, Some Rights Reserved. CC-BY-SA 2.0." querystring="lithuania,vilnius" polygon="false" exclude_place_ids="29446018,53849547,8831058,29614806" more_url="http://open.mapquestapi.com/nominatim/v1/search?format=xml&exclude_place_ids=29446018,53849547,8831058,29614806&accept-language=en&q=lithuania%2Cvilnius">
//<place place_id="29446018" osm_type="way" osm_id="24598347" place_rank="30" boundingbox="54.6868133544922,54.6879043579102,25.2885360717773,25.2898139953613" lat="54.6873633486028" lon="25.289199818878" display_name="National Museum of Lithuania, 1, Arsenalo g., Senamiesčio seniūnija, YAHOO-HIRES-20080313, Vilnius County, Šalčininkų rajonas, Vilniaus apskritis, 01513, Lithuania" class="tourism" type="museum" icon="http://open.mapquestapi.com/nominatim/v1/images/mapicons/tourist_museum.p.20.png"/>
//<place place_id="53849547" osm_type="way" osm_id="55469274" place_rank="30" boundingbox="54.6896553039551,54.690486907959,25.2675743103027,25.2692089080811" lat="54.6900227236882" lon="25.2683589759401" display_name="Ministry of Foreign Affairs of the Republic of Lithuania, 2, J. Tumo Vaižganto g., Naujamiesčio seniūnija, Vilnius, Vilnius County, Vilniaus m. savivaldybė, Vilniaus apskritis, LT-01104, Lithuania" class="amenity" type="public_building"/>
//<place place_id="8831058" osm_type="node" osm_id="836234960" place_rank="30" boundingbox="54.6670935059,54.6870973206,25.2638857269,25.2838876343" lat="54.677095" lon="25.2738876" display_name="Railway Museum of Lithuania, 15, Mindaugo g., Senamiesčio seniūnija, Vilnius, Vilnius County, Vilniaus m. savivaldybė, Vilniaus apskritis, 03215, Lithuania" class="tourism" type="museum" icon="http://open.mapquestapi.com/nominatim/v1/images/mapicons/tourist_museum.p.20.png"/>
//<place place_id="29614806" osm_type="way" osm_id="24845629" place_rank="30" boundingbox="54.6904983520508,54.6920852661133,25.2606296539307,25.2628803253174" lat="54.6913385159005" lon="25.2617684209873" display_name="Seimas (Parliament) of the Republic of Lithuania, 53, Gedimino pr., Naujamiesčio seniūnija, Vilnius, Vilnius County, Vilniaus m. savivaldybė, Vilniaus apskritis, LT-01111, Lithuania" class="amenity" type="public_building"/>
//</searchresults>
#endregion
 
return GetLatLngFromGeocoderUrl(MakeGeocoderUrl(keywords), out pointList);
}
 
public PointLatLng? GetPoint(string keywords, out GeoCoderStatusCode status)
{
List<PointLatLng> pointList;
status = GetPoints(keywords, out pointList);
return pointList != null && pointList.Count > 0 ? pointList[0] : (PointLatLng?) null;
}
 
public GeoCoderStatusCode GetPoints(Placemark placemark, out List<PointLatLng> pointList)
{
// http://nominatim.openstreetmap.org/search?street=&city=vilnius&county=&state=&country=lithuania&postalcode=&format=xml
 
#region -- response --
//<searchresults timestamp="Thu, 29 Nov 12 08:38:23 +0000" attribution="Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright" querystring="vilnius, lithuania" polygon="false" exclude_place_ids="98093941" more_url="http://nominatim.openstreetmap.org/search?format=xml&exclude_place_ids=98093941&accept-language=de-de,de;q=0.8,en-us;q=0.5,en;q=0.3&q=vilnius%2C+lithuania">
//<place place_id="98093941" osm_type="relation" osm_id="1529146" place_rank="16" boundingbox="54.5693359375,54.8323097229004,25.0250644683838,25.4815216064453" lat="54.6843135" lon="25.2853984" display_name="Vilnius, Vilniaus m. savivaldybė, Distrikt Vilnius, Litauen" class="boundary" type="administrative" icon="http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png"/>
//</searchresults>
#endregion
 
return GetLatLngFromGeocoderUrl(MakeDetailedGeocoderUrl(placemark), out pointList);
}
 
public PointLatLng? GetPoint(Placemark placemark, out GeoCoderStatusCode status)
{
List<PointLatLng> pointList;
status = GetPoints(placemark, out pointList);
return pointList != null && pointList.Count > 0 ? pointList[0] : (PointLatLng?) null;
}
 
public GeoCoderStatusCode GetPlacemarks(PointLatLng location, out List<Placemark> placemarkList)
{
throw new NotImplementedException("use GetPlacemark");
}
 
public Placemark? GetPlacemark(PointLatLng location, out GeoCoderStatusCode status)
{
//http://nominatim.openstreetmap.org/reverse?format=xml&lat=52.5487429714954&lon=-1.81602098644987&zoom=18&addressdetails=1
 
#region -- response --
/*
<reversegeocode timestamp="Wed, 01 Feb 12 09:51:11 -0500" attribution="Data Copyright OpenStreetMap Contributors, Some Rights Reserved. CC-BY-SA 2.0." querystring="format=xml&lat=52.5487429714954&lon=-1.81602098644987&zoom=18&addressdetails=1">
<result place_id="2061235282" osm_type="way" osm_id="90394420" lat="52.5487800131654" lon="-1.81626922291265">
137, Pilkington Avenue, Castle Vale, City of Birmingham, West Midlands, England, B72 1LH, United Kingdom
</result>
<addressparts>
<house_number>
137
</house_number>
<road>
Pilkington Avenue
</road>
<suburb>
Castle Vale
</suburb>
<city>
City of Birmingham
</city>
<county>
West Midlands
</county>
<state_district>
West Midlands
</state_district>
<state>
England
</state>
<postcode>
B72 1LH
</postcode>
<country>
United Kingdom
</country>
<country_code>
gb
</country_code>
</addressparts>
</reversegeocode>
*/
 
#endregion
 
return GetPlacemarkFromReverseGeocoderUrl(MakeReverseGeocoderUrl(location), out status);
}
 
#region -- internals --
 
string MakeGeocoderUrl(string keywords)
{
return string.Format(GeocoderUrlFormat, keywords.Replace(' ', '+'));
}
 
string MakeDetailedGeocoderUrl(Placemark placemark)
{
var street = String.Join(" ", new[] { placemark.HouseNo, placemark.ThoroughfareName }).Trim();
return string.Format(GeocoderDetailedUrlFormat,
street.Replace(' ', '+'),
placemark.LocalityName.Replace(' ', '+'),
placemark.SubAdministrativeAreaName.Replace(' ', '+'),
placemark.AdministrativeAreaName.Replace(' ', '+'),
placemark.CountryName.Replace(' ', '+'),
placemark.PostalCodeNumber.Replace(' ', '+'));
}
 
string MakeReverseGeocoderUrl(PointLatLng pt)
{
return string.Format(CultureInfo.InvariantCulture, ReverseGeocoderUrlFormat, pt.Lat, pt.Lng);
}
 
GeoCoderStatusCode GetLatLngFromGeocoderUrl(string url, out List<PointLatLng> pointList)
{
var status = GeoCoderStatusCode.Unknow;
pointList = null;
 
try
{
string geo = GMaps.Instance.UseGeocoderCache ? Cache.Instance.GetContent(url, CacheType.GeocoderCache) : string.Empty;
 
bool cache = false;
 
if(string.IsNullOrEmpty(geo))
{
geo = GetContentUsingHttp(url);
 
if(!string.IsNullOrEmpty(geo))
{
cache = true;
}
}
 
if(!string.IsNullOrEmpty(geo))
{
if(geo.StartsWith("<?xml") && geo.Contains("<place"))
{
if(cache && GMaps.Instance.UseGeocoderCache)
{
Cache.Instance.SaveContent(url, CacheType.GeocoderCache, geo);
}
 
XmlDocument doc = new XmlDocument();
doc.LoadXml(geo);
{
XmlNodeList l = doc.SelectNodes("/searchresults/place");
if(l != null)
{
pointList = new List<PointLatLng>();
 
foreach(XmlNode n in l)
{
var nn = n.Attributes["place_rank"];
 
int rank = 0;
#if !PocketPC
if (nn != null && Int32.TryParse(nn.Value, out rank))
{
#else
if(nn != null && !string.IsNullOrEmpty(nn.Value))
{
rank = int.Parse(nn.Value, NumberStyles.Integer, CultureInfo.InvariantCulture);
#endif
if(rank < MinExpectedRank)
continue;
}
 
nn = n.Attributes["lat"];
if(nn != null)
{
double lat = double.Parse(nn.Value, CultureInfo.InvariantCulture);
 
nn = n.Attributes["lon"];
if(nn != null)
{
double lng = double.Parse(nn.Value, CultureInfo.InvariantCulture);
pointList.Add(new PointLatLng(lat, lng));
}
}
}
 
status = GeoCoderStatusCode.G_GEO_SUCCESS;
}
}
}
}
}
catch(Exception ex)
{
status = GeoCoderStatusCode.ExceptionInCode;
Debug.WriteLine("GetLatLngFromGeocoderUrl: " + ex);
}
 
return status;
}
 
Placemark? GetPlacemarkFromReverseGeocoderUrl(string url, out GeoCoderStatusCode status)
{
status = GeoCoderStatusCode.Unknow;
Placemark? ret = null;
 
try
{
string geo = GMaps.Instance.UsePlacemarkCache ? Cache.Instance.GetContent(url, CacheType.PlacemarkCache) : string.Empty;
 
bool cache = false;
 
if(string.IsNullOrEmpty(geo))
{
geo = GetContentUsingHttp(url);
 
if(!string.IsNullOrEmpty(geo))
{
cache = true;
}
}
 
if(!string.IsNullOrEmpty(geo))
{
if(geo.StartsWith("<?xml") && geo.Contains("<result"))
{
if(cache && GMaps.Instance.UsePlacemarkCache)
{
Cache.Instance.SaveContent(url, CacheType.PlacemarkCache, geo);
}
 
XmlDocument doc = new XmlDocument();
doc.LoadXml(geo);
{
XmlNode r = doc.SelectSingleNode("/reversegeocode/result");
if(r != null)
{
var p = new Placemark(r.InnerText);
 
XmlNode ad = doc.SelectSingleNode("/reversegeocode/addressparts");
if(ad != null)
{
var vl = ad.SelectSingleNode("country");
if(vl != null)
{
p.CountryName = vl.InnerText;
}
 
vl = ad.SelectSingleNode("country_code");
if(vl != null)
{
p.CountryNameCode = vl.InnerText;
}
 
vl = ad.SelectSingleNode("postcode");
if(vl != null)
{
p.PostalCodeNumber = vl.InnerText;
}
 
vl = ad.SelectSingleNode("state");
if(vl != null)
{
p.AdministrativeAreaName = vl.InnerText;
}
 
vl = ad.SelectSingleNode("region");
if(vl != null)
{
p.SubAdministrativeAreaName = vl.InnerText;
}
 
vl = ad.SelectSingleNode("suburb");
if(vl != null)
{
p.LocalityName = vl.InnerText;
}
 
vl = ad.SelectSingleNode("road");
if(vl != null)
{
p.ThoroughfareName = vl.InnerText;
}
}
 
ret = p;
 
status = GeoCoderStatusCode.G_GEO_SUCCESS;
}
}
}
}
}
catch(Exception ex)
{
ret = null;
status = GeoCoderStatusCode.ExceptionInCode;
Debug.WriteLine("GetPlacemarkFromReverseGeocoderUrl: " + ex);
}
 
return ret;
}
 
static readonly string ReverseGeocoderUrlFormat = "http://nominatim.openstreetmap.org/reverse?format=xml&lat={0}&lon={1}&zoom=18&addressdetails=1";
static readonly string GeocoderUrlFormat = "http://nominatim.openstreetmap.org/search?q={0}&format=xml";
static readonly string GeocoderDetailedUrlFormat = "http://nominatim.openstreetmap.org/search?street={0}&city={1}&county={2}&state={3}&country={4}&postalcode={5}&format=xml";
 
#endregion
 
#endregion
}
 
/// <summary>
/// OpenStreetMap provider - http://www.openstreetmap.org/
/// </summary>
public class OpenStreetMapProvider : OpenStreetMapProviderBase
{
public static readonly OpenStreetMapProvider Instance;
 
OpenStreetMapProvider()
{
}
 
static OpenStreetMapProvider()
{
Instance = new OpenStreetMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("0521335C-92EC-47A8-98A5-6FD333DDA9C0");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenStreetMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
char letter = ServerLetters[GetServerNum(pos, 3)];
return string.Format(UrlFormat, letter, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://{0}.tile.openstreetmap.org/{1}/{2}/{3}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenStreetMapQuestHybridProvider.cs
0,0 → 1,72

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OpenStreetMapQuestHybrid provider - http://wiki.openstreetmap.org/wiki/MapQuest
/// </summary>
public class OpenStreetMapQuestHybridProvider : OpenStreetMapProviderBase
{
public static readonly OpenStreetMapQuestHybridProvider Instance;
 
OpenStreetMapQuestHybridProvider()
{
Copyright = string.Format("© MapQuest - Map data ©{0} MapQuest, OpenStreetMap", DateTime.Today.Year);
}
 
static OpenStreetMapQuestHybridProvider()
{
Instance = new OpenStreetMapQuestHybridProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("95E05027-F846-4429-AB7A-9445ABEEFA2A");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenStreetMapQuestHybrid";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { OpenStreetMapQuestSatteliteProvider.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://otile{0}.mqcdn.com/tiles/1.0.0/hyb/{1}/{2}/{3}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenStreetMapQuestProvider.cs
0,0 → 1,72

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OpenStreetMapQuest provider - http://wiki.openstreetmap.org/wiki/MapQuest
/// </summary>
public class OpenStreetMapQuestProvider : OpenStreetMapProviderBase
{
public static readonly OpenStreetMapQuestProvider Instance;
 
OpenStreetMapQuestProvider()
{
Copyright = string.Format("© MapQuest - Map data ©{0} MapQuest, OpenStreetMap", DateTime.Today.Year);
}
 
static OpenStreetMapQuestProvider()
{
Instance = new OpenStreetMapQuestProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("D0A12840-973A-448B-B9C2-89B8A07DFF0F");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenStreetMapQuest";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://otile{0}.mqcdn.com/tiles/1.0.0/osm/{1}/{2}/{3}.png";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenStreetMapQuestSatteliteProvider.cs
0,0 → 1,72

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OpenStreetMapQuestSattelite provider - http://wiki.openstreetmap.org/wiki/MapQuest
/// </summary>
public class OpenStreetMapQuestSatteliteProvider : OpenStreetMapProviderBase
{
public static readonly OpenStreetMapQuestSatteliteProvider Instance;
 
OpenStreetMapQuestSatteliteProvider()
{
Copyright = string.Format("© MapQuest - Map data ©{0} MapQuest, OpenStreetMap", DateTime.Today.Year);
}
 
static OpenStreetMapQuestSatteliteProvider()
{
Instance = new OpenStreetMapQuestSatteliteProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("E590D3B1-37F4-442B-9395-ADB035627F67");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenStreetMapQuestSattelite";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, GetServerNum(pos, 3) + 1, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://otile{0}.mqcdn.com/tiles/1.0.0/sat/{1}/{2}/{3}.jpg";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenStreetMapSurferProvider.cs
0,0 → 1,78

namespace GMap.NET.MapProviders
{
using System;
 
#if OpenStreetMapSurfer
/// <summary>
/// OpenStreetMapSurfer provider
/// http://wiki.openstreetmap.org/wiki/MapSurfer.Net
///
/// Since May 2011 the service http://www.mapsurfer.net is unavailable due
/// to hosting problems.
/// </summary>
public class OpenStreetMapSurferProvider : OpenStreetMapProviderBase
{
public static readonly OpenStreetMapSurferProvider Instance;
 
OpenStreetMapSurferProvider()
{
RefererUrl = "http://www.mapsurfer.net/";
}
 
static OpenStreetMapSurferProvider()
{
Instance = new OpenStreetMapSurferProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("6282888B-2F01-4029-9CD8-0CFFCB043995");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenStreetMapSurfer";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, pos.X, pos.Y, zoom);
}
 
static readonly string UrlFormat = "http://tiles1.mapsurfer.net/tms_r.ashx?x={0}&y={1}&z={2}";
}
#endif
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenStreetMapSurferTerrainProvider.cs
0,0 → 1,74

namespace GMap.NET.MapProviders
{
using System;
 
#if OpenStreetMapSurfer
/// <summary>
/// OpenStreetMapSurferTerrain provider
/// </summary>
public class OpenStreetMapSurferTerrainProvider : OpenStreetMapProviderBase
{
public static readonly OpenStreetMapSurferTerrainProvider Instance;
 
OpenStreetMapSurferTerrainProvider()
{
RefererUrl = "http://www.mapsurfer.net/";
}
 
static OpenStreetMapSurferTerrainProvider()
{
Instance = new OpenStreetMapSurferTerrainProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("E87954A4-1852-4B64-95FA-24E512E4B021");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenStreetMapSurferTerrain";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, pos.X, pos.Y, zoom);
}
 
static readonly string UrlFormat = "http://tiles2.mapsurfer.net/tms_t.ashx?x={0}&y={1}&z={2}";
}
#endif
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/OpenStreetMap/OpenStreetOsmProvider.cs
0,0 → 1,80

namespace GMap.NET.MapProviders
{
using System;
 
#if OpenStreetOsm
/// <summary>
/// OpenStreetOsm provider
/// http://wiki.openstreetmap.org/wiki/Osmarender
///
/// Osmarender is a rule-based rendering tool for generating SVG images
/// of OSM data. Note that Osmarender has not been actively maintained
/// since March 2012 and was discontinued as a main Slippy Map layer on
/// openstreetmap.org around that time.
/// </summary>
public class OpenStreetOsmProvider : OpenStreetMapProviderBase
{
public static readonly OpenStreetOsmProvider Instance;
 
OpenStreetOsmProvider()
{
}
 
static OpenStreetOsmProvider()
{
Instance = new OpenStreetOsmProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("07EF8CBC-A91D-4B2F-8B2D-70DBE384EF18");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OpenStreetOsm";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, string.Empty);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
char letter = ServerLetters[GMapProvider.GetServerNum(pos, 3)];
return string.Format(UrlFormat, letter, zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://{0}.tah.openstreetmap.org/Tiles/tile/{1}/{2}/{3}.png";
}
#endif
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Ovi/OviHybridMapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OviHybridMap provider
/// </summary>
public class OviHybridMapProvider : OviMapProviderBase
{
public static readonly OviHybridMapProvider Instance;
 
OviHybridMapProvider()
{
}
 
static OviHybridMapProvider()
{
Instance = new OviHybridMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("B85A8FD2-40F4-40EE-9B45-491AA45D86C1");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OviHybridMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://c.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/hybrid.day/12/2316/1277/256/png8
 
return string.Format(UrlFormat, UrlServerLetters[GetServerNum(pos, 4)], zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://{0}.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/hybrid.day/{1}/{2}/{3}/256/png8";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Ovi/OviMapProvider.cs
0,0 → 1,117

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
 
public abstract class OviMapProviderBase : GMapProvider
{
public OviMapProviderBase()
{
MaxZoom = null;
RefererUrl = "http://maps.ovi.com/";
Copyright = string.Format("©{0} OVI Nokia - Map data ©{0} NAVTEQ, Imagery ©{0} DigitalGlobe", DateTime.Today.Year);
}
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
 
protected static readonly string UrlServerLetters = "bcde";
}
 
/// <summary>
/// OviMap provider
/// </summary>
public class OviMapProvider : OviMapProviderBase
{
public static readonly OviMapProvider Instance;
 
OviMapProvider()
{
}
 
static OviMapProvider()
{
Instance = new OviMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("30DC1083-AC4D-4471-A232-D8A67AC9373A");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OviMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://c.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/normal.day/12/2321/1276/256/png8
 
return string.Format(UrlFormat, UrlServerLetters[GetServerNum(pos, 4)], zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://{0}.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/normal.day/{1}/{2}/{3}/256/png8";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Ovi/OviSatelliteMapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OviSatelliteMap provider
/// </summary>
public class OviSatelliteMapProvider : OviMapProviderBase
{
public static readonly OviSatelliteMapProvider Instance;
 
OviSatelliteMapProvider()
{
}
 
static OviSatelliteMapProvider()
{
Instance = new OviSatelliteMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("6696CE12-7694-4073-BC48-79EE849F2563");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OviSatelliteMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://b.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/satellite.day/12/2313/1275/256/png8
 
return string.Format(UrlFormat, UrlServerLetters[GetServerNum(pos, 4)], zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://{0}.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/satellite.day/{1}/{2}/{3}/256/png8";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Ovi/OviTerrainMapProvider.cs
0,0 → 1,60

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// OviTerrainMap provider
/// </summary>
public class OviTerrainMapProvider : OviMapProviderBase
{
public static readonly OviTerrainMapProvider Instance;
 
OviTerrainMapProvider()
{
}
 
static OviTerrainMapProvider()
{
Instance = new OviTerrainMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("7267339C-445E-4E61-B8B8-82D0B7AAACC5");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "OviTerrainMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://d.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/terrain.day/12/2317/1277/256/png8
 
return string.Format(UrlFormat, UrlServerLetters[GetServerNum(pos, 4)], zoom, pos.X, pos.Y);
}
 
static readonly string UrlFormat = "http://{0}.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/terrain.day/{1}/{2}/{3}/256/png8";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Yahoo/YahooHybridMapProvider.cs
0,0 → 1,75

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// YahooHybridMap provider
/// </summary>
public class YahooHybridMapProvider : YahooMapProviderBase
{
public static readonly YahooHybridMapProvider Instance;
 
YahooHybridMapProvider()
{
}
 
static YahooHybridMapProvider()
{
Instance = new YahooHybridMapProvider();
}
 
public string Version = "4.3";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("A084E0DB-F9A6-45C1-BC2F-791E1F4E958E");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "YahooHybridMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { YahooSatelliteMapProvider.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://maps1.yimg.com/hx/tl?b=1&v=4.3&t=h&.intl=en&x=14&y=5&z=7&r=1
 
return string.Format(UrlFormat, ((GetServerNum(pos, 2)) + 1), Version, language, pos.X, (((1 << zoom) >> 1) - 1 - pos.Y), (zoom + 1));
}
 
static readonly string UrlFormat = "http://maps{0}.yimg.com/hx/tl?v={1}&t=h&.intl={2}&x={3}&y={4}&z={5}&r=1";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Yahoo/YahooMapProvider.cs
0,0 → 1,427
 
namespace GMap.NET.MapProviders
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
using GMap.NET.Internals;
using GMap.NET.Projections;
 
public abstract class YahooMapProviderBase : GMapProvider, GeocodingProvider
{
public YahooMapProviderBase()
{
RefererUrl = "http://maps.yahoo.com/";
Copyright = string.Format("© Yahoo! Inc. - Map data & Imagery ©{0} NAVTEQ", DateTime.Today.Year);
}
 
public string AppId = string.Empty;
public int MinExpectedQuality = 39;
 
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjection.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
 
#region GeocodingProvider Members
 
public GeoCoderStatusCode GetPoints(string keywords, out List<PointLatLng> pointList)
{
// http://where.yahooapis.com/geocode?q=lithuania,vilnius&appid=1234&flags=CG&gflags=QL&locale=LT-lt
 
#region -- response --
//<ResultSet version="1.0"><Error>0</Error><ErrorMessage>No error</ErrorMessage><Locale>LT-lt</Locale><Quality>40</Quality><Found>1</Found><Result><quality>40</quality><latitude>54.689850</latitude><longitude>25.269260</longitude><offsetlat>54.689850</offsetlat><offsetlon>25.269260</offsetlon><radius>46100</radius></Result></ResultSet>
#endregion
 
return GetLatLngFromGeocoderUrl(MakeGeocoderUrl(keywords), out pointList);
}
 
public PointLatLng? GetPoint(string keywords, out GeoCoderStatusCode status)
{
List<PointLatLng> pointList;
status = GetPoints(keywords, out pointList);
return pointList != null && pointList.Count > 0 ? pointList[0] : (PointLatLng?)null;
}
 
public GeoCoderStatusCode GetPoints(Placemark placemark, out List<PointLatLng> pointList)
{
// http://where.yahooapis.com/geocode?country=LT&state=Vilniaus+Apskritis&county=Vilniaus+Miesto+Savivaldybe&city=Vilnius&neighborhood=Naujamiestis&postal=01108&street=J.+Tumo-Vaizganto+Gatve&house=2&appid=1234&flags=CG&gflags=QL&locale=LT-lt
 
#region -- response --
//<ResultSet version="1.0"><Error>0</Error><ErrorMessage>No error</ErrorMessage><Locale>LT-lt</Locale><Quality>19</Quality><Found>1</Found><Result><quality>87</quality><latitude>54.690181</latitude><longitude>25.269483</longitude><offsetlat>54.690227</offsetlat><offsetlon>25.269278</offsetlon><radius>500</radius></Result></ResultSet>
#endregion
 
return GetLatLngFromGeocoderUrl(MakeGeocoderDetailedUrl(placemark), out pointList);
}
 
public PointLatLng? GetPoint(Placemark placemark, out GeoCoderStatusCode status)
{
List<PointLatLng> pointList;
status = GetPoints(placemark, out pointList);
return pointList != null && pointList.Count > 0 ? pointList[0] : (PointLatLng?)null;
}
 
public GeoCoderStatusCode GetPlacemarks(PointLatLng location, out List<Placemark> placemarkList)
{
// http://where.yahooapis.com/geocode?q=54.689850,25.269260&appid=1234&flags=G&gflags=QRL&locale=LT-lt
 
#region -- response --
//<ResultSet version="1.0"><Error>0</Error><ErrorMessage>No error</ErrorMessage><Locale>LT-lt</Locale><Quality>99</Quality><Found>1</Found><Result><quality>99</quality><latitude>54.689850</latitude><longitude>25.269260</longitude><offsetlat>54.689850</offsetlat><offsetlon>25.269260</offsetlon><radius>500</radius><name>54.689850,25.269260</name><line1>2 J. Tumo-Vaizganto Gatve</line1><line2>01108 Naujamiestis</line2><line3/><line4>Lietuvos Respublika</line4><house>2</house><street>J. Tumo-Vaizganto Gatve</street><xstreet/><unittype/><unit/><postal>01108</postal><level4>Naujamiestis</level4><level3>Vilnius</level3><level2>Vilniaus Miesto Savivaldybe</level2><level1>Vilniaus Apskritis</level1><level0>Lietuvos Respublika</level0><level0code>LT</level0code><level1code/><level2code/><hash/><woeid>12758362</woeid><woetype>11</woetype><uzip>01108</uzip></Result></ResultSet>
#endregion
 
return GetPlacemarksFromReverseGeocoderUrl(MakeReverseGeocoderUrl(location), out placemarkList);
}
 
public Placemark ? GetPlacemark(PointLatLng location, out GeoCoderStatusCode status)
{
List<Placemark> placemarkList;
status = GetPlacemarks(location, out placemarkList);
return placemarkList != null && placemarkList.Count > 0 ? placemarkList[0] : (Placemark?)null;
}
 
#region -- internals --
 
string MakeGeocoderUrl(string keywords)
{
return string.Format(CultureInfo.InvariantCulture, GeocoderUrlFormat, keywords.Replace(' ', '+'), AppId, !string.IsNullOrEmpty(LanguageStr) ? "&locale=" + LanguageStr : "");
}
 
string MakeGeocoderDetailedUrl(Placemark placemark)
{
return string.Format(GeocoderDetailedUrlFormat,
PrepareUrlString(placemark.CountryName),
PrepareUrlString(placemark.AdministrativeAreaName),
PrepareUrlString(placemark.SubAdministrativeAreaName),
PrepareUrlString(placemark.LocalityName),
PrepareUrlString(placemark.DistrictName),
PrepareUrlString(placemark.PostalCodeNumber),
PrepareUrlString(placemark.ThoroughfareName),
PrepareUrlString(placemark.HouseNo),
AppId,
!string.IsNullOrEmpty(LanguageStr) ? "&locale=" + LanguageStr : string.Empty);
}
 
string MakeReverseGeocoderUrl(PointLatLng pt)
{
return string.Format(CultureInfo.InvariantCulture, ReverseGeocoderUrlFormat, pt.Lat, pt.Lng, AppId, !string.IsNullOrEmpty(LanguageStr) ? "&locale=" + LanguageStr : "");
}
 
string PrepareUrlString(string str)
{
if (str == null) return string.Empty;
return str.Replace(' ', '+');
}
 
GeoCoderStatusCode GetLatLngFromGeocoderUrl(string url, out List<PointLatLng> pointList)
{
var status = GeoCoderStatusCode.Unknow;
pointList = null;
 
try
{
string geo = GMaps.Instance.UseGeocoderCache ? Cache.Instance.GetContent(url, CacheType.GeocoderCache) : string.Empty;
 
bool cache = false;
 
if (string.IsNullOrEmpty(geo))
{
geo = GetContentUsingHttp(url);
 
if (!string.IsNullOrEmpty(geo))
{
cache = true;
}
}
 
if (!string.IsNullOrEmpty(geo))
{
if (geo.StartsWith("<?xml") && geo.Contains("<Result"))
{
if (cache && GMaps.Instance.UseGeocoderCache)
{
Cache.Instance.SaveContent(url, CacheType.GeocoderCache, geo);
}
 
XmlDocument doc = new XmlDocument();
doc.LoadXml(geo);
{
XmlNodeList l = doc.SelectNodes("/ResultSet/Result");
if (l != null)
{
pointList = new List<PointLatLng>();
 
foreach (XmlNode n in l)
{
var nn = n.SelectSingleNode("quality");
if (nn != null)
{
var quality = int.Parse(nn.InnerText);
if (quality < MinExpectedQuality) continue;
 
nn = n.SelectSingleNode("latitude");
if (nn != null)
{
double lat = double.Parse(nn.InnerText, CultureInfo.InvariantCulture);
 
nn = n.SelectSingleNode("longitude");
if (nn != null)
{
double lng = double.Parse(nn.InnerText, CultureInfo.InvariantCulture);
pointList.Add(new PointLatLng(lat, lng));
}
}
}
}
 
status = GeoCoderStatusCode.G_GEO_SUCCESS;
}
}
}
}
}
catch (Exception ex)
{
status = GeoCoderStatusCode.ExceptionInCode;
Debug.WriteLine("GetLatLngFromGeocoderUrl: " + ex);
}
 
return status;
}
 
GeoCoderStatusCode GetPlacemarksFromReverseGeocoderUrl(string url, out List<Placemark> placemarkList)
{
var status = GeoCoderStatusCode.Unknow;
placemarkList = null;
 
try
{
string geo = GMaps.Instance.UsePlacemarkCache ? Cache.Instance.GetContent(url, CacheType.PlacemarkCache) : string.Empty;
 
bool cache = false;
 
if (string.IsNullOrEmpty(geo))
{
geo = GetContentUsingHttp(url);
 
if (!string.IsNullOrEmpty(geo))
{
cache = true;
}
}
 
if (!string.IsNullOrEmpty(geo))
{
if (geo.StartsWith("<?xml") && geo.Contains("<ResultSet"))
{
if (cache && GMaps.Instance.UsePlacemarkCache)
{
Cache.Instance.SaveContent(url, CacheType.PlacemarkCache, geo);
}
 
XmlDocument doc = new XmlDocument();
doc.LoadXml(geo);
{
XmlNodeList l = doc.SelectNodes("/ResultSet/Result");
if (l != null)
{
placemarkList = new List<Placemark>();
 
foreach (XmlNode n in l)
{
var vl = n.SelectSingleNode("name");
if (vl == null) continue;
 
Placemark placemark = new Placemark(vl.InnerText);
 
vl = n.SelectSingleNode("level0");
if (vl != null)
{
placemark.CountryName = vl.InnerText;
}
 
vl = n.SelectSingleNode("level0code");
if (vl != null)
{
placemark.CountryNameCode = vl.InnerText;
}
 
vl = n.SelectSingleNode("postal");
if (vl != null)
{
placemark.PostalCodeNumber = vl.InnerText;
}
 
vl = n.SelectSingleNode("level1");
if (vl != null)
{
placemark.AdministrativeAreaName = vl.InnerText;
}
 
vl = n.SelectSingleNode("level2");
if (vl != null)
{
placemark.SubAdministrativeAreaName = vl.InnerText;
}
 
vl = n.SelectSingleNode("level3");
if (vl != null)
{
placemark.LocalityName = vl.InnerText;
}
 
vl = n.SelectSingleNode("level4");
if (vl != null)
{
placemark.DistrictName = vl.InnerText;
}
 
vl = n.SelectSingleNode("street");
if (vl != null)
{
placemark.ThoroughfareName = vl.InnerText;
}
 
vl = n.SelectSingleNode("house");
if (vl != null)
{
placemark.HouseNo = vl.InnerText;
}
 
vl = n.SelectSingleNode("radius");
if (vl != null)
{
placemark.Accuracy = int.Parse(vl.InnerText);
}
placemarkList.Add(placemark);
}
 
status = GeoCoderStatusCode.G_GEO_SUCCESS;
}
}
}
}
}
catch (Exception ex)
{
status = GeoCoderStatusCode.ExceptionInCode;
Debug.WriteLine("GetPlacemarkFromReverseGeocoderUrl: " + ex);
}
 
return status;
}
 
static readonly string ReverseGeocoderUrlFormat = "http://where.yahooapis.com/geocode?q={0},{1}&appid={2}&flags=G&gflags=QRL{3}";
static readonly string GeocoderUrlFormat = "http://where.yahooapis.com/geocode?q={0}&appid={1}&flags=CG&gflags=QL{2}";
static readonly string GeocoderDetailedUrlFormat = "http://where.yahooapis.com/geocode?country={0}&state={1}&county={2}&city={3}&neighborhood={4}&postal={5}&street={6}&house={7}&appid={8}&flags=CG&gflags=QL{9}";
 
#endregion
 
#endregion
}
 
/// <summary>
/// YahooMap provider
/// </summary>
public class YahooMapProvider : YahooMapProviderBase
{
public static readonly YahooMapProvider Instance;
 
YahooMapProvider()
{
}
 
static YahooMapProvider()
{
Instance = new YahooMapProvider();
}
 
public string Version = "2.1";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("65DB032C-6869-49B0-A7FC-3AE41A26AF4D");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "YahooMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://maps1.yimg.com/hx/tl?b=1&v=4.3&.intl=en&x=12&y=7&z=7&r=1
// http://2.base.maps.api.here.com/maptile/2.1/maptile/newest/normal.day/11/1169/652/256/png8?lg=EN&token=TrLJuXVK62IQk0vuXFzaig%3D%3D&app_id=eAdkWGYRoc4RfxVo0Z4B
// https://4.aerial.maps.api.here.com/maptile/2.1/maptile/newest/hybrid.day/11/1167/652/256/jpg?lg=ENG&token=TrLJuXVK62IQk0vuXFzaig%3D%3D&requestid=yahoo.prod&app_id=eAdkWGYRoc4RfxVo0Z4B
// https://4.aerial.maps.api.here.com/maptile/2.1/maptile/newest/satellite.day/13/4671/2604/256/jpg?lg=ENG&token=TrLJuXVK62IQk0vuXFzaig%3D%3D&requestid=yahoo.prod&app_id=eAdkWGYRoc4RfxVo0Z4B
 
return string.Format(UrlFormat, ((GetServerNum(pos, 2)) + 1), Version, zoom, pos.X, pos.Y, language, rnd1, rnd2);
}
 
string rnd1 = Guid.NewGuid().ToString("N").Substring(0, 28);
string rnd2 = Guid.NewGuid().ToString("N").Substring(0, 20);
 
//static readonly string UrlFormat = "http://maps{0}.yimg.com/hx/tl?v={1}&.intl={2}&x={3}&y={4}&z={5}&r=1";
static readonly string UrlFormat = "http://{0}.base.maps.api.here.com/maptile/{1}/maptile/newest/normal.day/{2}/{3}/{4}/256/png8?lg={5}&token={6}&requestid=yahoo.prod&app_id={7}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Yahoo/YahooSatelliteMapProvider.cs
0,0 → 1,62

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// YahooSatelliteMap provider
/// </summary>
public class YahooSatelliteMapProvider : YahooMapProviderBase
{
public static readonly YahooSatelliteMapProvider Instance;
 
YahooSatelliteMapProvider()
{
}
 
static YahooSatelliteMapProvider()
{
Instance = new YahooSatelliteMapProvider();
}
 
public string Version = "1.9";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("55D71878-913F-4320-B5B6-B4167A3F148F");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "YahooSatelliteMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
// http://maps3.yimg.com/ae/ximg?v=1.9&t=a&s=256&.intl=en&x=15&y=7&z=7&r=1
 
return string.Format(UrlFormat, ((GetServerNum(pos, 2)) + 1), Version, language, pos.X, (((1 << zoom) >> 1) - 1 - pos.Y), (zoom + 1));
}
 
static readonly string UrlFormat = "http://maps{0}.yimg.com/ae/ximg?v={1}&t=a&s=256&.intl={2}&x={3}&y={4}&z={5}&r=1";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Yandex/YandexHybridMapProvider.cs
0,0 → 1,72

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// YandexHybridMap provider
/// </summary>
public class YandexHybridMapProvider : YandexMapProviderBase
{
public static readonly YandexHybridMapProvider Instance;
 
YandexHybridMapProvider()
{
}
 
static YandexHybridMapProvider()
{
Instance = new YandexHybridMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("78A3830F-5EE3-432C-A32E-91B7AF6BBCB9");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "YandexHybridMap";
public override string Name
{
get
{
return name;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { YandexSatelliteMapProvider.Instance, this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, UrlServer, GetServerNum(pos, 4) + 1, Version, pos.X, pos.Y, zoom, language, Server);
}
 
static readonly string UrlServer = "vec";
static readonly string UrlFormat = "http://{0}0{1}.{7}/tiles?l=skl&v={2}&x={3}&y={4}&z={5}&lang={6}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Yandex/YandexMapProvider.cs
0,0 → 1,115

namespace GMap.NET.MapProviders
{
using System;
using GMap.NET.Projections;
using GMap.NET.Internals;
 
public abstract class YandexMapProviderBase : GMapProvider
{
#region GMapProvider Members
public override Guid Id
{
get
{
throw new NotImplementedException();
}
}
 
public override string Name
{
get
{
throw new NotImplementedException();
}
}
 
public override PureProjection Projection
{
get
{
return MercatorProjectionYandex.Instance;
}
}
 
GMapProvider[] overlays;
public override GMapProvider[] Overlays
{
get
{
if(overlays == null)
{
overlays = new GMapProvider[] { this };
}
return overlays;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
throw new NotImplementedException();
}
#endregion
 
protected string Version = "4.6.9";
 
public readonly string Server /*d{'_'}b*/ = /*{^_^}*/ Stuff.GString /*{"_"}*/ (/* ;}~ */"MECxW6okUK3Ir7a9ue/vIA=="/* ;}~ */);
public readonly string ServerRu /*d{'_'}b*/ = /*{^_^}*/ Stuff.GString /*{"_"}*/ (/* ;}~ */"MECxW6okUK0FRlRPbF0BQg=="/* ;}~ */);
public readonly string ServerCom /*d{'_'}b*/ = /*{^_^}*/ Stuff.GString/*{"_"}*/ (/* ;}~ */"MECxW6okUK2JNHOW5AuimA=="/* ;}~ */);
}
 
/// <summary>
/// YenduxMap provider
/// </summary>
public class YandexMapProvider : YandexMapProviderBase
{
public static readonly YandexMapProvider Instance;
 
YandexMapProvider()
{
RefererUrl = "http://" + ServerCom + "/";
}
 
static YandexMapProvider()
{
Instance = new YandexMapProvider();
}
 
#region GMapProvider Members
 
readonly Guid id = new Guid("82DC969D-0491-40F3-8C21-4D90B67F47EB");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "YandexMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, UrlServer, GetServerNum(pos, 4) + 1, Version, pos.X, pos.Y, zoom, language, Server);
}
 
static readonly string UrlServer = "vec";
static readonly string UrlFormat = "http://{0}0{1}.{7}/tiles?l=map&v={2}&x={3}&y={4}&z={5}&lang={6}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.MapProviders/Yandex/YandexSatelliteMapProvider.cs
0,0 → 1,61

namespace GMap.NET.MapProviders
{
using System;
 
/// <summary>
/// YandexSatelliteMap provider
/// </summary>
public class YandexSatelliteMapProvider : YandexMapProviderBase
{
public static readonly YandexSatelliteMapProvider Instance;
 
YandexSatelliteMapProvider()
{
}
 
static YandexSatelliteMapProvider()
{
Instance = new YandexSatelliteMapProvider();
}
 
public new string Version = "3.135.0";
 
#region GMapProvider Members
 
readonly Guid id = new Guid("2D4CE763-0F91-40B2-A511-13EF428237AD");
public override Guid Id
{
get
{
return id;
}
}
 
readonly string name = "YandexSatelliteMap";
public override string Name
{
get
{
return name;
}
}
 
public override PureImage GetTileImage(GPoint pos, int zoom)
{
string url = MakeTileImageUrl(pos, zoom, LanguageStr);
 
return GetTileImageUsingHttp(url);
}
 
#endregion
 
string MakeTileImageUrl(GPoint pos, int zoom, string language)
{
return string.Format(UrlFormat, UrlServer, GetServerNum(pos, 4) + 1, Version, pos.X, pos.Y, zoom, language, Server);
}
 
static readonly string UrlServer = "sat";
static readonly string UrlFormat = "http://{0}0{1}.{7}/tiles?l=sat&v={2}&x={3}&y={4}&z={5}&lang={6}";
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Projections/MapsLTProjection.cs
0,0 → 1,622

namespace GMap.NET.Projections
{
using System;
using System.Collections.Generic;
 
/// <summary>
/// GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]
/// PROJCS["LKS94 / Lithuania TM",GEOGCS["LKS94",DATUM["Lithuania_1994_ETRS89",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6126"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4669"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",24],PARAMETER["scale_factor",0.9998],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],AUTHORITY["EPSG","3346"],AXIS["Y",EAST],AXIS["X",NORTH]]
/// </summary>
public class LKS94Projection : PureProjection
{
public static readonly LKS94Projection Instance = new LKS94Projection();
 
static readonly double MinLatitude = 53.33;
static readonly double MaxLatitude = 56.55;
static readonly double MinLongitude = 20.22;
static readonly double MaxLongitude = 27.11;
 
static readonly double orignX = -5122000;
static readonly double orignY = 10000100;
 
static readonly double scaleFactor = 0.9998; // scale factor
static readonly double centralMeridian = 0.41887902047863912;// Center longitude (projection center)
static readonly double latOrigin = 0.0; // center latitude
static readonly double falseNorthing = 0.0; // y offset in meters
static readonly double falseEasting = 500000.0; // x offset in meters
static readonly double semiMajor = 6378137.0; // major axis
static readonly double semiMinor = 6356752.3141403561; // minor axis
static readonly double semiMinor2 = 6356752.3142451793; // minor axis
static readonly double metersPerUnit = 1.0;
static readonly double COS_67P5 = 0.38268343236508977; // cosine of 67.5 degrees
static readonly double AD_C = 1.0026000; // Toms region 1 constant
 
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
 
GSize tileSize = new GSize(256, 256);
public override GSize TileSize
{
get
{
return tileSize;
}
}
 
public override double Axis
{
get
{
return 6378137;
}
}
 
public override double Flattening
{
get
{
return (1.0 / 298.257222101);
}
}
 
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
GPoint ret = GPoint.Empty;
 
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
 
double[] lks = new double[] { lng, lat };
lks = DTM10(lks);
lks = MTD10(lks);
lks = DTM00(lks);
 
double res = GetTileMatrixResolution(zoom);
return LksToPixel(lks, res);
}
 
static GPoint LksToPixel(double[] lks, double res)
{
return new GPoint((long)Math.Floor((lks[0] - orignX) / res), (long)Math.Floor((orignY - lks[1]) / res));
}
 
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
PointLatLng ret = PointLatLng.Empty;
 
double res = GetTileMatrixResolution(zoom);
 
double[] lks = new double[] { (x * res) + orignX, orignY - (y * res) };
lks = MTD11(lks);
lks = DTM10(lks);
lks = MTD10(lks);
 
ret.Lat = Clip(lks[1], MinLatitude, MaxLatitude);
ret.Lng = Clip(lks[0], MinLongitude, MaxLongitude);
 
return ret;
}
 
double[] DTM10(double[] lonlat)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor2 * semiMinor2) / (semiMajor * semiMajor); // e^2
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor2, 2)) / Math.Pow(semiMinor2, 2);
 
double ba = semiMinor2 / semiMajor;
double ab = semiMajor / semiMinor2;
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
double h = lonlat.Length < 3 ? 0 : lonlat[2].Equals(Double.NaN) ? 0 : lonlat[2];
double v = semiMajor / Math.Sqrt(1 - es * Math.Pow(Math.Sin(lat), 2));
double x = (v + h) * Math.Cos(lat) * Math.Cos(lon);
double y = (v + h) * Math.Cos(lat) * Math.Sin(lon);
double z = ((1 - es) * v + h) * Math.Sin(lat);
return new double[] { x, y, z, };
}
 
double[] MTD10(double[] pnt)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor * semiMinor) / (semiMajor * semiMajor); // e^2
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor, 2)) / Math.Pow(semiMinor, 2);
 
double ba = semiMinor / semiMajor;
double ab = semiMajor / semiMinor;
 
bool AtPole = false; // is location in polar region
double Z = pnt.Length < 3 ? 0 : pnt[2].Equals(Double.NaN) ? 0 : pnt[2];
 
double lon = 0;
double lat = 0;
double Height = 0;
if(pnt[0] != 0.0)
{
lon = Math.Atan2(pnt[1], pnt[0]);
}
else
{
if(pnt[1] > 0)
{
lon = Math.PI / 2;
}
else
if(pnt[1] < 0)
{
lon = -Math.PI * 0.5;
}
else
{
AtPole = true;
lon = 0.0;
if(Z > 0.0) // north pole
{
lat = Math.PI * 0.5;
}
else
if(Z < 0.0) // south pole
{
lat = -Math.PI * 0.5;
}
else // center of earth
{
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(Math.PI * 0.5), -semiMinor, };
}
}
}
double W2 = pnt[0] * pnt[0] + pnt[1] * pnt[1]; // Square of distance from Z axis
double W = Math.Sqrt(W2); // distance from Z axis
double T0 = Z * AD_C; // initial estimate of vertical component
double S0 = Math.Sqrt(T0 * T0 + W2); // initial estimate of horizontal component
double Sin_B0 = T0 / S0; // sin(B0), B0 is estimate of Bowring aux variable
double Cos_B0 = W / S0; // cos(B0)
double Sin3_B0 = Math.Pow(Sin_B0, 3);
double T1 = Z + semiMinor * ses * Sin3_B0; // corrected estimate of vertical component
double Sum = W - semiMajor * es * Cos_B0 * Cos_B0 * Cos_B0; // numerator of cos(phi1)
double S1 = Math.Sqrt(T1 * T1 + Sum * Sum); // corrected estimate of horizontal component
double Sin_p1 = T1 / S1; // sin(phi1), phi1 is estimated latitude
double Cos_p1 = Sum / S1; // cos(phi1)
double Rn = semiMajor / Math.Sqrt(1.0 - es * Sin_p1 * Sin_p1); // Earth radius at location
if(Cos_p1 >= COS_67P5)
{
Height = W / Cos_p1 - Rn;
}
else
if(Cos_p1 <= -COS_67P5)
{
Height = W / -Cos_p1 - Rn;
}
else
{
Height = Z / Sin_p1 + Rn * (es - 1.0);
}
 
if(!AtPole)
{
lat = Math.Atan(Sin_p1 / Cos_p1);
}
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), Height, };
}
 
double[] DTM00(double[] lonlat)
{
double e0, e1, e2, e3; // eccentricity constants
double e, es, esp; // eccentricity constants
double ml0; // small value m
 
es = 1.0 - Math.Pow(semiMinor / semiMajor, 2);
e = Math.Sqrt(es);
e0 = e0fn(es);
e1 = e1fn(es);
e2 = e2fn(es);
e3 = e3fn(es);
ml0 = semiMajor * mlfn(e0, e1, e2, e3, latOrigin);
esp = es / (1.0 - es);
 
// ...
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
 
double delta_lon = 0.0; // Delta longitude (Given longitude - center)
double sin_phi, cos_phi; // sin and cos value
double al, als; // temporary values
double c, t, tq; // temporary values
double con, n, ml; // cone constant, small m
 
delta_lon = AdjustLongitude(lon - centralMeridian);
SinCos(lat, out sin_phi, out cos_phi);
 
al = cos_phi * delta_lon;
als = Math.Pow(al, 2);
c = esp * Math.Pow(cos_phi, 2);
tq = Math.Tan(lat);
t = Math.Pow(tq, 2);
con = 1.0 - es * Math.Pow(sin_phi, 2);
n = semiMajor / Math.Sqrt(con);
ml = semiMajor * mlfn(e0, e1, e2, e3, lat);
 
double x = scaleFactor * n * al * (1.0 + als / 6.0 * (1.0 - t + c + als / 20.0 *
(5.0 - 18.0 * t + Math.Pow(t, 2) + 72.0 * c - 58.0 * esp))) + falseEasting;
 
double y = scaleFactor * (ml - ml0 + n * tq * (als * (0.5 + als / 24.0 *
(5.0 - t + 9.0 * c + 4.0 * Math.Pow(c, 2) + als / 30.0 * (61.0 - 58.0 * t
+ Math.Pow(t, 2) + 600.0 * c - 330.0 * esp))))) + falseNorthing;
 
if(lonlat.Length < 3)
return new double[] { x / metersPerUnit, y / metersPerUnit };
else
return new double[] { x / metersPerUnit, y / metersPerUnit, lonlat[2] };
}
 
double[] DTM01(double[] lonlat)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor * semiMinor) / (semiMajor * semiMajor);
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor, 2)) / Math.Pow(semiMinor, 2);
 
double ba = semiMinor / semiMajor;
double ab = semiMajor / semiMinor;
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
double h = lonlat.Length < 3 ? 0 : lonlat[2].Equals(Double.NaN) ? 0 : lonlat[2];
double v = semiMajor / Math.Sqrt(1 - es * Math.Pow(Math.Sin(lat), 2));
double x = (v + h) * Math.Cos(lat) * Math.Cos(lon);
double y = (v + h) * Math.Cos(lat) * Math.Sin(lon);
double z = ((1 - es) * v + h) * Math.Sin(lat);
return new double[] { x, y, z, };
}
 
double[] MTD01(double[] pnt)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor2 * semiMinor2) / (semiMajor * semiMajor);
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor2, 2)) / Math.Pow(semiMinor2, 2);
 
double ba = semiMinor2 / semiMajor;
double ab = semiMajor / semiMinor2;
 
bool At_Pole = false; // is location in polar region
double Z = pnt.Length < 3 ? 0 : pnt[2].Equals(Double.NaN) ? 0 : pnt[2];
 
double lon = 0;
double lat = 0;
double Height = 0;
if(pnt[0] != 0.0)
{
lon = Math.Atan2(pnt[1], pnt[0]);
}
else
{
if(pnt[1] > 0)
{
lon = Math.PI / 2;
}
else
if(pnt[1] < 0)
{
lon = -Math.PI * 0.5;
}
else
{
At_Pole = true;
lon = 0.0;
if(Z > 0.0) // north pole
{
lat = Math.PI * 0.5;
}
else
if(Z < 0.0) // south pole
{
lat = -Math.PI * 0.5;
}
else // center of earth
{
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(Math.PI * 0.5), -semiMinor2, };
}
}
}
 
double W2 = pnt[0] * pnt[0] + pnt[1] * pnt[1]; // Square of distance from Z axis
double W = Math.Sqrt(W2); // distance from Z axis
double T0 = Z * AD_C; // initial estimate of vertical component
double S0 = Math.Sqrt(T0 * T0 + W2); //initial estimate of horizontal component
double Sin_B0 = T0 / S0; // sin(B0), B0 is estimate of Bowring aux variable
double Cos_B0 = W / S0; // cos(B0)
double Sin3_B0 = Math.Pow(Sin_B0, 3);
double T1 = Z + semiMinor2 * ses * Sin3_B0; //corrected estimate of vertical component
double Sum = W - semiMajor * es * Cos_B0 * Cos_B0 * Cos_B0; // numerator of cos(phi1)
double S1 = Math.Sqrt(T1 * T1 + Sum * Sum); // corrected estimate of horizontal component
double Sin_p1 = T1 / S1; // sin(phi1), phi1 is estimated latitude
double Cos_p1 = Sum / S1; // cos(phi1)
double Rn = semiMajor / Math.Sqrt(1.0 - es * Sin_p1 * Sin_p1); // Earth radius at location
 
if(Cos_p1 >= COS_67P5)
{
Height = W / Cos_p1 - Rn;
}
else
if(Cos_p1 <= -COS_67P5)
{
Height = W / -Cos_p1 - Rn;
}
else
{
Height = Z / Sin_p1 + Rn * (es - 1.0);
}
 
if(!At_Pole)
{
lat = Math.Atan(Sin_p1 / Cos_p1);
}
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), Height, };
}
 
double[] MTD11(double[] p)
{
double e0, e1, e2, e3; // eccentricity constants
double e, es, esp; // eccentricity constants
double ml0; // small value m
 
es = 1.0 - Math.Pow(semiMinor / semiMajor, 2);
e = Math.Sqrt(es);
e0 = e0fn(es);
e1 = e1fn(es);
e2 = e2fn(es);
e3 = e3fn(es);
ml0 = semiMajor * mlfn(e0, e1, e2, e3, latOrigin);
esp = es / (1.0 - es);
 
// ...
 
double con, phi;
double delta_phi;
long i;
double sin_phi, cos_phi, tan_phi;
double c, cs, t, ts, n, r, d, ds;
long max_iter = 6;
 
double x = p[0] * metersPerUnit - falseEasting;
double y = p[1] * metersPerUnit - falseNorthing;
 
con = (ml0 + y / scaleFactor) / semiMajor;
phi = con;
for(i = 0; ; i++)
{
delta_phi = ((con + e1 * Math.Sin(2.0 * phi) - e2 * Math.Sin(4.0 * phi) + e3 * Math.Sin(6.0 * phi)) / e0) - phi;
phi += delta_phi;
 
if(Math.Abs(delta_phi) <= EPSLoN)
break;
 
if(i >= max_iter)
throw new ArgumentException("Latitude failed to converge");
}
 
if(Math.Abs(phi) < HALF_PI)
{
SinCos(phi, out sin_phi, out cos_phi);
tan_phi = Math.Tan(phi);
c = esp * Math.Pow(cos_phi, 2);
cs = Math.Pow(c, 2);
t = Math.Pow(tan_phi, 2);
ts = Math.Pow(t, 2);
con = 1.0 - es * Math.Pow(sin_phi, 2);
n = semiMajor / Math.Sqrt(con);
r = n * (1.0 - es) / con;
d = x / (n * scaleFactor);
ds = Math.Pow(d, 2);
 
double lat = phi - (n * tan_phi * ds / r) * (0.5 - ds / 24.0 * (5.0 + 3.0 * t +
10.0 * c - 4.0 * cs - 9.0 * esp - ds / 30.0 * (61.0 + 90.0 * t +
298.0 * c + 45.0 * ts - 252.0 * esp - 3.0 * cs)));
 
double lon = AdjustLongitude(centralMeridian + (d * (1.0 - ds / 6.0 * (1.0 + 2.0 * t +
c - ds / 20.0 * (5.0 - 2.0 * c + 28.0 * t - 3.0 * cs + 8.0 * esp +
24.0 * ts))) / cos_phi));
 
if(p.Length < 3)
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat) };
else
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), p[2] };
}
else
{
if(p.Length < 3)
return new double[] { RadiansToDegrees(HALF_PI * Sign(y)), RadiansToDegrees(centralMeridian) };
else
return new double[] { RadiansToDegrees(HALF_PI * Sign(y)), RadiansToDegrees(centralMeridian), p[2] };
}
}
 
#region -- levels info --
// layers":[{"id":0,"name":"Lietuva","parentLayerId":-1, "defaultVisibility":true,
// "subLayerIds":null,
//
// "minScale":10000000,"maxScale":900}],
// "tables":[],"spatialReference":{"wkid":2600,"latestWkid":3346},
// "singleFusedMapCache":true,"tileInfo":{"rows":256,"cols":256,"dpi":96,"format":"PNG8","compressionQuality":0,
//
// "origin":{"x":-5122000,"y":10000100},
// "spatialReference":{"wkid":2600,"latestWkid":3346},
//
// "lods":[
//{"level":0,"resolution":1587.5031750063501,"scale":6000000},
//{"level":1,"resolution":793.7515875031751,"scale":3000000},
//{"level":2,"resolution":529.1677250021168,"scale":2000000},
//{"level":3,"resolution":264.5838625010584,"scale":1000000},
//{"level":4,"resolution":132.2919312505292,"scale":500000},
//{"level":5,"resolution":52.91677250021167,"scale":200000},
//{"level":6,"resolution":26.458386250105836,"scale":100000},
//{"level":7,"resolution":13.229193125052918,"scale":50000},
//{"level":8,"resolution":6.614596562526459,"scale":25000},
//{"level":9,"resolution":2.6458386250105836,"scale":10000},
//{"level":10,"resolution":1.3229193125052918,"scale":5000},
//{"level":11,"resolution":0.5291677250021167,"scale":2000},
//{"level":12,"resolution":0.26458386250105836,"scale":1000}]},
 
//"initialExtent":
//{"xmin":95993.35274978809,"ymin":5830525.306491293,
//"xmax":852703.1995028148,"ymax":6400968.114043575,
//"spatialReference":{"wkid":2600,"latestWkid":3346}},
 
//"fullExtent":{"xmin":38843.23844955949,"ymin":5663308.305390623,
//"xmax":907736.6429030352,"ymax":6555485.089744193,
//"spatialReference":{"wkid":2600,"latestWkid":3346}},
 
//"minScale":6000000,"maxScale":1000,"units":"esriMeters",
//"supportedImageFormatTypes":"PNG32,PNG24,PNG,JPG,DIB,TIFF,EMF,PS,PDF,GIF,SVG,SVGZ,BMP",
//"documentInfo":{"Title":"Lietuvos topografinis žemėlapis"
//"xmax":1050000,"ymax":6500000, units":"esriMeters"
#endregion
 
public static double GetTileMatrixResolution(int zoom)
{
double ret = 0;
 
switch(zoom)
{
#region -- sizes --
case 0:
{
ret = 1587.5031750063501;
}
break;
 
case 1:
{
ret = 793.7515875031751;
}
break;
 
case 2:
{
ret = 529.1677250021168;
}
break;
 
case 3:
{
ret = 264.5838625010584;
}
break;
 
case 4:
{
ret = 132.2919312505292;
}
break;
 
case 5:
{
ret = 52.91677250021167;
}
break;
 
case 6:
{
ret = 26.458386250105836;
}
break;
 
case 7:
{
ret = 13.229193125052918;
}
break;
 
case 8:
{
ret = 6.614596562526459;
}
break;
 
case 9:
{
ret = 2.6458386250105836;
}
break;
 
case 10:
{
ret = 1.3229193125052918;
}
break;
 
case 11:
{
ret = 0.5291677250021167;
}
break;
 
case 12:
{
ret = 0.26458386250105836;
}
break;
#endregion
}
 
return ret;
}
 
public override double GetGroundResolution(int zoom, double latitude)
{
return GetTileMatrixResolution(zoom);
}
 
Dictionary<int, GSize> extentMatrixMin;
Dictionary<int, GSize> extentMatrixMax;
 
public override GSize GetTileMatrixMinXY(int zoom)
{
if(extentMatrixMin == null)
{
GenerateExtents();
}
return extentMatrixMin[zoom];
}
 
public override GSize GetTileMatrixMaxXY(int zoom)
{
if(extentMatrixMax == null)
{
GenerateExtents();
}
return extentMatrixMax[zoom];
}
 
void GenerateExtents()
{
extentMatrixMin = new Dictionary<int, GSize>();
extentMatrixMax = new Dictionary<int, GSize>();
//RectLatLng Extent = RectLatLng.FromLTRB(219818.60040028347, 6407318.126743601, 747927.9899523959, 5826291.964691277);
 
for(int i = 0; i <= 12; i++)
{
double res = GetTileMatrixResolution(i);
//extentMatrixMin.Add(i, new GSize(FromPixelToTileXY(LksToPixel(new double[]{ Extent.Left, Extent.Top }, res))));
//extentMatrixMax.Add(i, new GSize(FromPixelToTileXY(LksToPixel(new double[] { Extent.Right, Extent.Bottom }, res))));
 
extentMatrixMin.Add(i, new GSize(FromPixelToTileXY(FromLatLngToPixel(Bounds.LocationTopLeft, i))));
extentMatrixMax.Add(i, new GSize(FromPixelToTileXY(FromLatLngToPixel(Bounds.LocationRightBottom, i))));
}
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Projections/MapsLTReliefProjection.cs
0,0 → 1,621

namespace GMap.NET.Projections
{
using System;
using System.Collections.Generic;
 
/// <summary>
/// GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]
/// PROJCS["LKS94 / Lithuania TM",GEOGCS["LKS94",DATUM["Lithuania_1994_ETRS89",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6126"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4669"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",24],PARAMETER["scale_factor",0.9998],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],AUTHORITY["EPSG","3346"],AXIS["Y",EAST],AXIS["X",NORTH]]
/// </summary>
public class LKS94rProjection : PureProjection
{
public static readonly LKS94rProjection Instance = new LKS94rProjection();
 
static readonly double MinLatitude = 53.33;
static readonly double MaxLatitude = 56.55;
static readonly double MinLongitude = 20.22;
static readonly double MaxLongitude = 27.11;
 
static readonly double orignX = -5122000;
static readonly double orignY = 10325013.240285;
 
static readonly double scaleFactor = 0.9998; // scale factor
static readonly double centralMeridian = 0.41887902047863912;// Center longitude (projection center)
static readonly double latOrigin = 0.0; // center latitude
static readonly double falseNorthing = 0.0; // y offset in meters
static readonly double falseEasting = 500000.0; // x offset in meters
static readonly double semiMajor = 6378137.0; // major axis
static readonly double semiMinor = 6356752.3141403561; // minor axis
static readonly double semiMinor2 = 6356752.3142451793; // minor axis
static readonly double metersPerUnit = 1.0;
static readonly double COS_67P5 = 0.38268343236508977; // cosine of 67.5 degrees
static readonly double AD_C = 1.0026000; // Toms region 1 constant
 
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
 
GSize tileSize = new GSize(256, 256);
public override GSize TileSize
{
get
{
return tileSize;
}
}
 
public override double Axis
{
get
{
return 6378137;
}
}
 
public override double Flattening
{
get
{
return (1.0 / 298.257222101);
}
}
 
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
 
double[] lks = new double[] { lng, lat };
lks = DTM10(lks);
lks = MTD10(lks);
lks = DTM00(lks);
 
double res = GetTileMatrixResolution(zoom);
return LksToPixel(lks, res);
}
 
static GPoint LksToPixel(double[] lks, double res)
{
return new GPoint((long)Math.Floor((lks[0] - orignX) / res), (long)Math.Floor((orignY - lks[1]) / res));
}
 
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
PointLatLng ret = PointLatLng.Empty;
 
double res = GetTileMatrixResolution(zoom);
 
double[] lks = new double[] { (x * res) + orignX, orignY - (y * res) };
lks = MTD11(lks);
lks = DTM10(lks);
lks = MTD10(lks);
 
ret.Lat = Clip(lks[1], MinLatitude, MaxLatitude);
ret.Lng = Clip(lks[0], MinLongitude, MaxLongitude);
 
return ret;
}
 
double[] DTM10(double[] lonlat)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor2 * semiMinor2) / (semiMajor * semiMajor); // e^2
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor2, 2)) / Math.Pow(semiMinor2, 2);
 
double ba = semiMinor2 / semiMajor;
double ab = semiMajor / semiMinor2;
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
double h = lonlat.Length < 3 ? 0 : lonlat[2].Equals(Double.NaN) ? 0 : lonlat[2];
double v = semiMajor / Math.Sqrt(1 - es * Math.Pow(Math.Sin(lat), 2));
double x = (v + h) * Math.Cos(lat) * Math.Cos(lon);
double y = (v + h) * Math.Cos(lat) * Math.Sin(lon);
double z = ((1 - es) * v + h) * Math.Sin(lat);
return new double[] { x, y, z, };
}
 
double[] MTD10(double[] pnt)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor * semiMinor) / (semiMajor * semiMajor); // e^2
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor, 2)) / Math.Pow(semiMinor, 2);
 
double ba = semiMinor / semiMajor;
double ab = semiMajor / semiMinor;
 
bool AtPole = false; // is location in polar region
double Z = pnt.Length < 3 ? 0 : pnt[2].Equals(Double.NaN) ? 0 : pnt[2];
 
double lon = 0;
double lat = 0;
double Height = 0;
if(pnt[0] != 0.0)
{
lon = Math.Atan2(pnt[1], pnt[0]);
}
else
{
if(pnt[1] > 0)
{
lon = Math.PI / 2;
}
else
if(pnt[1] < 0)
{
lon = -Math.PI * 0.5;
}
else
{
AtPole = true;
lon = 0.0;
if(Z > 0.0) // north pole
{
lat = Math.PI * 0.5;
}
else
if(Z < 0.0) // south pole
{
lat = -Math.PI * 0.5;
}
else // center of earth
{
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(Math.PI * 0.5), -semiMinor, };
}
}
}
double W2 = pnt[0] * pnt[0] + pnt[1] * pnt[1]; // Square of distance from Z axis
double W = Math.Sqrt(W2); // distance from Z axis
double T0 = Z * AD_C; // initial estimate of vertical component
double S0 = Math.Sqrt(T0 * T0 + W2); // initial estimate of horizontal component
double Sin_B0 = T0 / S0; // sin(B0), B0 is estimate of Bowring aux variable
double Cos_B0 = W / S0; // cos(B0)
double Sin3_B0 = Math.Pow(Sin_B0, 3);
double T1 = Z + semiMinor * ses * Sin3_B0; // corrected estimate of vertical component
double Sum = W - semiMajor * es * Cos_B0 * Cos_B0 * Cos_B0; // numerator of cos(phi1)
double S1 = Math.Sqrt(T1 * T1 + Sum * Sum); // corrected estimate of horizontal component
double Sin_p1 = T1 / S1; // sin(phi1), phi1 is estimated latitude
double Cos_p1 = Sum / S1; // cos(phi1)
double Rn = semiMajor / Math.Sqrt(1.0 - es * Sin_p1 * Sin_p1); // Earth radius at location
if(Cos_p1 >= COS_67P5)
{
Height = W / Cos_p1 - Rn;
}
else
if(Cos_p1 <= -COS_67P5)
{
Height = W / -Cos_p1 - Rn;
}
else
{
Height = Z / Sin_p1 + Rn * (es - 1.0);
}
 
if(!AtPole)
{
lat = Math.Atan(Sin_p1 / Cos_p1);
}
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), Height, };
}
 
double[] DTM00(double[] lonlat)
{
double e0, e1, e2, e3; // eccentricity constants
double e, es, esp; // eccentricity constants
double ml0; // small value m
 
es = 1.0 - Math.Pow(semiMinor / semiMajor, 2);
e = Math.Sqrt(es);
e0 = e0fn(es);
e1 = e1fn(es);
e2 = e2fn(es);
e3 = e3fn(es);
ml0 = semiMajor * mlfn(e0, e1, e2, e3, latOrigin);
esp = es / (1.0 - es);
 
// ...
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
 
double delta_lon = 0.0; // Delta longitude (Given longitude - center)
double sin_phi, cos_phi; // sin and cos value
double al, als; // temporary values
double c, t, tq; // temporary values
double con, n, ml; // cone constant, small m
 
delta_lon = AdjustLongitude(lon - centralMeridian);
SinCos(lat, out sin_phi, out cos_phi);
 
al = cos_phi * delta_lon;
als = Math.Pow(al, 2);
c = esp * Math.Pow(cos_phi, 2);
tq = Math.Tan(lat);
t = Math.Pow(tq, 2);
con = 1.0 - es * Math.Pow(sin_phi, 2);
n = semiMajor / Math.Sqrt(con);
ml = semiMajor * mlfn(e0, e1, e2, e3, lat);
 
double x = scaleFactor * n * al * (1.0 + als / 6.0 * (1.0 - t + c + als / 20.0 *
(5.0 - 18.0 * t + Math.Pow(t, 2) + 72.0 * c - 58.0 * esp))) + falseEasting;
 
double y = scaleFactor * (ml - ml0 + n * tq * (als * (0.5 + als / 24.0 *
(5.0 - t + 9.0 * c + 4.0 * Math.Pow(c, 2) + als / 30.0 * (61.0 - 58.0 * t
+ Math.Pow(t, 2) + 600.0 * c - 330.0 * esp))))) + falseNorthing;
 
if(lonlat.Length < 3)
return new double[] { x / metersPerUnit, y / metersPerUnit };
else
return new double[] { x / metersPerUnit, y / metersPerUnit, lonlat[2] };
}
 
double[] DTM01(double[] lonlat)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor * semiMinor) / (semiMajor * semiMajor);
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor, 2)) / Math.Pow(semiMinor, 2);
 
double ba = semiMinor / semiMajor;
double ab = semiMajor / semiMinor;
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
double h = lonlat.Length < 3 ? 0 : lonlat[2].Equals(Double.NaN) ? 0 : lonlat[2];
double v = semiMajor / Math.Sqrt(1 - es * Math.Pow(Math.Sin(lat), 2));
double x = (v + h) * Math.Cos(lat) * Math.Cos(lon);
double y = (v + h) * Math.Cos(lat) * Math.Sin(lon);
double z = ((1 - es) * v + h) * Math.Sin(lat);
return new double[] { x, y, z, };
}
 
double[] MTD01(double[] pnt)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor2 * semiMinor2) / (semiMajor * semiMajor);
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor2, 2)) / Math.Pow(semiMinor2, 2);
 
double ba = semiMinor2 / semiMajor;
double ab = semiMajor / semiMinor2;
 
bool At_Pole = false; // is location in polar region
double Z = pnt.Length < 3 ? 0 : pnt[2].Equals(Double.NaN) ? 0 : pnt[2];
 
double lon = 0;
double lat = 0;
double Height = 0;
if(pnt[0] != 0.0)
{
lon = Math.Atan2(pnt[1], pnt[0]);
}
else
{
if(pnt[1] > 0)
{
lon = Math.PI / 2;
}
else
if(pnt[1] < 0)
{
lon = -Math.PI * 0.5;
}
else
{
At_Pole = true;
lon = 0.0;
if(Z > 0.0) // north pole
{
lat = Math.PI * 0.5;
}
else
if(Z < 0.0) // south pole
{
lat = -Math.PI * 0.5;
}
else // center of earth
{
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(Math.PI * 0.5), -semiMinor2, };
}
}
}
 
double W2 = pnt[0] * pnt[0] + pnt[1] * pnt[1]; // Square of distance from Z axis
double W = Math.Sqrt(W2); // distance from Z axis
double T0 = Z * AD_C; // initial estimate of vertical component
double S0 = Math.Sqrt(T0 * T0 + W2); //initial estimate of horizontal component
double Sin_B0 = T0 / S0; // sin(B0), B0 is estimate of Bowring aux variable
double Cos_B0 = W / S0; // cos(B0)
double Sin3_B0 = Math.Pow(Sin_B0, 3);
double T1 = Z + semiMinor2 * ses * Sin3_B0; //corrected estimate of vertical component
double Sum = W - semiMajor * es * Cos_B0 * Cos_B0 * Cos_B0; // numerator of cos(phi1)
double S1 = Math.Sqrt(T1 * T1 + Sum * Sum); // corrected estimate of horizontal component
double Sin_p1 = T1 / S1; // sin(phi1), phi1 is estimated latitude
double Cos_p1 = Sum / S1; // cos(phi1)
double Rn = semiMajor / Math.Sqrt(1.0 - es * Sin_p1 * Sin_p1); // Earth radius at location
 
if(Cos_p1 >= COS_67P5)
{
Height = W / Cos_p1 - Rn;
}
else
if(Cos_p1 <= -COS_67P5)
{
Height = W / -Cos_p1 - Rn;
}
else
{
Height = Z / Sin_p1 + Rn * (es - 1.0);
}
 
if(!At_Pole)
{
lat = Math.Atan(Sin_p1 / Cos_p1);
}
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), Height, };
}
 
double[] MTD11(double[] p)
{
double e0, e1, e2, e3; // eccentricity constants
double e, es, esp; // eccentricity constants
double ml0; // small value m
 
es = 1.0 - Math.Pow(semiMinor / semiMajor, 2);
e = Math.Sqrt(es);
e0 = e0fn(es);
e1 = e1fn(es);
e2 = e2fn(es);
e3 = e3fn(es);
ml0 = semiMajor * mlfn(e0, e1, e2, e3, latOrigin);
esp = es / (1.0 - es);
 
// ...
 
double con, phi;
double delta_phi;
long i;
double sin_phi, cos_phi, tan_phi;
double c, cs, t, ts, n, r, d, ds;
long max_iter = 6;
 
double x = p[0] * metersPerUnit - falseEasting;
double y = p[1] * metersPerUnit - falseNorthing;
 
con = (ml0 + y / scaleFactor) / semiMajor;
phi = con;
for(i = 0; ; i++)
{
delta_phi = ((con + e1 * Math.Sin(2.0 * phi) - e2 * Math.Sin(4.0 * phi) + e3 * Math.Sin(6.0 * phi)) / e0) - phi;
phi += delta_phi;
 
if(Math.Abs(delta_phi) <= EPSLoN)
break;
 
if(i >= max_iter)
throw new ArgumentException("Latitude failed to converge");
}
 
if(Math.Abs(phi) < HALF_PI)
{
SinCos(phi, out sin_phi, out cos_phi);
tan_phi = Math.Tan(phi);
c = esp * Math.Pow(cos_phi, 2);
cs = Math.Pow(c, 2);
t = Math.Pow(tan_phi, 2);
ts = Math.Pow(t, 2);
con = 1.0 - es * Math.Pow(sin_phi, 2);
n = semiMajor / Math.Sqrt(con);
r = n * (1.0 - es) / con;
d = x / (n * scaleFactor);
ds = Math.Pow(d, 2);
 
double lat = phi - (n * tan_phi * ds / r) * (0.5 - ds / 24.0 * (5.0 + 3.0 * t +
10.0 * c - 4.0 * cs - 9.0 * esp - ds / 30.0 * (61.0 + 90.0 * t +
298.0 * c + 45.0 * ts - 252.0 * esp - 3.0 * cs)));
 
double lon = AdjustLongitude(centralMeridian + (d * (1.0 - ds / 6.0 * (1.0 + 2.0 * t +
c - ds / 20.0 * (5.0 - 2.0 * c + 28.0 * t - 3.0 * cs + 8.0 * esp +
24.0 * ts))) / cos_phi));
 
if(p.Length < 3)
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat) };
else
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), p[2] };
}
else
{
if(p.Length < 3)
return new double[] { RadiansToDegrees(HALF_PI * Sign(y)), RadiansToDegrees(centralMeridian) };
else
return new double[] { RadiansToDegrees(HALF_PI * Sign(y)), RadiansToDegrees(centralMeridian), p[2] };
}
}
 
#region -- levels info --
/*
* "layers":[
* {"id":0,"name":"Lietuva","parentLayerId":-1,"defaultVisibility":true,
* "subLayerIds":null,
*
* "minScale":10000000,"maxScale":900}],
* "tables":[],"spatialReference":{"wkid":2600,"latestWkid":3346},
* "singleFusedMapCache":true,"tileInfo":{"rows":256,"cols":256,"dpi":96,"format":"MIXED","compressionQuality":90,
*
* "origin":{"x":-5122000,"y":1.0325013240285E7},
* "spatialReference":{"wkid":2600,"latestWkid":3346},
*
* "lods":[
* {"level":0,"resolution":1587.5031750063501,"scale":6000000},
* {"level":1,"resolution":793.7515875031751,"scale":3000000},
* {"level":2,"resolution":529.1677250021168,"scale":2000000},
* {"level":3,"resolution":264.5838625010584,"scale":1000000},
* {"level":4,"resolution":132.2919312505292,"scale":500000},
* {"level":5,"resolution":52.91677250021167,"scale":200000},
* {"level":6,"resolution":26.458386250105836,"scale":100000},
* {"level":7,"resolution":13.229193125052918,"scale":50000},
* {"level":8,"resolution":6.614596562526459,"scale":25000},
* {"level":9,"resolution":2.6458386250105836,"scale":10000},
* {"level":10,"resolution":1.3229193125052918,"scale":5000},
* {"level":11,"resolution":0.5291677250021167,"scale":2000},
* {"level":12,"resolution":0.26458386250105836,"scale":1000}]},
*
* "initialExtent":
* {"xmin":219818.60040028347,"ymin":5826291.964691277,
* "xmax":747927.9899523959,"ymax":6407318.126743601,
* "spatialReference":{"wkid":2600,"latestWkid":3346}},
*
* * "fullExtent":
* {"xmin":38843.23844955949,"ymin":5663308.305390623,
* "xmax":907736.6429030352,"ymax":6555485.089744193,
*
* "spatialReference":{"wkid":2600,"latestWkid":3346}},
* "minScale":6000000,"maxScale":5000,"units":"esriMeters","supportedImageFormatTypes":"PNG32,PNG24,PNG,JPG,DIB,TIFF,EMF,PS,PDF,GIF,SVG,SVGZ,BMP",
* "documentInfo":{"Title":"Lietuvos reljefinis žemėlapis","Author":"","Comments":"","Subject":"","Category":"","AntialiasingMode":"None","TextAntialiasingMode":"Force","Keywords":""},"capabilities":"Map","supportedQueryFormats":"JSON, AMF","exportTilesAllowed":false,"maxRecordCount":1000,"maxImageHeight":4096,"maxImageWidth":4096,"supportedExtensions":""});*/
#endregion
 
public static double GetTileMatrixResolution(int zoom)
{
double ret = 0;
 
switch(zoom)
{
#region -- sizes --
case 0:
{
ret = 1587.5031750063501;
}
break;
 
case 1:
{
ret = 793.7515875031751;
}
break;
 
case 2:
{
ret = 529.1677250021168;
}
break;
 
case 3:
{
ret = 264.5838625010584;
}
break;
 
case 4:
{
ret = 132.2919312505292;
}
break;
 
case 5:
{
ret = 52.91677250021167;
}
break;
 
case 6:
{
ret = 26.458386250105836;
}
break;
 
case 7:
{
ret = 13.229193125052918;
}
break;
 
case 8:
{
ret = 6.614596562526459;
}
break;
 
case 9:
{
ret = 2.6458386250105836;
}
break;
 
case 10:
{
ret = 1.3229193125052918;
}
break;
 
case 11:
{
ret = 0.5291677250021167;
}
break;
 
case 12:
{
ret = 0.26458386250105836;
}
break;
#endregion
}
 
return ret;
}
 
public override double GetGroundResolution(int zoom, double latitude)
{
return GetTileMatrixResolution(zoom);
}
 
Dictionary<int, GSize> extentMatrixMin;
Dictionary<int, GSize> extentMatrixMax;
 
public override GSize GetTileMatrixMinXY(int zoom)
{
if(extentMatrixMin == null)
{
GenerateExtents();
}
return extentMatrixMin[zoom];
}
 
public override GSize GetTileMatrixMaxXY(int zoom)
{
if(extentMatrixMax == null)
{
GenerateExtents();
}
return extentMatrixMax[zoom];
}
 
void GenerateExtents()
{
extentMatrixMin = new Dictionary<int, GSize>();
extentMatrixMax = new Dictionary<int, GSize>();
//RectLatLng Extent = RectLatLng.FromLTRB(219818.60040028347, 6407318.126743601, 747927.9899523959, 5826291.964691277);
 
for(int i = 0; i <= 12; i++)
{
double res = GetTileMatrixResolution(i);
//extentMatrixMin.Add(i, new GSize(FromPixelToTileXY(LksToPixel(new double[]{ Extent.Left, Extent.Top }, res))));
//extentMatrixMax.Add(i, new GSize(FromPixelToTileXY(LksToPixel(new double[] { Extent.Right, Extent.Bottom }, res))));
 
extentMatrixMin.Add(i, new GSize(FromPixelToTileXY(FromLatLngToPixel(Bounds.LocationTopLeft, i))));
extentMatrixMax.Add(i, new GSize(FromPixelToTileXY(FromLatLngToPixel(Bounds.LocationRightBottom, i))));
}
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Projections/MapsLVProjection.cs
0,0 → 1,610

namespace GMap.NET.Projections
{
using System;
using System.Collections.Generic;
 
/// <summary>
/// GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]
/// PROJCS["LKS92 / Latvia TM",GEOGCS["LKS92",DATUM["D_Latvia_1992",SPHEROID["GRS_1980",6378137,298.257222101]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",24],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",-6000000],UNIT["Meter",1]]
/// </summary>
public class LKS92Projection : PureProjection
{
public static readonly LKS92Projection Instance = new LKS92Projection();
 
static readonly double MinLatitude = 55.55;
static readonly double MaxLatitude = 58.22;
static readonly double MinLongitude = 20.22;
static readonly double MaxLongitude = 28.28;
 
static readonly double orignX = -5120900;
static readonly double orignY = 3998100;
 
static readonly double scaleFactor = 0.9996; // scale factor
static readonly double centralMeridian = 0.41887902047863912;// Center longitude (projection center)
static readonly double latOrigin = 0.0; // center latitude
static readonly double falseNorthing = -6000000.0; // y offset in meters
static readonly double falseEasting = 500000.0; // x offset in meters
static readonly double semiMajor = 6378137.0; // major axis
static readonly double semiMinor = 6356752.3141403561; // minor axis
static readonly double semiMinor2 = 6356752.3142451793; // minor axis
static readonly double metersPerUnit = 1.0;
static readonly double COS_67P5 = 0.38268343236508977; // cosine of 67.5 degrees
static readonly double AD_C = 1.0026000; // Toms region 1 constant
 
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
 
GSize tileSize = new GSize(256, 256);
public override GSize TileSize
{
get
{
return tileSize;
}
}
 
public override double Axis
{
get
{
return 6378137;
}
}
 
public override double Flattening
{
get
{
return (1.0 / 298.257222101);
}
}
 
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
 
double[] lks = new double[] { lng, lat };
lks = DTM10(lks);
lks = MTD10(lks);
lks = DTM00(lks);
 
double res = GetTileMatrixResolution(zoom);
return LksToPixel(lks, res);
}
 
static GPoint LksToPixel(double[] lks, double res)
{
return new GPoint((long)Math.Floor((lks[0] - orignX) / res), (long)Math.Floor((orignY - lks[1]) / res));
}
 
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
PointLatLng ret = PointLatLng.Empty;
 
double res = GetTileMatrixResolution(zoom);
 
double[] lks = new double[] { (x * res) + orignX, orignY - (y * res) };
lks = MTD11(lks);
lks = DTM10(lks);
lks = MTD10(lks);
 
ret.Lat = Clip(lks[1], MinLatitude, MaxLatitude);
ret.Lng = Clip(lks[0], MinLongitude, MaxLongitude);
 
return ret;
}
 
double[] DTM10(double[] lonlat)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor2 * semiMinor2) / (semiMajor * semiMajor); // e^2
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor2, 2)) / Math.Pow(semiMinor2, 2);
 
double ba = semiMinor2 / semiMajor;
double ab = semiMajor / semiMinor2;
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
double h = lonlat.Length < 3 ? 0 : lonlat[2].Equals(Double.NaN) ? 0 : lonlat[2];
double v = semiMajor / Math.Sqrt(1 - es * Math.Pow(Math.Sin(lat), 2));
double x = (v + h) * Math.Cos(lat) * Math.Cos(lon);
double y = (v + h) * Math.Cos(lat) * Math.Sin(lon);
double z = ((1 - es) * v + h) * Math.Sin(lat);
return new double[] { x, y, z, };
}
 
double[] MTD10(double[] pnt)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor * semiMinor) / (semiMajor * semiMajor); // e^2
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor, 2)) / Math.Pow(semiMinor, 2);
 
double ba = semiMinor / semiMajor;
double ab = semiMajor / semiMinor;
 
bool AtPole = false; // is location in polar region
double Z = pnt.Length < 3 ? 0 : pnt[2].Equals(Double.NaN) ? 0 : pnt[2];
 
double lon = 0;
double lat = 0;
double Height = 0;
if(pnt[0] != 0.0)
{
lon = Math.Atan2(pnt[1], pnt[0]);
}
else
{
if(pnt[1] > 0)
{
lon = Math.PI / 2;
}
else
if(pnt[1] < 0)
{
lon = -Math.PI * 0.5;
}
else
{
AtPole = true;
lon = 0.0;
if(Z > 0.0) // north pole
{
lat = Math.PI * 0.5;
}
else
if(Z < 0.0) // south pole
{
lat = -Math.PI * 0.5;
}
else // center of earth
{
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(Math.PI * 0.5), -semiMinor, };
}
}
}
double W2 = pnt[0] * pnt[0] + pnt[1] * pnt[1]; // Square of distance from Z axis
double W = Math.Sqrt(W2); // distance from Z axis
double T0 = Z * AD_C; // initial estimate of vertical component
double S0 = Math.Sqrt(T0 * T0 + W2); // initial estimate of horizontal component
double Sin_B0 = T0 / S0; // sin(B0), B0 is estimate of Bowring aux variable
double Cos_B0 = W / S0; // cos(B0)
double Sin3_B0 = Math.Pow(Sin_B0, 3);
double T1 = Z + semiMinor * ses * Sin3_B0; // corrected estimate of vertical component
double Sum = W - semiMajor * es * Cos_B0 * Cos_B0 * Cos_B0; // numerator of cos(phi1)
double S1 = Math.Sqrt(T1 * T1 + Sum * Sum); // corrected estimate of horizontal component
double Sin_p1 = T1 / S1; // sin(phi1), phi1 is estimated latitude
double Cos_p1 = Sum / S1; // cos(phi1)
double Rn = semiMajor / Math.Sqrt(1.0 - es * Sin_p1 * Sin_p1); // Earth radius at location
if(Cos_p1 >= COS_67P5)
{
Height = W / Cos_p1 - Rn;
}
else
if(Cos_p1 <= -COS_67P5)
{
Height = W / -Cos_p1 - Rn;
}
else
{
Height = Z / Sin_p1 + Rn * (es - 1.0);
}
 
if(!AtPole)
{
lat = Math.Atan(Sin_p1 / Cos_p1);
}
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), Height, };
}
 
double[] DTM00(double[] lonlat)
{
double e0, e1, e2, e3; // eccentricity constants
double e, es, esp; // eccentricity constants
double ml0; // small value m
 
es = 1.0 - Math.Pow(semiMinor / semiMajor, 2);
e = Math.Sqrt(es);
e0 = e0fn(es);
e1 = e1fn(es);
e2 = e2fn(es);
e3 = e3fn(es);
ml0 = semiMajor * mlfn(e0, e1, e2, e3, latOrigin);
esp = es / (1.0 - es);
 
// ...
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
 
double delta_lon = 0.0; // Delta longitude (Given longitude - center)
double sin_phi, cos_phi; // sin and cos value
double al, als; // temporary values
double c, t, tq; // temporary values
double con, n, ml; // cone constant, small m
 
delta_lon = AdjustLongitude(lon - centralMeridian);
SinCos(lat, out sin_phi, out cos_phi);
 
al = cos_phi * delta_lon;
als = Math.Pow(al, 2);
c = esp * Math.Pow(cos_phi, 2);
tq = Math.Tan(lat);
t = Math.Pow(tq, 2);
con = 1.0 - es * Math.Pow(sin_phi, 2);
n = semiMajor / Math.Sqrt(con);
ml = semiMajor * mlfn(e0, e1, e2, e3, lat);
 
double x = scaleFactor * n * al * (1.0 + als / 6.0 * (1.0 - t + c + als / 20.0 *
(5.0 - 18.0 * t + Math.Pow(t, 2) + 72.0 * c - 58.0 * esp))) + falseEasting;
 
double y = scaleFactor * (ml - ml0 + n * tq * (als * (0.5 + als / 24.0 *
(5.0 - t + 9.0 * c + 4.0 * Math.Pow(c, 2) + als / 30.0 * (61.0 - 58.0 * t
+ Math.Pow(t, 2) + 600.0 * c - 330.0 * esp))))) + falseNorthing;
 
if(lonlat.Length < 3)
return new double[] { x / metersPerUnit, y / metersPerUnit };
else
return new double[] { x / metersPerUnit, y / metersPerUnit, lonlat[2] };
}
 
double[] DTM01(double[] lonlat)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor * semiMinor) / (semiMajor * semiMajor);
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor, 2)) / Math.Pow(semiMinor, 2);
 
double ba = semiMinor / semiMajor;
double ab = semiMajor / semiMinor;
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
double h = lonlat.Length < 3 ? 0 : lonlat[2].Equals(Double.NaN) ? 0 : lonlat[2];
double v = semiMajor / Math.Sqrt(1 - es * Math.Pow(Math.Sin(lat), 2));
double x = (v + h) * Math.Cos(lat) * Math.Cos(lon);
double y = (v + h) * Math.Cos(lat) * Math.Sin(lon);
double z = ((1 - es) * v + h) * Math.Sin(lat);
return new double[] { x, y, z, };
}
 
double[] MTD01(double[] pnt)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor2 * semiMinor2) / (semiMajor * semiMajor);
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor2, 2)) / Math.Pow(semiMinor2, 2);
 
double ba = semiMinor2 / semiMajor;
double ab = semiMajor / semiMinor2;
 
bool At_Pole = false; // is location in polar region
double Z = pnt.Length < 3 ? 0 : pnt[2].Equals(Double.NaN) ? 0 : pnt[2];
 
double lon = 0;
double lat = 0;
double Height = 0;
if(pnt[0] != 0.0)
{
lon = Math.Atan2(pnt[1], pnt[0]);
}
else
{
if(pnt[1] > 0)
{
lon = Math.PI / 2;
}
else
if(pnt[1] < 0)
{
lon = -Math.PI * 0.5;
}
else
{
At_Pole = true;
lon = 0.0;
if(Z > 0.0) // north pole
{
lat = Math.PI * 0.5;
}
else
if(Z < 0.0) // south pole
{
lat = -Math.PI * 0.5;
}
else // center of earth
{
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(Math.PI * 0.5), -semiMinor2, };
}
}
}
 
double W2 = pnt[0] * pnt[0] + pnt[1] * pnt[1]; // Square of distance from Z axis
double W = Math.Sqrt(W2); // distance from Z axis
double T0 = Z * AD_C; // initial estimate of vertical component
double S0 = Math.Sqrt(T0 * T0 + W2); //initial estimate of horizontal component
double Sin_B0 = T0 / S0; // sin(B0), B0 is estimate of Bowring aux variable
double Cos_B0 = W / S0; // cos(B0)
double Sin3_B0 = Math.Pow(Sin_B0, 3);
double T1 = Z + semiMinor2 * ses * Sin3_B0; //corrected estimate of vertical component
double Sum = W - semiMajor * es * Cos_B0 * Cos_B0 * Cos_B0; // numerator of cos(phi1)
double S1 = Math.Sqrt(T1 * T1 + Sum * Sum); // corrected estimate of horizontal component
double Sin_p1 = T1 / S1; // sin(phi1), phi1 is estimated latitude
double Cos_p1 = Sum / S1; // cos(phi1)
double Rn = semiMajor / Math.Sqrt(1.0 - es * Sin_p1 * Sin_p1); // Earth radius at location
 
if(Cos_p1 >= COS_67P5)
{
Height = W / Cos_p1 - Rn;
}
else
if(Cos_p1 <= -COS_67P5)
{
Height = W / -Cos_p1 - Rn;
}
else
{
Height = Z / Sin_p1 + Rn * (es - 1.0);
}
 
if(!At_Pole)
{
lat = Math.Atan(Sin_p1 / Cos_p1);
}
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), Height, };
}
 
double[] MTD11(double[] p)
{
double e0, e1, e2, e3; // eccentricity constants
double e, es, esp; // eccentricity constants
double ml0; // small value m
 
es = 1.0 - Math.Pow(semiMinor / semiMajor, 2);
e = Math.Sqrt(es);
e0 = e0fn(es);
e1 = e1fn(es);
e2 = e2fn(es);
e3 = e3fn(es);
ml0 = semiMajor * mlfn(e0, e1, e2, e3, latOrigin);
esp = es / (1.0 - es);
 
// ...
 
double con, phi;
double delta_phi;
long i;
double sin_phi, cos_phi, tan_phi;
double c, cs, t, ts, n, r, d, ds;
long max_iter = 6;
 
double x = p[0] * metersPerUnit - falseEasting;
double y = p[1] * metersPerUnit - falseNorthing;
 
con = (ml0 + y / scaleFactor) / semiMajor;
phi = con;
for(i = 0; ; i++)
{
delta_phi = ((con + e1 * Math.Sin(2.0 * phi) - e2 * Math.Sin(4.0 * phi) + e3 * Math.Sin(6.0 * phi)) / e0) - phi;
phi += delta_phi;
 
if(Math.Abs(delta_phi) <= EPSLoN)
break;
 
if(i >= max_iter)
throw new ArgumentException("Latitude failed to converge");
}
 
if(Math.Abs(phi) < HALF_PI)
{
SinCos(phi, out sin_phi, out cos_phi);
tan_phi = Math.Tan(phi);
c = esp * Math.Pow(cos_phi, 2);
cs = Math.Pow(c, 2);
t = Math.Pow(tan_phi, 2);
ts = Math.Pow(t, 2);
con = 1.0 - es * Math.Pow(sin_phi, 2);
n = semiMajor / Math.Sqrt(con);
r = n * (1.0 - es) / con;
d = x / (n * scaleFactor);
ds = Math.Pow(d, 2);
 
double lat = phi - (n * tan_phi * ds / r) * (0.5 - ds / 24.0 * (5.0 + 3.0 * t +
10.0 * c - 4.0 * cs - 9.0 * esp - ds / 30.0 * (61.0 + 90.0 * t +
298.0 * c + 45.0 * ts - 252.0 * esp - 3.0 * cs)));
 
double lon = AdjustLongitude(centralMeridian + (d * (1.0 - ds / 6.0 * (1.0 + 2.0 * t +
c - ds / 20.0 * (5.0 - 2.0 * c + 28.0 * t - 3.0 * cs + 8.0 * esp +
24.0 * ts))) / cos_phi));
 
if(p.Length < 3)
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat) };
else
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), p[2] };
}
else
{
if(p.Length < 3)
return new double[] { RadiansToDegrees(HALF_PI * Sign(y)), RadiansToDegrees(centralMeridian) };
else
return new double[] { RadiansToDegrees(HALF_PI * Sign(y)), RadiansToDegrees(centralMeridian), p[2] };
}
}
 
#region -- levels info --
/*
"spatialReference":{"wkid":3059,"latestWkid":3059},"singleFusedMapCache":true,
* "tileInfo":{"rows":256,"cols":256,"dpi":96,"format":"PNG8","compressionQuality":0,
* "origin":{"x":-5120900,"y":3998100},
* "spatialReference":{"wkid":3059,"latestWkid":3059},
*
* "lods":[
* {"level":0,"resolution":1587.5031750063501,"scale":6000000},
* {"level":1,"resolution":793.7515875031751,"scale":3000000},
* {"level":2,"resolution":529.1677250021168,"scale":2000000},
* {"level":3,"resolution":264.5838625010584,"scale":1000000},
* {"level":4,"resolution":132.2919312505292,"scale":500000},
* {"level":5,"resolution":52.91677250021167,"scale":200000},
* {"level":6,"resolution":26.458386250105836,"scale":100000},
* {"level":7,"resolution":13.229193125052918,"scale":50000},
* {"level":8,"resolution":6.614596562526459,"scale":25000},
* {"level":9,"resolution":2.6458386250105836,"scale":10000},
* {"level":10,"resolution":1.3229193125052918,"scale":5000},
* {"level":11,"resolution":0.5291677250021167,"scale":2000}]},
*
* "initialExtent":
* {"xmin":352544.7096929534,"ymin":240883.24768736016,
* "xmax":722784.980307047,"ymax":539178.473189597,
* "spatialReference":{"wkid":3059,"latestWkid":3059}},
*
* "fullExtent":
* {"xmin":312773.6900000004,"ymin":172941,
* "xmax":762556,"ymax":438880,
* "spatialReference":{"wkid":3059,"latestWkid":3059}},
*
* "minScale":6000000,"maxScale":2000,"units":"esriMeters","supportedImageFormatTypes":"PNG32,PNG24,PNG,JPG,DIB,TIFF,EMF,PS,PDF,GIF,SVG,SVGZ,BMP",
* "documentInfo":{"Title":"ikartelv","Author":"gstanevicius","Comments":"","Subject":"","Category":"","AntialiasingMode":"None","TextAntialiasingMode":"Force","Keywords":""},"capabilities":"Map,Query,Data","supportedQueryFormats":"JSON, AMF","exportTilesAllowed":false,"maxRecordCount":500,"maxImageHeight":4096,"maxImageWidth":4096,"supportedExtensions":"KmlServer, WMSServer"});
*/
 
#endregion
 
public static double GetTileMatrixResolution(int zoom)
{
double ret = 0;
 
switch(zoom)
{
#region -- sizes --
case 0:
{
ret = 1587.5031750063501;
}
break;
 
case 1:
{
ret = 793.7515875031751;
}
break;
 
case 2:
{
ret = 529.1677250021168;
}
break;
 
case 3:
{
ret = 264.5838625010584;
}
break;
 
case 4:
{
ret = 132.2919312505292;
}
break;
 
case 5:
{
ret = 52.91677250021167;
}
break;
 
case 6:
{
ret = 26.458386250105836;
}
break;
 
case 7:
{
ret = 13.229193125052918;
}
break;
 
case 8:
{
ret = 6.614596562526459;
}
break;
 
case 9:
{
ret = 2.6458386250105836;
}
break;
 
case 10:
{
ret = 1.3229193125052918;
}
break;
 
case 11:
{
ret = 0.5291677250021167;
}
break;
#endregion
}
 
return ret;
}
 
public override double GetGroundResolution(int zoom, double latitude)
{
return GetTileMatrixResolution(zoom);
}
 
Dictionary<int, GSize> extentMatrixMin;
Dictionary<int, GSize> extentMatrixMax;
 
public override GSize GetTileMatrixMinXY(int zoom)
{
if(extentMatrixMin == null)
{
GenerateExtents();
}
return extentMatrixMin[zoom];
}
 
public override GSize GetTileMatrixMaxXY(int zoom)
{
if(extentMatrixMax == null)
{
GenerateExtents();
}
return extentMatrixMax[zoom];
}
 
void GenerateExtents()
{
extentMatrixMin = new Dictionary<int, GSize>();
extentMatrixMax = new Dictionary<int, GSize>();
//RectLatLng Extent = RectLatLng.FromLTRB(219818.60040028347, 6407318.126743601, 747927.9899523959, 5826291.964691277);
 
for(int i = 0; i <= 11; i++)
{
double res = GetTileMatrixResolution(i);
//extentMatrixMin.Add(i, new GSize(FromPixelToTileXY(LksToPixel(new double[]{ Extent.Left, Extent.Top }, res))));
//extentMatrixMax.Add(i, new GSize(FromPixelToTileXY(LksToPixel(new double[] { Extent.Right, Extent.Bottom }, res))));
 
extentMatrixMin.Add(i, new GSize(FromPixelToTileXY(FromLatLngToPixel(Bounds.LocationTopLeft, i))));
extentMatrixMax.Add(i, new GSize(FromPixelToTileXY(FromLatLngToPixel(Bounds.LocationRightBottom, i))));
}
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Projections/MapyCZProjection.cs
0,0 → 1,259

namespace GMap.NET.Projections
{
using System;
 
/// <summary>
/// GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]
/// PROJCS["Mapy.cz",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",15],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",134400000],PARAMETER["false_northing",-41600000],UNIT["1/32meter",0.03125]]
/// </summary>
public class MapyCZProjection : PureProjection
{
public static readonly MapyCZProjection Instance = new MapyCZProjection();
 
static readonly double MinLatitude = 26;
static readonly double MaxLatitude = 76;
static readonly double MinLongitude = -26;
static readonly double MaxLongitude = 38;
 
#region -- Common --
static int getLCM(int zone)
{
if((zone < 1) || (zone > 60))
{
throw new Exception("MapyCZProjection: UTM Zone number is not between 1 and 60.");
}
else
{
return ((zone * 6) - 183);
}
}
 
static double roundoff(double xx, double yy)
{
var x = xx;
var y = yy;
x = Math.Round(x * Math.Pow(10, y)) / Math.Pow(10, y);
return x;
}
 
static readonly double UTMSIZE = 2;
static readonly double UNITS = 1;
 
#endregion
 
#region -- WGSToMapyCZ --
 
public long[] WGSToPP(double la, double lo)
{
var utmEE = wgsToUTM(DegreesToRadians(la), DegreesToRadians(lo), 33);
var pp = utmEEToPP(utmEE[0], utmEE[1]);
return pp;
}
 
static long[] utmEEToPP(double east, double north)
{
var x = (Math.Round(east) - (-3700000.0)) * Math.Pow(2, 5);
var y = (Math.Round(north) - (1300000.0)) * Math.Pow(2, 5);
 
return new long[] { (long)x, (long)y };
}
 
double[] wgsToUTM(double la, double lo, int zone)
{
var latrad = la;
var lonrad = lo;
var latddd = RadiansToDegrees(la);
var londdd = RadiansToDegrees(lo);
 
var k = 0.9996f;
var a = Axis;
var f = Flattening;
var b = a * (1.0 - f);
var e2 = (a * a - b * b) / (a * a);
var e = Math.Sqrt(e2);
var ei2 = (a * a - b * b) / (b * b);
var ei = Math.Sqrt(ei2);
var n = (a - b) / (a + b);
var G = a * (1.0 - n) * (1.0 - n * n) * (1.0 + (9 / 4.0) * n * n + (255.0 / 64.0) * Math.Pow(n, 4)) * (PI / 180.0);
var w = londdd - ((double) (zone * 6 - 183));
w = DegreesToRadians(w);
var t = Math.Tan(latrad);
var rho = a * (1.0 - e2) / Math.Pow(1.0 - (e2 * Math.Sin(latrad) * Math.Sin(latrad)), (3 / 2.0));
var nu = a / Math.Sqrt(1.0 - (e2 * Math.Sin(latrad) * Math.Sin(latrad)));
var psi = nu / rho;
var coslat = Math.Cos(latrad);
var sinlat = Math.Sin(latrad);
var A0 = 1 - (e2 / 4.0) - (3 * e2 * e2 / 64.0) - (5 * Math.Pow(e2, 3) / 256.0);
var A2 = (3 / 8.0) * (e2 + (e2 * e2 / 4.0) + (15 * Math.Pow(e2, 3) / 128.0));
var A4 = (15 / 256.0) * (e2 * e2 + (3 * Math.Pow(e2, 3) / 4.0));
var A6 = 35 * Math.Pow(e2, 3) / 3072.0;
var m = a * ((A0 * latrad) - (A2 * Math.Sin(2 * latrad)) + (A4 * Math.Sin(4 * latrad)) - (A6 * Math.Sin(6 * latrad)));
var eterm1 = (w * w / 6.0) * coslat * coslat * (psi - t * t);
var eterm2 = (Math.Pow(w, 4) / 120.0) * Math.Pow(coslat, 4) * (4 * Math.Pow(psi, 3) * (1.0 - 6 * t * t) + psi * psi * (1.0 + 8 * t * t) - psi * 2 * t * t + Math.Pow(t, 4));
var eterm3 = (Math.Pow(w, 6) / 5040.0) * Math.Pow(coslat, 6) * (61.0 - 479 * t * t + 179 * Math.Pow(t, 4) - Math.Pow(t, 6));
var dE = k * nu * w * coslat * (1.0 + eterm1 + eterm2 + eterm3);
var east = 500000.0 + (dE / UNITS);
east = roundoff(east, UTMSIZE);
var nterm1 = (w * w / 2.0) * nu * sinlat * coslat;
var nterm2 = (Math.Pow(w, 4) / 24.0) * nu * sinlat * Math.Pow(coslat, 3) * (4 * psi * psi + psi - t * t);
var nterm3 = (Math.Pow(w, 6) / 720.0) * nu * sinlat * Math.Pow(coslat, 5) * (8 * Math.Pow(psi, 4) * (11.0 - 24 * t * t) - 28 * Math.Pow(psi, 3) * (1.0 - 6 * t * t) + psi * psi * (1.0 - 32 * t * t) - psi * 2 * t * t + Math.Pow(t, 4));
var nterm4 = (Math.Pow(w, 8) / 40320.0) * nu * sinlat * Math.Pow(coslat, 7) * (1385.0 - 3111 * t * t + 543 * Math.Pow(t, 4) - Math.Pow(t, 6));
var dN = k * (m + nterm1 + nterm2 + nterm3 + nterm4);
var north = (0.0 + (dN / UNITS));
north = roundoff(north, UTMSIZE);
 
return new double[] { east, north, zone };
}
 
#endregion
 
#region -- MapyCZToWGS --
 
public double[] PPToWGS(double x, double y)
{
var utmEE = ppToUTMEE(x, y);
var ret = utmToWGS(utmEE[0], utmEE[1], 33);
return ret;
}
 
double[] ppToUTMEE(double x, double y)
{
var north = y * Math.Pow(2, -5) + 1300000.0;
var east = x * Math.Pow(2, -5) + (-3700000.0);
east = roundoff(east, UTMSIZE);
north = roundoff(north, UTMSIZE);
 
return new double[] { east, north };
}
 
double[] utmToWGS(double eastIn, double northIn, int zone)
{
var k = 0.9996f;
var a = Axis;
var f = Flattening;
var b = a * (1.0 - f);
var e2 = (a * a - b * b) / (a * a);
var e = Math.Sqrt(e2);
var ei2 = (a * a - b * b) / (b * b);
var ei = Math.Sqrt(ei2);
var n = (a - b) / (a + b);
var G = a * (1.0 - n) * (1.0 - n * n) * (1.0 + (9 / 4.0) * n * n + (255 / 64.0) * Math.Pow(n, 4)) * (PI / 180.0);
var north = (northIn - 0) * UNITS;
var east = (eastIn - 500000.0) * UNITS;
var m = north / k;
var sigma = (m * PI) / (180.0 * G);
var footlat = sigma + ((3 * n / 2.0) - (27 * Math.Pow(n, 3) / 32.0)) * Math.Sin(2 * sigma) + ((21 * n * n / 16.0) - (55 * Math.Pow(n, 4) / 32.0)) * Math.Sin(4 * sigma) + (151 * Math.Pow(n, 3) / 96.0) * Math.Sin(6 * sigma) + (1097 * Math.Pow(n, 4) / 512.0) * Math.Sin(8 * sigma);
var rho = a * (1.0 - e2) / Math.Pow(1.0 - (e2 * Math.Sin(footlat) * Math.Sin(footlat)), (3 / 2.0));
var nu = a / Math.Sqrt(1.0 - (e2 * Math.Sin(footlat) * Math.Sin(footlat)));
var psi = nu / rho;
var t = Math.Tan(footlat);
var x = east / (k * nu);
var laterm1 = (t / (k * rho)) * (east * x / 2.0);
var laterm2 = (t / (k * rho)) * (east * Math.Pow(x, 3) / 24.0) * (-4 * psi * psi + 9 * psi * (1 - t * t) + 12 * t * t);
var laterm3 = (t / (k * rho)) * (east * Math.Pow(x, 5) / 720.0) * (8 * Math.Pow(psi, 4) * (11 - 24 * t * t) - 12 * Math.Pow(psi, 3) * (21.0 - 71 * t * t) + 15 * psi * psi * (15.0 - 98 * t * t + 15 * Math.Pow(t, 4)) + 180 * psi * (5 * t * t - 3 * Math.Pow(t, 4)) + 360 * Math.Pow(t, 4));
var laterm4 = (t / (k * rho)) * (east * Math.Pow(x, 7) / 40320.0) * (1385.0 + 3633 * t * t + 4095 * Math.Pow(t, 4) + 1575 * Math.Pow(t, 6));
var latrad = footlat - laterm1 + laterm2 - laterm3 + laterm4;
var lat = RadiansToDegrees(latrad);
var seclat = 1 / Math.Cos(footlat);
var loterm1 = x * seclat;
var loterm2 = (Math.Pow(x, 3) / 6.0) * seclat * (psi + 2 * t * t);
var loterm3 = (Math.Pow(x, 5) / 120.0) * seclat * (-4 * Math.Pow(psi, 3) * (1 - 6 * t * t) + psi * psi * (9 - 68 * t * t) + 72 * psi * t * t + 24 * Math.Pow(t, 4));
var loterm4 = (Math.Pow(x, 7) / 5040.0) * seclat * (61.0 + 662 * t * t + 1320 * Math.Pow(t, 4) + 720 * Math.Pow(t, 6));
var w = loterm1 - loterm2 + loterm3 - loterm4;
var longrad = DegreesToRadians(getLCM(zone)) + w;
var lon = RadiansToDegrees(longrad);
 
return new double[] { lat, lon, latrad, longrad };
}
 
#endregion
 
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
 
public override GSize TileSize
{
get
{
return new GSize(256, 256);
}
}
 
public override double Axis
{
get
{
return 6378137;
}
}
 
public override double Flattening
{
get
{
return (1.0 / 298.257223563);
}
}
 
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
GPoint ret = GPoint.Empty;
 
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
 
var size = GetTileMatrixSizePixel(zoom);
{
var l = WGSToPP(lat, lng);
ret.X = (long)l[0] >> (20 - zoom);
ret.Y = size.Height - ((long)l[1] >> (20 - zoom));
}
return ret;
}
 
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
PointLatLng ret = PointLatLng.Empty;
 
var size = GetTileMatrixSizePixel(zoom);
 
var oX = x << (20 - zoom);
var oY = (size.Height - y) << (20 - zoom);
{
var l = PPToWGS(oX, oY);
ret.Lat = Clip(l[0], MinLatitude, MaxLatitude);
ret.Lng = Clip(l[1], MinLongitude, MaxLongitude);
}
return ret;
}
 
public override GSize GetTileMatrixSizeXY(int zoom)
{
return new GSize((long)Math.Pow(2, zoom), (long)Math.Pow(2, zoom));
}
 
public override GSize GetTileMatrixSizePixel(int zoom)
{
GSize s = GetTileMatrixSizeXY(zoom);
return new GSize(s.Width << 8, s.Height << 8);
}
 
public override GSize GetTileMatrixMinXY(int zoom)
{
long wh = zoom > 3 ? (3 * (long)Math.Pow(2, zoom - 4)) : 1;
return new GSize(wh, wh);
}
 
public override GSize GetTileMatrixMaxXY(int zoom)
{
long wh = (long)Math.Pow(2, zoom) - (long)Math.Pow(2, zoom - 2);
return new GSize(wh, wh);
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Projections/MercatorProjection.cs
0,0 → 1,101

namespace GMap.NET.Projections
{
using System;
 
/// <summary>
/// The Mercator projection
/// PROJCS["World_Mercator",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Mercator"],PARAMETER["False_Easting",0],PARAMETER["False_Northing",0],PARAMETER["Central_Meridian",0],PARAMETER["standard_parallel_1",0],UNIT["Meter",1]]
/// </summary>
public class MercatorProjection : PureProjection
{
public static readonly MercatorProjection Instance = new MercatorProjection();
 
static readonly double MinLatitude = -85.05112878;
static readonly double MaxLatitude = 85.05112878;
static readonly double MinLongitude = -180;
static readonly double MaxLongitude = 180;
 
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
 
readonly GSize tileSize = new GSize(256, 256);
public override GSize TileSize
{
get
{
return tileSize;
}
}
 
public override double Axis
{
get
{
return 6378137;
}
}
 
public override double Flattening
{
get
{
return (1.0 / 298.257223563);
}
}
 
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
GPoint ret = GPoint.Empty;
 
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
 
double x = (lng + 180) / 360;
double sinLatitude = Math.Sin(lat * Math.PI / 180);
double y = 0.5 - Math.Log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI);
 
GSize s = GetTileMatrixSizePixel(zoom);
long mapSizeX = s.Width;
long mapSizeY = s.Height;
 
ret.X = (long)Clip(x * mapSizeX + 0.5, 0, mapSizeX - 1);
ret.Y = (long)Clip(y * mapSizeY + 0.5, 0, mapSizeY - 1);
 
return ret;
}
 
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
PointLatLng ret = PointLatLng.Empty;
 
GSize s = GetTileMatrixSizePixel(zoom);
double mapSizeX = s.Width;
double mapSizeY = s.Height;
 
double xx = (Clip(x, 0, mapSizeX - 1) / mapSizeX) - 0.5;
double yy = 0.5 - (Clip(y, 0, mapSizeY - 1) / mapSizeY);
 
ret.Lat = 90 - 360 * Math.Atan(Math.Exp(-yy * 2 * Math.PI)) / Math.PI;
ret.Lng = 360 * xx;
 
return ret;
}
 
public override GSize GetTileMatrixMinXY(int zoom)
{
return new GSize(0, 0);
}
 
public override GSize GetTileMatrixMaxXY(int zoom)
{
long xy = (1 << zoom);
return new GSize(xy - 1, xy - 1);
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Projections/MercatorProjectionYandex.cs
0,0 → 1,113

namespace GMap.NET.Projections
{
using System;
 
class MercatorProjectionYandex : PureProjection
{
public static readonly MercatorProjectionYandex Instance = new MercatorProjectionYandex();
 
static readonly double MinLatitude = -85.05112878;
static readonly double MaxLatitude = 85.05112878;
static readonly double MinLongitude = -177;
static readonly double MaxLongitude = 177;
 
static readonly double RAD_DEG = 180 / Math.PI;
static readonly double DEG_RAD = Math.PI / 180;
static readonly double MathPiDiv4 = Math.PI / 4;
 
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
 
GSize tileSize = new GSize(256, 256);
public override GSize TileSize
{
get
{
return tileSize;
}
}
 
public override double Axis
{
get
{
return 6356752.3142;
}
}
 
public override double Flattening
{
get
{
return (1.0 / 298.257223563);
}
}
 
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
 
double rLon = lng * DEG_RAD; // Math.PI / 180;
double rLat = lat * DEG_RAD; // Math.PI / 180;
 
double a = 6378137;
double k = 0.0818191908426;
 
double z = Math.Tan(MathPiDiv4 + rLat / 2) / Math.Pow((Math.Tan(MathPiDiv4 + Math.Asin(k * Math.Sin(rLat)) / 2)), k);
double z1 = Math.Pow(2, 23 - zoom);
 
double DX = ((20037508.342789 + a * rLon) * 53.5865938 / z1);
double DY = ((20037508.342789 - a * Math.Log(z)) * 53.5865938 / z1);
 
GPoint ret = GPoint.Empty;
ret.X = (long)DX;
ret.Y = (long)DY;
 
return ret;
}
 
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
GSize s = GetTileMatrixSizePixel(zoom);
 
double mapSizeX = s.Width;
double mapSizeY = s.Height;
 
double a = 6378137;
double c1 = 0.00335655146887969;
double c2 = 0.00000657187271079536;
double c3 = 0.00000001764564338702;
double c4 = 0.00000000005328478445;
double z1 = (23 - zoom);
double mercX = (x * Math.Pow(2, z1)) / 53.5865938 - 20037508.342789;
double mercY = 20037508.342789 - (y * Math.Pow(2, z1)) / 53.5865938;
 
double g = Math.PI / 2 - 2 * Math.Atan(1 / Math.Exp(mercY / a));
double z = g + c1 * Math.Sin(2 * g) + c2 * Math.Sin(4 * g) + c3 * Math.Sin(6 * g) + c4 * Math.Sin(8 * g);
 
PointLatLng ret = PointLatLng.Empty;
ret.Lat = z * RAD_DEG;
ret.Lng = mercX / a * RAD_DEG;
 
return ret;
}
 
public override GSize GetTileMatrixMinXY(int zoom)
{
return new GSize(0, 0);
}
 
public override GSize GetTileMatrixMaxXY(int zoom)
{
long xy = (1 << zoom);
return new GSize(xy - 1, xy - 1);
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Projections/PlateCarreeProjection.cs
0,0 → 1,98

namespace GMap.NET.Projections
{
using System;
 
/// <summary>
/// Plate Carrée (literally, “plane square”) projection
/// PROJCS["WGS 84 / World Equidistant Cylindrical",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],UNIT["Meter",1]]
/// </summary>
public class PlateCarreeProjection : PureProjection
{
public static readonly PlateCarreeProjection Instance = new PlateCarreeProjection();
 
static readonly double MinLatitude = -85.05112878;
static readonly double MaxLatitude = 85.05112878;
static readonly double MinLongitude = -180;
static readonly double MaxLongitude = 180;
 
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
 
GSize tileSize = new GSize(512, 512);
public override GSize TileSize
{
get
{
return tileSize;
}
}
 
public override double Axis
{
get
{
return 6378137;
}
}
 
public override double Flattening
{
get
{
return (1.0 / 298.257223563);
}
}
 
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
GPoint ret = GPoint.Empty;
 
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
 
GSize s = GetTileMatrixSizePixel(zoom);
double mapSizeX = s.Width;
double mapSizeY = s.Height;
 
double scale = 360.0 / mapSizeX;
 
ret.Y = (long)((90.0 - lat) / scale);
ret.X = (long)((lng + 180.0) / scale);
 
return ret;
}
 
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
PointLatLng ret = PointLatLng.Empty;
 
GSize s = GetTileMatrixSizePixel(zoom);
double mapSizeX = s.Width;
double mapSizeY = s.Height;
 
double scale = 360.0 / mapSizeX;
 
ret.Lat = 90 - (y * scale);
ret.Lng = (x * scale) - 180;
 
return ret;
}
 
public override GSize GetTileMatrixMaxXY(int zoom)
{
long y = (long)Math.Pow(2, zoom);
return new GSize((2 * y) - 1, y - 1);
}
 
public override GSize GetTileMatrixMinXY(int zoom)
{
return new GSize(0, 0);
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Projections/PlateCarreeProjectionDarbAe.cs
0,0 → 1,230

namespace GMap.NET.Projections
{
using System;
 
/// <summary>
/// Plate Carrée (literally, “plane square”) projection
/// PROJCS["WGS 84 / World Equidistant Cylindrical",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],UNIT["Meter",1]]
///
///"spatialReference":
///{"wkid":4326},"singleFusedMapCache":true,"tileInfo":
///{"rows":256,"cols":256,"dpi":96,"format":"PNG8","compressionQuality":0,
///"origin":{"x":-400,"y":400},"spatialReference":{"wkid":4326},"lods":
///
///[{"level":0,"resolution":0.0118973050291514,"scale":5000000},
///{"level":1,"resolution":0.0059486525145757,"scale":2500000},
///{"level":2,"resolution":0.00297432625728785,"scale":1250000},
///{"level":3,"resolution":0.00118973050291514,"scale":500000},
///{"level":4,"resolution":0.00059486525145757,"scale":250000},
///{"level":5,"resolution":0.000356919150874542,"scale":150000},
///{"level":6,"resolution":0.000178459575437271,"scale":75000},
///{"level":7,"resolution":0.000118973050291514,"scale":50000},
///{"level":8,"resolution":5.9486525145757E-05,"scale":25000},
///{"level":9,"resolution":3.56919150874542E-05,"scale":15000},
///{"level":10,"resolution":1.90356880466422E-05,"scale":8000},
///{"level":11,"resolution":9.51784402332112E-06,"scale":4000},
///{"level":12,"resolution":4.75892201166056E-06,"scale":2000}]},
///
///"initialExtent":
///{"xmin":42.1125196069871,"ymin":18.6650706214551,"xmax":65.698643558112
///4,"ymax":29.4472987133981,"spatialReference":{"wkid":4326}},
///
///"fullExtent":
///{"xmin":41.522866508209,"ymin":18.7071563263201,"xmax":66.2882966568906
///,"ymax":29.4052130085331,"spatialReference":{"wkid":4326}},
///
///"units":"esriDecimalDegrees"
/// </summary>
public class PlateCarreeProjectionDarbAe : PureProjection
{
public static readonly PlateCarreeProjectionDarbAe Instance = new PlateCarreeProjectionDarbAe();
 
public static readonly double MinLatitude = 18.7071563263201;
public static readonly double MaxLatitude = 29.4052130085331;
public static readonly double MinLongitude = 41.522866508209;
public static readonly double MaxLongitude = 66.2882966568906;
 
static readonly double orignX = -400;
static readonly double orignY = 400;
 
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
 
GSize tileSize = new GSize(256, 256);
public override GSize TileSize
{
get
{
return tileSize;
}
}
 
public override double Axis
{
get
{
return 6378137;
}
}
 
public override double Flattening
{
get
{
return (1.0 / 298.257223563);
}
}
 
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
GPoint ret = GPoint.Empty;
 
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
 
/*
getContainingTileCoords:function(ti,_1dd,lod)
{
var to=ti.origin,
res=lod.resolution,
tmw=ti.width*res,
tmh=ti.height*res,
tc=Math.floor((_1dd.x-to.x)/tmw),
tr=Math.floor((to.y-_1dd.y)/tmh);
}
*/
 
double res = GetTileMatrixResolution(zoom);
 
ret.X = (long)Math.Floor((lng - orignX) / res);
ret.Y = (long)Math.Floor((orignY - lat) / res);
 
return ret;
}
 
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
PointLatLng ret = PointLatLng.Empty;
 
double res = GetTileMatrixResolution(zoom);
 
ret.Lat = orignY - (y * res);
ret.Lng = (x * res) + orignX;
 
return ret;
}
 
public static double GetTileMatrixResolution(int zoom)
{
double ret = 0;
 
switch(zoom)
{
#region -- sizes --
case 0:
{
ret = 0.0118973050291514;
}
break;
 
case 1:
{
ret = 0.0059486525145757;
}
break;
 
case 2:
{
ret = 0.00297432625728785;
}
break;
 
case 3:
{
ret = 0.00118973050291514;
}
break;
 
case 4:
{
ret = 0.00059486525145757;
}
break;
 
case 5:
{
ret = 0.000356919150874542;
}
break;
 
case 6:
{
ret = 0.000178459575437271;
}
break;
 
case 7:
{
ret = 0.000118973050291514;
}
break;
 
case 8:
{
ret = 5.9486525145757E-05;
}
break;
 
case 9:
{
ret = 3.56919150874542E-05;
}
break;
 
case 10:
{
ret = 1.90356880466422E-05;
}
break;
 
case 11:
{
ret = 9.51784402332112E-06;
}
break;
 
case 12:
{
ret = 4.75892201166056E-06;
}
break;
#endregion
}
 
return ret;
}
 
public override double GetGroundResolution(int zoom, double latitude)
{
return GetTileMatrixResolution(zoom);
}
 
public override GSize GetTileMatrixMaxXY(int zoom)
{
var maxPx = FromLatLngToPixel(MinLatitude, MaxLongitude, zoom);
return new GSize(FromPixelToTileXY(maxPx));
}
 
public override GSize GetTileMatrixMinXY(int zoom)
{
var minPx = FromLatLngToPixel(MaxLatitude, MinLongitude, zoom);
return new GSize(FromPixelToTileXY(minPx));
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Projections/PlateCarreeProjectionPergo.cs
0,0 → 1,100

namespace GMap.NET.Projections
{
#if OLD_PERGO
using System;
 
/// <summary>
/// Plate Carrée (literally, “plane square”) projection
/// PROJCS["WGS 84 / World Equidistant Cylindrical",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],UNIT["Meter",1]]
/// </summary>
public class PlateCarreeProjectionPergo : PureProjection
{
public static readonly PlateCarreeProjectionPergo Instance = new PlateCarreeProjectionPergo();
 
static readonly double MinLatitude = -85.05112878;
static readonly double MaxLatitude = 85.05112878;
static readonly double MinLongitude = -180;
static readonly double MaxLongitude = 180;
 
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
 
GSize tileSize = new GSize(256, 256);
public override GSize TileSize
{
get
{
return tileSize;
}
}
 
public override double Axis
{
get
{
return 6378137;
}
}
 
public override double Flattening
{
get
{
return (1.0 / 298.257223563);
}
}
 
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
GPoint ret = GPoint.Empty;
 
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
 
GSize s = GetTileMatrixSizePixel(zoom);
double mapSizeX = s.Width;
double mapSizeY = s.Height;
 
double scale = 360.0 / mapSizeX;
 
ret.Y = (long)((90.0 - lat) / scale);
ret.X = (long)((lng + 180.0) / scale);
 
return ret;
}
 
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
PointLatLng ret = PointLatLng.Empty;
 
GSize s = GetTileMatrixSizePixel(zoom);
double mapSizeX = s.Width;
double mapSizeY = s.Height;
 
double scale = 360.0 / mapSizeX;
 
ret.Lat = 90 - (y * scale);
ret.Lng = (x * scale) - 180;
 
return ret;
}
 
public override GSize GetTileMatrixMaxXY(int zoom)
{
long y = (long)Math.Pow(2, zoom);
return new GSize((2*y) - 1, y - 1);
}
 
public override GSize GetTileMatrixMinXY(int zoom)
{
return new GSize(0, 0);
}
}
#endif
}
/MKLiveView/v1.0/Source/GMap.NET.Core/GMap.NET.Projections/SWEREF99_TMProjection.cs
0,0 → 1,520

namespace GMap.NET.Projections
{
using System;
using System.Collections.Generic;
 
/// <summary>
/// PROJCS["SWEREF99 TM",GEOGCS["SWEREF99",DATUM["SWEREF99",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6619"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4619"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],
/// PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",15],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],AUTHORITY["EPSG","3006"],AXIS["y",EAST],AXIS["x",NORTH]]
/// </summary>
public class SWEREF99_TMProjection : PureProjection
{
public static readonly SWEREF99_TMProjection Instance = new SWEREF99_TMProjection();
 
static readonly double MinLatitude = 54.96;
static readonly double MaxLatitude = 69.07;
static readonly double MinLongitude = 10.0;
static readonly double MaxLongitude = 24.5;
 
static readonly double orignX = -1200000;
static readonly double orignY = 8500000;
 
static readonly double scaleFactor = 0.9996; // scale factor
static readonly double centralMeridian = DegreesToRadians(15);// Center longitude (projection center)
static readonly double latOrigin = 0.0; // center latitude
static readonly double falseNorthing = 0.0; // y offset in meters
static readonly double falseEasting = 500000.0; // x offset in meters
static readonly double semiMajor = 6378137.0; // major axis
static readonly double semiMinor = 6356752.3141403561; // minor axis
static readonly double semiMinor2 = 6356752.3142451793; // minor axis
static readonly double metersPerUnit = 1.0;
static readonly double COS_67P5 = 0.38268343236508977; // cosine of 67.5 degrees
static readonly double AD_C = 1.0026000; // Toms region 1 constant
 
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
 
GSize tileSize = new GSize(256, 256);
public override GSize TileSize
{
get
{
return tileSize;
}
}
 
public override double Axis
{
get
{
return 6378137;
}
}
 
public override double Flattening
{
get
{
return (1.0 / 298.257222101);
}
}
 
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
GPoint ret = GPoint.Empty;
 
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
 
double[] lks = new double[] { lng, lat };
lks = DTM10(lks);
lks = MTD10(lks);
lks = DTM00(lks);
 
double res = GetTileMatrixResolution(zoom);
return LksToPixel(lks, res);
}
 
static GPoint LksToPixel(double[] lks, double res)
{
return new GPoint((long)Math.Floor((lks[0] - orignX) / res), (long)Math.Floor((orignY - lks[1]) / res));
}
 
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
PointLatLng ret = PointLatLng.Empty;
 
double res = GetTileMatrixResolution(zoom);
 
double[] lks = new double[] { (x * res) + orignX, orignY - (y * res) };
lks = MTD11(lks);
lks = DTM10(lks);
lks = MTD10(lks);
 
ret.Lat = Clip(lks[1], MinLatitude, MaxLatitude);
ret.Lng = Clip(lks[0], MinLongitude, MaxLongitude);
 
return ret;
}
 
double[] DTM10(double[] lonlat)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor2 * semiMinor2) / (semiMajor * semiMajor); // e^2
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor2, 2)) / Math.Pow(semiMinor2, 2);
 
double ba = semiMinor2 / semiMajor;
double ab = semiMajor / semiMinor2;
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
double h = lonlat.Length < 3 ? 0 : lonlat[2].Equals(Double.NaN) ? 0 : lonlat[2];
double v = semiMajor / Math.Sqrt(1 - es * Math.Pow(Math.Sin(lat), 2));
double x = (v + h) * Math.Cos(lat) * Math.Cos(lon);
double y = (v + h) * Math.Cos(lat) * Math.Sin(lon);
double z = ((1 - es) * v + h) * Math.Sin(lat);
return new double[] { x, y, z, };
}
 
double[] MTD10(double[] pnt)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor * semiMinor) / (semiMajor * semiMajor); // e^2
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor, 2)) / Math.Pow(semiMinor, 2);
 
double ba = semiMinor / semiMajor;
double ab = semiMajor / semiMinor;
 
bool AtPole = false; // is location in polar region
double Z = pnt.Length < 3 ? 0 : pnt[2].Equals(Double.NaN) ? 0 : pnt[2];
 
double lon = 0;
double lat = 0;
double Height = 0;
if (pnt[0] != 0.0)
{
lon = Math.Atan2(pnt[1], pnt[0]);
}
else
{
if (pnt[1] > 0)
{
lon = Math.PI / 2;
}
else
if (pnt[1] < 0)
{
lon = -Math.PI * 0.5;
}
else
{
AtPole = true;
lon = 0.0;
if (Z > 0.0) // north pole
{
lat = Math.PI * 0.5;
}
else
if (Z < 0.0) // south pole
{
lat = -Math.PI * 0.5;
}
else // center of earth
{
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(Math.PI * 0.5), -semiMinor, };
}
}
}
double W2 = pnt[0] * pnt[0] + pnt[1] * pnt[1]; // Square of distance from Z axis
double W = Math.Sqrt(W2); // distance from Z axis
double T0 = Z * AD_C; // initial estimate of vertical component
double S0 = Math.Sqrt(T0 * T0 + W2); // initial estimate of horizontal component
double Sin_B0 = T0 / S0; // sin(B0), B0 is estimate of Bowring aux variable
double Cos_B0 = W / S0; // cos(B0)
double Sin3_B0 = Math.Pow(Sin_B0, 3);
double T1 = Z + semiMinor * ses * Sin3_B0; // corrected estimate of vertical component
double Sum = W - semiMajor * es * Cos_B0 * Cos_B0 * Cos_B0; // numerator of cos(phi1)
double S1 = Math.Sqrt(T1 * T1 + Sum * Sum); // corrected estimate of horizontal component
double Sin_p1 = T1 / S1; // sin(phi1), phi1 is estimated latitude
double Cos_p1 = Sum / S1; // cos(phi1)
double Rn = semiMajor / Math.Sqrt(1.0 - es * Sin_p1 * Sin_p1); // Earth radius at location
if (Cos_p1 >= COS_67P5)
{
Height = W / Cos_p1 - Rn;
}
else
if (Cos_p1 <= -COS_67P5)
{
Height = W / -Cos_p1 - Rn;
}
else
{
Height = Z / Sin_p1 + Rn * (es - 1.0);
}
 
if (!AtPole)
{
lat = Math.Atan(Sin_p1 / Cos_p1);
}
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), Height, };
}
 
double[] DTM00(double[] lonlat)
{
double e0, e1, e2, e3; // eccentricity constants
double e, es, esp; // eccentricity constants
double ml0; // small value m
 
es = 1.0 - Math.Pow(semiMinor / semiMajor, 2);
e = Math.Sqrt(es);
e0 = e0fn(es);
e1 = e1fn(es);
e2 = e2fn(es);
e3 = e3fn(es);
ml0 = semiMajor * mlfn(e0, e1, e2, e3, latOrigin);
esp = es / (1.0 - es);
 
// ...
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
 
double delta_lon = 0.0; // Delta longitude (Given longitude - center)
double sin_phi, cos_phi; // sin and cos value
double al, als; // temporary values
double c, t, tq; // temporary values
double con, n, ml; // cone constant, small m
 
delta_lon = AdjustLongitude(lon - centralMeridian);
SinCos(lat, out sin_phi, out cos_phi);
 
al = cos_phi * delta_lon;
als = Math.Pow(al, 2);
c = esp * Math.Pow(cos_phi, 2);
tq = Math.Tan(lat);
t = Math.Pow(tq, 2);
con = 1.0 - es * Math.Pow(sin_phi, 2);
n = semiMajor / Math.Sqrt(con);
ml = semiMajor * mlfn(e0, e1, e2, e3, lat);
 
double x = scaleFactor * n * al * (1.0 + als / 6.0 * (1.0 - t + c + als / 20.0 *
(5.0 - 18.0 * t + Math.Pow(t, 2) + 72.0 * c - 58.0 * esp))) + falseEasting;
 
double y = scaleFactor * (ml - ml0 + n * tq * (als * (0.5 + als / 24.0 *
(5.0 - t + 9.0 * c + 4.0 * Math.Pow(c, 2) + als / 30.0 * (61.0 - 58.0 * t
+ Math.Pow(t, 2) + 600.0 * c - 330.0 * esp))))) + falseNorthing;
 
if (lonlat.Length < 3)
return new double[] { x / metersPerUnit, y / metersPerUnit };
else
return new double[] { x / metersPerUnit, y / metersPerUnit, lonlat[2] };
}
 
double[] DTM01(double[] lonlat)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor * semiMinor) / (semiMajor * semiMajor);
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor, 2)) / Math.Pow(semiMinor, 2);
 
double ba = semiMinor / semiMajor;
double ab = semiMajor / semiMinor;
 
double lon = DegreesToRadians(lonlat[0]);
double lat = DegreesToRadians(lonlat[1]);
double h = lonlat.Length < 3 ? 0 : lonlat[2].Equals(Double.NaN) ? 0 : lonlat[2];
double v = semiMajor / Math.Sqrt(1 - es * Math.Pow(Math.Sin(lat), 2));
double x = (v + h) * Math.Cos(lat) * Math.Cos(lon);
double y = (v + h) * Math.Cos(lat) * Math.Sin(lon);
double z = ((1 - es) * v + h) * Math.Sin(lat);
return new double[] { x, y, z, };
}
 
double[] MTD01(double[] pnt)
{
// Eccentricity squared : (a^2 - b^2)/a^2
double es = 1.0 - (semiMinor2 * semiMinor2) / (semiMajor * semiMajor);
 
// Second eccentricity squared : (a^2 - b^2)/b^2
double ses = (Math.Pow(semiMajor, 2) - Math.Pow(semiMinor2, 2)) / Math.Pow(semiMinor2, 2);
 
double ba = semiMinor2 / semiMajor;
double ab = semiMajor / semiMinor2;
 
bool At_Pole = false; // is location in polar region
double Z = pnt.Length < 3 ? 0 : pnt[2].Equals(Double.NaN) ? 0 : pnt[2];
 
double lon = 0;
double lat = 0;
double Height = 0;
if (pnt[0] != 0.0)
{
lon = Math.Atan2(pnt[1], pnt[0]);
}
else
{
if (pnt[1] > 0)
{
lon = Math.PI / 2;
}
else
if (pnt[1] < 0)
{
lon = -Math.PI * 0.5;
}
else
{
At_Pole = true;
lon = 0.0;
if (Z > 0.0) // north pole
{
lat = Math.PI * 0.5;
}
else
if (Z < 0.0) // south pole
{
lat = -Math.PI * 0.5;
}
else // center of earth
{
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(Math.PI * 0.5), -semiMinor2, };
}
}
}
 
double W2 = pnt[0] * pnt[0] + pnt[1] * pnt[1]; // Square of distance from Z axis
double W = Math.Sqrt(W2); // distance from Z axis
double T0 = Z * AD_C; // initial estimate of vertical component
double S0 = Math.Sqrt(T0 * T0 + W2); //initial estimate of horizontal component
double Sin_B0 = T0 / S0; // sin(B0), B0 is estimate of Bowring aux variable
double Cos_B0 = W / S0; // cos(B0)
double Sin3_B0 = Math.Pow(Sin_B0, 3);
double T1 = Z + semiMinor2 * ses * Sin3_B0; //corrected estimate of vertical component
double Sum = W - semiMajor * es * Cos_B0 * Cos_B0 * Cos_B0; // numerator of cos(phi1)
double S1 = Math.Sqrt(T1 * T1 + Sum * Sum); // corrected estimate of horizontal component
double Sin_p1 = T1 / S1; // sin(phi1), phi1 is estimated latitude
double Cos_p1 = Sum / S1; // cos(phi1)
double Rn = semiMajor / Math.Sqrt(1.0 - es * Sin_p1 * Sin_p1); // Earth radius at location
 
if (Cos_p1 >= COS_67P5)
{
Height = W / Cos_p1 - Rn;
}
else
if (Cos_p1 <= -COS_67P5)
{
Height = W / -Cos_p1 - Rn;
}
else
{
Height = Z / Sin_p1 + Rn * (es - 1.0);
}
 
if (!At_Pole)
{
lat = Math.Atan(Sin_p1 / Cos_p1);
}
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), Height, };
}
 
double[] MTD11(double[] p)
{
double e0, e1, e2, e3; // eccentricity constants
double e, es, esp; // eccentricity constants
double ml0; // small value m
 
es = 1.0 - Math.Pow(semiMinor / semiMajor, 2);
e = Math.Sqrt(es);
e0 = e0fn(es);
e1 = e1fn(es);
e2 = e2fn(es);
e3 = e3fn(es);
ml0 = semiMajor * mlfn(e0, e1, e2, e3, latOrigin);
esp = es / (1.0 - es);
 
// ...
 
double con, phi;
double delta_phi;
long i;
double sin_phi, cos_phi, tan_phi;
double c, cs, t, ts, n, r, d, ds;
long max_iter = 6;
 
double x = p[0] * metersPerUnit - falseEasting;
double y = p[1] * metersPerUnit - falseNorthing;
 
con = (ml0 + y / scaleFactor) / semiMajor;
phi = con;
for (i = 0; ; i++)
{
delta_phi = ((con + e1 * Math.Sin(2.0 * phi) - e2 * Math.Sin(4.0 * phi) + e3 * Math.Sin(6.0 * phi)) / e0) - phi;
phi += delta_phi;
 
if (Math.Abs(delta_phi) <= EPSLoN)
break;
 
if (i >= max_iter)
throw new ArgumentException("Latitude failed to converge");
}
 
if (Math.Abs(phi) < HALF_PI)
{
SinCos(phi, out sin_phi, out cos_phi);
tan_phi = Math.Tan(phi);
c = esp * Math.Pow(cos_phi, 2);
cs = Math.Pow(c, 2);
t = Math.Pow(tan_phi, 2);
ts = Math.Pow(t, 2);
con = 1.0 - es * Math.Pow(sin_phi, 2);
n = semiMajor / Math.Sqrt(con);
r = n * (1.0 - es) / con;
d = x / (n * scaleFactor);
ds = Math.Pow(d, 2);
 
double lat = phi - (n * tan_phi * ds / r) * (0.5 - ds / 24.0 * (5.0 + 3.0 * t +
10.0 * c - 4.0 * cs - 9.0 * esp - ds / 30.0 * (61.0 + 90.0 * t +
298.0 * c + 45.0 * ts - 252.0 * esp - 3.0 * cs)));
 
double lon = AdjustLongitude(centralMeridian + (d * (1.0 - ds / 6.0 * (1.0 + 2.0 * t +
c - ds / 20.0 * (5.0 - 2.0 * c + 28.0 * t - 3.0 * cs + 8.0 * esp +
24.0 * ts))) / cos_phi));
 
if (p.Length < 3)
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat) };
else
return new double[] { RadiansToDegrees(lon), RadiansToDegrees(lat), p[2] };
}
else
{
if (p.Length < 3)
return new double[] { RadiansToDegrees(HALF_PI * Sign(y)), RadiansToDegrees(centralMeridian) };
else
return new double[] { RadiansToDegrees(HALF_PI * Sign(y)), RadiansToDegrees(centralMeridian), p[2] };
}
}
 
#region -- levels info --
// "defaultLayer" : "topowebbwmts",
// "extent" : {
// "left" : -1200000,
// "bottom" : 4700000,
// "right" : 2600000,
// "top" : 8500000
// },
// "projection" : "EPSG:3006",
// "units" : "m",
// "allOverlays" : true,
// "resolutions" : [4096.0, 2048.0, 1024.0, 512.0, 256.0, 128.0, 64.0, 32.0, 16.0, 8.0, 4.0, 2.0, 1.0, 0.5, 0.25, 0.15, 0.1, 0.05, 0.01],
// "initPosition" : {
// "n" : 6607899,
// "e" : 564931,
// "zoom" : 2
// },
#endregion
 
static double[] resolutions = new double[] { 4096.0, 2048.0, 1024.0, 512.0, 256.0, 128.0, 64.0, 32.0, 16.0, 8.0, 4.0, 2.0, 1.0, 0.5, 0.25, 0.15, 0.1, 0.05, 0.01 };
public static double GetTileMatrixResolution(int zoom)
{
double ret = 0;
 
if (zoom < resolutions.Length)
{
ret = resolutions[zoom];
}
 
return ret;
}
 
public override double GetGroundResolution(int zoom, double latitude)
{
return GetTileMatrixResolution(zoom);
}
 
Dictionary<int, GSize> extentMatrixMin;
Dictionary<int, GSize> extentMatrixMax;
 
public override GSize GetTileMatrixMinXY(int zoom)
{
if (extentMatrixMin == null)
{
GenerateExtents();
}
return extentMatrixMin[zoom];
}
 
public override GSize GetTileMatrixMaxXY(int zoom)
{
if (extentMatrixMax == null)
{
GenerateExtents();
}
return extentMatrixMax[zoom];
}
 
void GenerateExtents()
{
extentMatrixMin = new Dictionary<int, GSize>();
extentMatrixMax = new Dictionary<int, GSize>();
 
for (int i = 0; i <= resolutions.Length; i++)
{
double res = GetTileMatrixResolution(i);
 
extentMatrixMin.Add(i, new GSize(FromPixelToTileXY(FromLatLngToPixel(Bounds.LocationTopLeft, i))));
extentMatrixMax.Add(i, new GSize(FromPixelToTileXY(FromLatLngToPixel(Bounds.LocationRightBottom, i))));
}
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/Properties/AssemblyInfo.cs
0,0 → 1,40
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
 
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GMap.NET.Core")]
[assembly: AssemblyDescription("GMap.NET - Great Maps")]
[assembly: AssemblyProduct("GMap.NET.Core")]
 
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]
 
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("843e1f67-489b-4454-b451-021e5c526e30")]
 
// internal visibility
[assembly:
#if DEBUG
InternalsVisibleTo("ConsoleApplication, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cd251b0b8f7079914bbe3e5655d92e5427218f3f0241537a9cb7467b6da2aa5cb20915c31400800e3081d20e6454a35164600fe8bf4f846744f211e040588260cc872c78abd91b422c60071bfda5f11d251eb09f0935944b41de2a28374ad17e8c963d642310df9050e8ae0f1a2b867bcc8f035e4b353dc699cfc7125b9661ce"),
#endif
InternalsVisibleTo("GMap.NET.WindowsForms, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cd251b0b8f7079914bbe3e5655d92e5427218f3f0241537a9cb7467b6da2aa5cb20915c31400800e3081d20e6454a35164600fe8bf4f846744f211e040588260cc872c78abd91b422c60071bfda5f11d251eb09f0935944b41de2a28374ad17e8c963d642310df9050e8ae0f1a2b867bcc8f035e4b353dc699cfc7125b9661ce"),
InternalsVisibleTo("GMap.NET.WindowsMobile, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cd251b0b8f7079914bbe3e5655d92e5427218f3f0241537a9cb7467b6da2aa5cb20915c31400800e3081d20e6454a35164600fe8bf4f846744f211e040588260cc872c78abd91b422c60071bfda5f11d251eb09f0935944b41de2a28374ad17e8c963d642310df9050e8ae0f1a2b867bcc8f035e4b353dc699cfc7125b9661ce"),
InternalsVisibleTo("GMap.NET.WindowsPresentation, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cd251b0b8f7079914bbe3e5655d92e5427218f3f0241537a9cb7467b6da2aa5cb20915c31400800e3081d20e6454a35164600fe8bf4f846744f211e040588260cc872c78abd91b422c60071bfda5f11d251eb09f0935944b41de2a28374ad17e8c963d642310df9050e8ae0f1a2b867bcc8f035e4b353dc699cfc7125b9661ce")]
 
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.5.3.3")]
//[assembly: AssemblyFileVersion("1.5.3.3")]
/MKLiveView/v1.0/Source/GMap.NET.Core/Properties/Resources.Designer.cs
0,0 → 1,107
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.235
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
 
namespace GMap.NET.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GMap.NET.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to CREATE TABLE IF NOT EXISTS Tiles (id INTEGER NOT NULL PRIMARY KEY, X INTEGER NOT NULL, Y INTEGER NOT NULL, Zoom INTEGER NOT NULL, Type UNSIGNED INTEGER NOT NULL, CacheTime DATETIME);
///CREATE INDEX IF NOT EXISTS IndexOfTiles ON Tiles (X, Y, Zoom, Type);
///
///CREATE TABLE IF NOT EXISTS TilesData (id INTEGER NOT NULL PRIMARY KEY CONSTRAINT fk_Tiles_id REFERENCES Tiles(id) ON DELETE CASCADE, Tile BLOB NULL);
///
///-- Foreign Key Preventing insert
///CREATE TRIGGER fki_TilesData_id_Tiles_id
///BEFORE INSERT ON [TilesDat [rest of string was truncated]&quot;;.
/// </summary>
internal static string CreateTileDb {
get {
return ResourceManager.GetString("CreateTileDb", resourceCulture);
}
}
internal static byte[] System_Data_SQLite_x64_NET2_dll {
get {
object obj = ResourceManager.GetObject("System_Data_SQLite_x64_NET2_dll", resourceCulture);
return ((byte[])(obj));
}
}
internal static byte[] System_Data_SQLite_x64_NET4_dll {
get {
object obj = ResourceManager.GetObject("System_Data_SQLite_x64_NET4_dll", resourceCulture);
return ((byte[])(obj));
}
}
internal static byte[] System_Data_SQLite_x86_NET2_dll {
get {
object obj = ResourceManager.GetObject("System_Data_SQLite_x86_NET2_dll", resourceCulture);
return ((byte[])(obj));
}
}
internal static byte[] System_Data_SQLite_x86_NET4_dll {
get {
object obj = ResourceManager.GetObject("System_Data_SQLite_x86_NET4_dll", resourceCulture);
return ((byte[])(obj));
}
}
}
}
/MKLiveView/v1.0/Source/GMap.NET.Core/Properties/Resources.resx
0,0 → 1,162
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
 
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CreateTileDb" xml:space="preserve">
<value>CREATE TABLE IF NOT EXISTS Tiles (id INTEGER NOT NULL PRIMARY KEY, X INTEGER NOT NULL, Y INTEGER NOT NULL, Zoom INTEGER NOT NULL, Type UNSIGNED INTEGER NOT NULL, CacheTime DATETIME);
CREATE INDEX IF NOT EXISTS IndexOfTiles ON Tiles (X, Y, Zoom, Type);
 
CREATE TABLE IF NOT EXISTS TilesData (id INTEGER NOT NULL PRIMARY KEY CONSTRAINT fk_Tiles_id REFERENCES Tiles(id) ON DELETE CASCADE, Tile BLOB NULL);
 
-- Foreign Key Preventing insert
CREATE TRIGGER fki_TilesData_id_Tiles_id
BEFORE INSERT ON [TilesData]
FOR EACH ROW BEGIN
SELECT RAISE(ROLLBACK, 'insert on table "TilesData" violates foreign key constraint "fki_TilesData_id_Tiles_id"')
WHERE (SELECT id FROM Tiles WHERE id = NEW.id) IS NULL;
END;
 
-- Foreign key preventing update
CREATE TRIGGER fku_TilesData_id_Tiles_id
BEFORE UPDATE ON [TilesData]
FOR EACH ROW BEGIN
SELECT RAISE(ROLLBACK, 'update on table "TilesData" violates foreign key constraint "fku_TilesData_id_Tiles_id"')
WHERE (SELECT id FROM Tiles WHERE id = NEW.id) IS NULL;
END;
 
-- Cascading Delete
CREATE TRIGGER fkdc_TilesData_id_Tiles_id
BEFORE DELETE ON Tiles
FOR EACH ROW BEGIN
DELETE FROM TilesData WHERE TilesData.id = OLD.id;
END;</value>
</data>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="System_Data_SQLite_x64_NET2_dll" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\System.Data.SQLite.x64.NET2.dll.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="System_Data_SQLite_x64_NET4_dll" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\System.Data.SQLite.x64.NET4.dll.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="System_Data_SQLite_x86_NET2_dll" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\System.Data.SQLite.x86.NET2.dll.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="System_Data_SQLite_x86_NET4_dll" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\System.Data.SQLite.x86.NET4.dll.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
</root>
/MKLiveView/v1.0/Source/GMap.NET.Core/Properties/VersionInfo.cs
0,0 → 1,34
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
 
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyCulture("")]
[assembly: AssemblyCompany("Universe")]
[assembly: AssemblyCopyright("Copyright © Universe 2015")]
[assembly: AssemblyTrademark("email@radioman.lt")]
 
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
 
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.7")]
[assembly: AssemblyInformationalVersion("1.7")]
 
#if !PocketPC
[assembly: AssemblyFileVersion("1.7")]
#endif
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/System.Data.SQLite.x64.NET2.dll.gz
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/System.Data.SQLite.x64.NET4.dll.gz
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/System.Data.SQLite.x86.NET2.dll.gz
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/System.Data.SQLite.x86.NET4.dll.gz
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/blue-dot.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/drag_cross_67_16.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/green-dot.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/marker.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/mm_20_blue.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/mm_20_green.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/mm_20_red.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/mm_20_shadow.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/mm_20_yellow.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/red-dot.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/shadow50.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/Resources/yellow-dot.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/bin/Debug/GMap.NET.Core.dll
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/bin/Debug/GMap.NET.Core.pdb
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/bin/Release/GMap.NET.Core.dll
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Debug/DesignTimeResolveAssemblyReferences.cache
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Debug/GMap.NET.Core.csproj.FileListAbsolute.txt
0,0 → 1,14
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\bin\Debug\GMap.NET.Core.dll
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\bin\Debug\GMap.NET.Core.pdb
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\obj\Debug\GMap.NET.Properties.Resources.resources
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\obj\Debug\GMap.NET.Core.csproj.GenerateResource.Cache
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\obj\Debug\GMap.NET.Core.dll
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\obj\Debug\GMap.NET.Core.pdb
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\obj\Debug\GMap.NET.Core.csprojResolveAssemblyReference.cache
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\bin\Debug\GMap.NET.Core.dll
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\bin\Debug\GMap.NET.Core.pdb
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\obj\Debug\GMap.NET.Core.csprojResolveAssemblyReference.cache
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\obj\Debug\GMap.NET.Properties.Resources.resources
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\obj\Debug\GMap.NET.Core.csproj.GenerateResource.Cache
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\obj\Debug\GMap.NET.Core.dll
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\obj\Debug\GMap.NET.Core.pdb
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Debug/GMap.NET.Core.csproj.GenerateResource.Cache
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Debug/GMap.NET.Core.csprojResolveAssemblyReference.cache
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Debug/GMap.NET.Core.dll
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Debug/GMap.NET.Core.pdb
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Debug/GMap.NET.Properties.Resources.resources
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Debug/TempPE/Properties.Resources.Designer.cs.dll
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Release/DesignTimeResolveAssemblyReferencesInput.cache
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Release/GMap.NET.Core.csproj.FileListAbsolute.txt
0,0 → 1,8
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\bin\Release\GMap.NET.Core.dll
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\obj\Release\GMap.NET.Properties.Resources.resources
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\obj\Release\GMap.NET.Core.csproj.GenerateResource.Cache
E:\Documents\VS Projects\_Beispiele etc\greatmaps-master\GMap.NET.Core\obj\Release\GMap.NET.Core.dll
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\bin\Release\GMap.NET.Core.dll
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\obj\Release\GMap.NET.Properties.Resources.resources
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\obj\Release\GMap.NET.Core.csproj.GenerateResource.Cache
E:\Documents\VS Projects\MKLiveView\WPF\MKLiveView\GMap.NET.Core\obj\Release\GMap.NET.Core.dll
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Release/GMap.NET.Core.csproj.GenerateResource.Cache
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Release/GMap.NET.Core.dll
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Release/GMap.NET.Properties.Resources.resources
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/obj/Release/TempPE/Properties.Resources.Designer.cs.dll
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/MKLiveView/v1.0/Source/GMap.NET.Core/sn.snk
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property