forked from SharpMap/SharpMap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMap.cs
More file actions
1704 lines (1477 loc) · 63.8 KB
/
Map.cs
File metadata and controls
1704 lines (1477 loc) · 63.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap 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 Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using Common.Logging;
using NetTopologySuite.Geometries;
using SharpMap.Layers;
using SharpMap.Rendering;
using SharpMap.Rendering.Decoration;
using SharpMap.Styles;
using SharpMap.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using Point = NetTopologySuite.Geometries.Coordinate;
namespace SharpMap
{
/// <summary>
/// Map class, the main holder for a MapObject in SharpMap
/// </summary>
/// <example>
/// Creating a new map instance, adding layers and rendering the map:
/// </example>
[Serializable]
public class Map : IDisposable
{
/// <summary>
/// Method to invoke the static constructor of this class
/// </summary>
public static void Configure()
{
// Methods sole purpose is to get the static constructor executed
}
/// <summary>
/// Static constructor. Needed to get <see cref="NetTopologySuite.NtsGeometryServices.Instance"/> set.
/// </summary>
static Map()
{
try
{
_logger.Debug("Trying to get NetTopologySuite.NetTopologySuite.NtsGeometryServices.Instance");
var instance = NetTopologySuite.NtsGeometryServices.Instance;
if (instance == null)
{
_logger.Debug("Returned null");
throw new InvalidOperationException();
}
}
catch (InvalidOperationException)
{
_logger.Debug("Loading NetTopologySuite");
Assembly.Load("NetTopologySuite");
_logger.Debug("Loaded NetTopologySuite");
_logger.Debug("Trying to get NetTopologySuite.NetTopologySuite.NtsGeometryServices.Instance");
var instance = NetTopologySuite.NtsGeometryServices.Instance;
if (instance == null)
{
_logger.Debug("Returned null");
throw new InvalidOperationException();
}
}
// The following code did not seem to work in all cases.
/*
if (System.ComponentModel.LicenseManager.UsageMode != System.ComponentModel.LicenseUsageMode.Designtime)
{
_logger.Debug("In design mode");
Trace.WriteLine("In design mode");
// We have to do this initialization with reflection due to the fact that NTS can reference an older version of NetTopologySuite and redirection
// is not available at design time..
var ntsAssembly = Assembly.Load("NetTopologySuite");
_logger.Debug("Loaded NetTopologySuite");
Trace.WriteLine("Loaded NetTopologySuite");
try
{
_logger.Debug("Trying to access NetTopologySuite.NetTopologySuite.NtsGeometryServices.Instance");
Trace.WriteLine("Trying to access NetTopologySuite.NetTopologySuite.NtsGeometryServices.Instance");
if (NetTopologySuite.NetTopologySuite.NtsGeometryServices.Instance == null)
{
_logger.Debug("Returned null, setting it to default");
Trace.WriteLine("Returned null, setting it to default");
var ntsApiGeometryServices = ntsAssembly.GetType("NetTopologySuite.NtsGeometryServices");
NetTopologySuite.NetTopologySuite.NtsGeometryServices.Instance =
ntsApiGeometryServices.GetProperty("Instance").GetValue(null, null) as
NetTopologySuite.IGeometryServices;
}
}
catch (InvalidOperationException)
{
_logger.Debug("InvalidOperationException thrown, setting it to default");
Trace.WriteLine("InvalidOperationException thrown, setting it to default");
var ntsApiGeometryServices = ntsAssembly.GetType("NetTopologySuite.NtsGeometryServices");
NetTopologySuite.NetTopologySuite.NtsGeometryServices.Instance =
ntsApiGeometryServices.GetProperty("Instance").GetValue(null, null) as
NetTopologySuite.IGeometryServices;
}
_logger.Debug("Exiting design mode handling");
Trace.WriteLine("Exiting design mode handling");
}
*/
}
static readonly ILog _logger = LogManager.GetLogger(typeof(Map));
/// <summary>
/// Used for converting numbers to/from strings
/// </summary>
public static NumberFormatInfo NumberFormatEnUs = new CultureInfo("en-US", false).NumberFormat;
#region Fields
private readonly List<IMapDecoration> _decorations = new List<IMapDecoration>();
private Color _backgroundColor;
private int _srid = -1;
private double _zoom;
private Point _center;
private readonly LayerCollection _layers;
private readonly LayerCollection _backgroundLayers;
private readonly VariableLayerCollection _variableLayers;
#pragma warning disable 169
// both fields redundant, but unable to remove without violating serialization
private Matrix _mapTransform;
private Matrix _mapTransformInverted;
#pragma warning restore 169
private readonly object _lockMapTransform = new object();
private readonly object _lockMapTransformInverted = new object();
private float[] _mapTransformElements;
private float[] _mapTransformInvertedElements;
private readonly MapViewPortGuard _mapViewportGuard;
private readonly Dictionary<object, List<ILayer>> _layersPerGroup = new Dictionary<object, List<ILayer>>();
private ObservableCollection<ILayer> _replacingCollection;
private Guid _id = Guid.NewGuid();
#endregion
/// <summary>
/// Specifies whether to trigger a dispose on all layers (and their datasources) contained in this map when the map-object is disposed.
/// The default behaviour is true unless the map is a result of a Map.Clone() operation in which case the value is false
/// <para/>
/// If you reuse your datasources or layers between many map-objects you should set this property to false in order for them to keep existing after a map.dispose()
/// </summary>
public bool DisposeLayersOnDispose = true;
/// <summary>
/// Initializes a new map
/// </summary>
public Map() : this(new Size(640, 480))
{
}
/// <summary>
/// Initializes a new map
/// </summary>
/// <param name="size">Size of map in pixels</param>
public Map(Size size)
{
_mapViewportGuard = new MapViewPortGuard(size, 0d, Double.MaxValue);
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
Factory = Session.Instance.GeometryServices.CreateGeometryFactory(_srid);
}
_layers = new LayerCollection();
_layersPerGroup.Add(_layers, new List<ILayer>());
_backgroundLayers = new LayerCollection();
_layersPerGroup.Add(_backgroundLayers, new List<ILayer>());
_variableLayers = new VariableLayerCollection(_layers);
_layersPerGroup.Add(_variableLayers, new List<ILayer>());
BackColor = Color.Transparent;
var matrix = new Matrix();
_mapTransformElements = matrix.Elements;
_mapTransformInvertedElements = matrix.Elements;
_center = new Point(0, 0);
_zoom = 1;
WireEvents();
if (_logger.IsDebugEnabled)
_logger.DebugFormat("Map initialized with size {0},{1}", size.Width, size.Height);
}
/// <summary>
/// Wires the events
/// </summary>
private void WireEvents()
{
_backgroundLayers.CollectionChanged += OnLayersCollectionChanged;
_layers.CollectionChanged += OnLayersCollectionChanged;
}
/// <summary>
/// Event handler to intercept when a new ITileAsymclayer is added to the Layers List and associate the MapNewTile Handler Event
/// </summary>
private void OnLayersCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Reset)
{
var cloneList = _layersPerGroup[sender];
IterUnHookEvents(sender, cloneList);
}
if (e.Action == NotifyCollectionChangedAction.Replace || e.Action == NotifyCollectionChangedAction.Remove)
{
IterUnHookEvents(sender, e.OldItems.Cast<ILayer>());
}
if (e.Action == NotifyCollectionChangedAction.Replace || e.Action == NotifyCollectionChangedAction.Add)
{
IterWireEvents(sender, e.NewItems.Cast<ILayer>());
}
}
private void IterWireEvents(object owner, IEnumerable<ILayer> layers)
{
foreach (var layer in layers)
{
_layersPerGroup[owner].Add(layer);
var tileAsyncLayer = layer as ITileAsyncLayer;
if (tileAsyncLayer != null)
{
WireTileAsyncEvents(tileAsyncLayer);
}
var group = layer as LayerGroup;
if (group != null)
{
group.LayersChanging += OnLayerGroupCollectionReplaching;
group.LayersChanged += OnLayerGroupCollectionReplached;
var nestedList = group.Layers;
if (group.Layers != null)
{
group.Layers.CollectionChanged += OnLayersCollectionChanged;
_layersPerGroup.Add(nestedList, new List<ILayer>());
}
else
{
_layersPerGroup.Add(nestedList, new List<ILayer>());
}
IterWireEvents(nestedList, nestedList);
}
}
}
private void IterUnHookEvents(object owner, IEnumerable<ILayer> layers)
{
var toBeRemoved = new List<ILayer>();
foreach (var layer in layers)
{
toBeRemoved.Add(layer);
var tileAsyncLayer = layer as ITileAsyncLayer;
if (tileAsyncLayer != null)
{
UnhookTileAsyncEvents(tileAsyncLayer);
}
var group = layer as LayerGroup;
if (group != null)
{
group.LayersChanging -= OnLayerGroupCollectionReplaching;
group.LayersChanged -= OnLayerGroupCollectionReplached;
var nestedList = group.Layers;
if (nestedList != null)
{
nestedList.CollectionChanged -= OnLayersCollectionChanged;
IterUnHookEvents(nestedList, nestedList);
_layersPerGroup.Remove(nestedList);
}
}
}
var clonedList = _layersPerGroup[owner];
toBeRemoved.ForEach(layer => clonedList.Remove(layer));
}
private void OnLayerGroupCollectionReplached(object sender, EventArgs eventArgs)
{
var layerGroup = (LayerGroup)sender;
var newCollection = layerGroup.Layers;
IterUnHookEvents(_replacingCollection, _replacingCollection);
_layersPerGroup.Remove(_replacingCollection);
_replacingCollection.CollectionChanged -= OnLayersCollectionChanged;
if (newCollection != null)
{
IterWireEvents(newCollection, newCollection);
_layersPerGroup.Add(newCollection, new List<ILayer>(newCollection));
newCollection.CollectionChanged += OnLayersCollectionChanged;
}
}
private void OnLayerGroupCollectionReplaching(object sender, EventArgs eventArgs)
{
var layerGroup = (LayerGroup)sender;
_replacingCollection = layerGroup.Layers;
}
private void layer_DownloadProgressChanged(int tilesRemaining)
{
if (tilesRemaining <= 0)
{
OnRefreshNeeded(EventArgs.Empty);
}
}
private void WireTileAsyncEvents(ITileAsyncLayer tileAsyncLayer)
{
if (tileAsyncLayer.OnlyRedrawWhenComplete)
{
tileAsyncLayer.DownloadProgressChanged += layer_DownloadProgressChanged;
}
else
{
tileAsyncLayer.MapNewTileAvaliable += MapNewTileAvaliableHandler;
}
}
private void UnhookTileAsyncEvents(ITileAsyncLayer tileAsyncLayer)
{
tileAsyncLayer.DownloadProgressChanged -= layer_DownloadProgressChanged;
tileAsyncLayer.MapNewTileAvaliable -= MapNewTileAvaliableHandler;
}
#region IDisposable Members
/// <summary>
/// Disposes the map object
/// </summary>
public void Dispose()
{
if (DisposeLayersOnDispose)
{
if (Layers != null)
{
foreach (IDisposable disposable in Layers.OfType<IDisposable>())
{
disposable.Dispose();
}
}
if (BackgroundLayer != null)
{
foreach (IDisposable disposable in BackgroundLayer.OfType<IDisposable>())
{
disposable.Dispose();
}
}
if (VariableLayers != null)
{
foreach (IDisposable layer in VariableLayers.OfType<IDisposable>())
layer.Dispose();
}
}
if (Layers != null)
{
Layers.Clear();
}
if (BackgroundLayer != null)
{
BackgroundLayer.Clear();
}
if (VariableLayers != null)
{
VariableLayers.Clear();
}
}
#endregion
#region Events
#region Delegates
/// <summary>
/// EventHandler for event fired when the maps layer list has been changed
/// </summary>
public delegate void LayersChangedEventHandler();
/// <summary>
/// EventHandler for event fired when all layers have been rendered
/// </summary>
public delegate void MapRenderedEventHandler(Graphics g);
/// <summary>
/// EventHandler for event fired when all layers are about to be rendered
/// </summary>
public delegate void MapRenderingEventHandler(Graphics g);
/// <summary>
/// EventHandler for event fired when the zoomlevel or the center point has been changed
/// </summary>
public delegate void MapViewChangedHandler();
#endregion
/// <summary>
/// Event fired when the maps layer list have been changed
/// </summary>
[Obsolete("This event is never invoked since it has been made impossible to change the LayerCollection for a map instance.")]
#pragma warning disable 67
public event LayersChangedEventHandler LayersChanged;
#pragma warning restore 67
/// <summary>
/// Event fired when the zoomlevel or the center point has been changed
/// </summary>
public event MapViewChangedHandler MapViewOnChange;
/// <summary>
/// Event fired when all layers are about to be rendered
/// </summary>
public event MapRenderedEventHandler MapRendering;
/// <summary>
/// Event fired when all layers have been rendered
/// </summary>
public event MapRenderedEventHandler MapRendered;
/// <summary>
/// Event fired when one layer have been rendered
/// </summary>
public event EventHandler<LayerRenderingEventArgs> LayerRendering;
/// <summary>
/// Event fired when one layer have been rendered
/// </summary>
public event EventHandler<LayerRenderingEventArgs> LayerRenderedEx;
///<summary>
/// Event fired when a layer has been rendered
///</summary>
[Obsolete("Use LayerRenderedEx")]
public event EventHandler LayerRendered;
/// <summary>
/// Event fired when a new Tile is available in a TileAsyncLayer
/// </summary>
public event MapNewTileAvaliabledHandler MapNewTileAvaliable;
/// <summary>
/// Event that is called when a layer has changed and the map need to redraw
/// </summary>
public event EventHandler RefreshNeeded;
#endregion
#region Methods
/// <summary>
/// Renders the map to an image
/// </summary>
/// <returns>the map image</returns>
public Image GetMap()
{
Image img = new Bitmap(Size.Width, Size.Height);
Graphics g = Graphics.FromImage(img);
RenderMap(g);
g.Dispose();
return img;
}
/// <summary>
/// Renders the map to an image with the supplied resolution
/// </summary>
/// <param name="resolution">The resolution of the image</param>
/// <returns>The map image</returns>
public Image GetMap(int resolution)
{
Image img = new Bitmap(Size.Width, Size.Height);
((Bitmap)img).SetResolution(resolution, resolution);
Graphics g = Graphics.FromImage(img);
RenderMap(g);
g.Dispose();
return img;
}
/// <summary>
/// Renders the map to a Metafile (Vectorimage).
/// </summary>
/// <remarks>
/// A Metafile can be saved as WMF,EMF etc. or put onto the clipboard for paste in other applications such av Word-processors which will give
/// a high quality vector image in that application.
/// </remarks>
/// <returns>The current map rendered as to a Metafile</returns>
public Metafile GetMapAsMetafile()
{
return GetMapAsMetafile(String.Empty);
}
/// <summary>
/// Renders the map to a Metafile (Vectorimage).
/// </summary>
/// <param name="metafileName">The filename of the metafile. If this is null or empty the metafile is not saved.</param>
/// <remarks>
/// A Metafile can be saved as WMF,EMF etc. or put onto the clipboard for paste in other applications such av Word-processors which will give
/// a high quality vector image in that application.
/// </remarks>
/// <returns>The current map rendered as to a Metafile</returns>
public Metafile GetMapAsMetafile(string metafileName)
{
Metafile metafile;
var bm = new Bitmap(1, 1);
using (var g = Graphics.FromImage(bm))
{
var hdc = g.GetHdc();
using (var stream = new MemoryStream())
{
metafile = new Metafile(stream, hdc, new RectangleF(0, 0, Size.Width, Size.Height),
MetafileFrameUnit.Pixel, EmfType.EmfPlusDual);
using (var metafileGraphics = Graphics.FromImage(metafile))
{
metafileGraphics.PageUnit = GraphicsUnit.Pixel;
metafileGraphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Device,
new[] { new PointF(Size.Width, Size.Height) });
//Render map to metafile
RenderMap(metafileGraphics);
}
//Save metafile if desired
if (!String.IsNullOrEmpty(metafileName))
File.WriteAllBytes(metafileName, stream.ToArray());
}
g.ReleaseHdc(hdc);
}
return metafile;
}
//ToDo: fill in the blanks
/// <summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="bbox"></param>
/// <param name="bm"></param>
/// <param name="sourceWidth"></param>
/// <param name="sourceHeight"></param>
/// <param name="imageAttributes"></param>
public void MapNewTileAvaliableHandler(ITileAsyncLayer sender, Envelope bbox, Bitmap bm, int sourceWidth, int sourceHeight, ImageAttributes imageAttributes)
{
var e = MapNewTileAvaliable;
if (e != null)
e(sender, bbox, bm, sourceWidth, sourceHeight, imageAttributes);
}
/// <summary>
/// Renders the map using the provided <see cref="Graphics"/> object.
/// </summary>
/// <param name="g">the <see cref="Graphics"/> object to use</param>
/// <exception cref="ArgumentNullException">if <see cref="Graphics"/> object is null.</exception>
/// <exception cref="InvalidOperationException">if there are no layers to render.</exception>
public void RenderMap(Graphics g)
{
OnMapRendering(g);
if (g == null)
throw new ArgumentNullException("g", "Cannot render map with null graphics object!");
//Pauses the timer for VariableLayer
_variableLayers.Pause = true;
if ((Layers == null || Layers.Count == 0) && (BackgroundLayer == null || BackgroundLayer.Count == 0) && (_variableLayers == null || _variableLayers.Count == 0))
throw new InvalidOperationException("No layers to render");
g.Transform = MapTransform;
var mvp = (MapViewport)this;
g.Clear(BackColor);
g.PageUnit = GraphicsUnit.Pixel;
double zoom = mvp.Zoom;
double scale = double.NaN; //will be resolved if needed
ILayer[] layerList;
if (_backgroundLayers != null && _backgroundLayers.Count > 0)
{
layerList = new ILayer[_backgroundLayers.Count];
_backgroundLayers.CopyTo(layerList, 0);
foreach (ILayer layer in layerList)
{
if (layer.VisibilityUnits == VisibilityUnits.Scale && double.IsNaN(scale))
{
scale = mvp.GetMapScale((int)g.DpiX);
}
double visibleLevel = layer.VisibilityUnits == VisibilityUnits.ZoomLevel ? zoom : scale;
OnLayerRendering(layer, LayerCollectionType.Background);
if (layer.Enabled)
{
if (layer.MaxVisible >= visibleLevel && layer.MinVisible < visibleLevel)
{
LayerCollectionRenderer.RenderLayer(layer, g, mvp);
}
}
OnLayerRendered(layer, LayerCollectionType.Background);
}
}
if (_layers != null && _layers.Count > 0)
{
layerList = new ILayer[_layers.Count];
_layers.CopyTo(layerList, 0);
//int srid = (Layers.Count > 0 ? Layers[0].SRID : -1); //Get the SRID of the first layer
foreach (ILayer layer in layerList)
{
if (layer.VisibilityUnits == VisibilityUnits.Scale && double.IsNaN(scale))
{
scale = mvp.GetMapScale((int)g.DpiX);
}
double visibleLevel = layer.VisibilityUnits == VisibilityUnits.ZoomLevel ? zoom : scale;
OnLayerRendering(layer, LayerCollectionType.Static);
if (layer.Enabled && layer.MaxVisible >= visibleLevel && layer.MinVisible < visibleLevel)
LayerCollectionRenderer.RenderLayer(layer, g, mvp);
OnLayerRendered(layer, LayerCollectionType.Static);
}
}
if (_variableLayers != null && _variableLayers.Count > 0)
{
layerList = new ILayer[_variableLayers.Count];
_variableLayers.CopyTo(layerList, 0);
foreach (ILayer layer in layerList)
{
if (layer.VisibilityUnits == VisibilityUnits.Scale && double.IsNaN(scale))
{
scale = mvp.GetMapScale((int)g.DpiX);
}
double visibleLevel = layer.VisibilityUnits == VisibilityUnits.ZoomLevel ? zoom : scale;
if (layer.Enabled && layer.MaxVisible >= visibleLevel && layer.MinVisible < visibleLevel)
LayerCollectionRenderer.RenderLayer(layer, g, mvp);
OnLayerRendered(layer, LayerCollectionType.Variable);
}
}
#pragma warning disable 612,618
RenderDisclaimer(g);
#pragma warning restore 612,618
// Render all map decorations
foreach (var mapDecoration in _decorations)
{
mapDecoration.Render(g, mvp);
}
//Resets the timer for VariableLayer
_variableLayers.Pause = false;
OnMapRendered(g);
}
/// <summary>
/// Fires the RefreshNeeded event.
/// </summary>
/// <param name="e">EventArgs argument.</param>
protected virtual void OnRefreshNeeded(EventArgs e)
{
var handler = RefreshNeeded;
if (handler != null)
handler(this, e);
}
/// <summary>
/// Fired when map is rendering
/// </summary>
/// <param name="g"></param>
protected virtual void OnMapRendering(Graphics g)
{
var e = MapRendering;
if (e != null) e(g);
}
/// <summary>
/// Fired when Map is rendered
/// </summary>
/// <param name="g"></param>
protected virtual void OnMapRendered(Graphics g)
{
var e = MapRendered;
if (e != null) e(g); //Fire render event
}
/// <summary>
/// Method called when starting to render <paramref name="layer"/> of <paramref name="layerCollectionType"/>. This fires the
/// <see cref="E:SharpMap.Map.LayerRendering"/> event.
/// </summary>
/// <param name="layer">The layer to render</param>
/// <param name="layerCollectionType">The collection type</param>
protected virtual void OnLayerRendering(ILayer layer, LayerCollectionType layerCollectionType)
{
var e = LayerRendering;
if (e != null) e(this, new LayerRenderingEventArgs(layer, layerCollectionType));
}
#pragma warning disable 612,618
/// <summary>
/// Method called when <paramref name="layer"/> of <paramref name="layerCollectionType"/> has been rendered. This fires the
/// <see cref="E:SharpMap.Map.LayerRendered"/> and <see cref="E:SharpMap.Map.LayerRenderedEx"/> event.
/// </summary>
/// <param name="layer">The layer to render</param>
/// <param name="layerCollectionType">The collection type</param>
protected virtual void OnLayerRendered(ILayer layer, LayerCollectionType layerCollectionType)
{
var e = LayerRendered;
#pragma warning restore 612,618
if (e != null)
{
e(this, EventArgs.Empty);
}
var eex = LayerRenderedEx;
if (eex != null)
{
eex(this, new LayerRenderingEventArgs(layer, layerCollectionType));
}
}
/// <summary>
/// Renders the map using the provided <see cref="Graphics"/> object.
/// </summary>
/// <param name="g">the <see cref="Graphics"/> object to use</param>
/// <param name="layerCollectionType">the <see cref="LayerCollectionType"/> to use</param>
/// <exception cref="ArgumentNullException">if <see cref="Graphics"/> object is null.</exception>
/// <exception cref="InvalidOperationException">if there are no layers to render.</exception>
public void RenderMap(Graphics g, LayerCollectionType layerCollectionType)
{
RenderMap(g, layerCollectionType, true, false);
}
/// <summary>
/// Renders the map using the provided <see cref="Graphics"/> object.
/// </summary>
/// <param name="g">the <see cref="Graphics"/> object to use</param>
/// <param name="layerCollectionType">the <see cref="LayerCollectionType"/> to use</param>
/// <param name="drawMapDecorations">Set whether to draw map decorations on the map (if such are set)</param>
/// <param name="drawTransparent">Set whether to draw with transparent background or with BackColor as background</param>
/// <exception cref="ArgumentNullException">if <see cref="Graphics"/> object is null.</exception>
/// <exception cref="InvalidOperationException">if there are no layers to render.</exception>
public void RenderMap(Graphics g, LayerCollectionType layerCollectionType, bool drawMapDecorations, bool drawTransparent)
{
if (g == null)
throw new ArgumentNullException("g", "Cannot render map with null graphics object!");
_variableLayers.Pause = true;
LayerCollection lc = null;
switch (layerCollectionType)
{
case LayerCollectionType.Static:
lc = Layers;
break;
case LayerCollectionType.Variable:
lc = VariableLayers;
break;
case LayerCollectionType.Background:
lc = BackgroundLayer;
break;
}
if (lc == null || lc.Count == 0)
throw new InvalidOperationException("No layers to render");
var origTransform = g.Transform;
g.Transform = MapTransform;
var mvp = (MapViewport)this;
if (!drawTransparent)
g.Clear(BackColor);
g.PageUnit = GraphicsUnit.Pixel;
//LayerCollectionRenderer.AllowParallel = layerCollectionType == LayerCollectionType.Static;
using (var lcr = new LayerCollectionRenderer(lc))
{
lcr.Render(g, mvp, layerCollectionType == LayerCollectionType.Static);
}
/*
var layerList = new ILayer[lc.Count];
lc.CopyTo(layerList, 0);
foreach (ILayer layer in layerList)
{
if (layer.Enabled && layer.MaxVisible >= Zoom && layer.MinVisible < Zoom)
layer.Render(g, this);
}
*/
if (drawTransparent)
g.Transform = origTransform;
if (layerCollectionType == LayerCollectionType.Static)
{
#pragma warning disable 612,618
RenderDisclaimer(g);
#pragma warning restore 612,618
if (drawMapDecorations)
{
foreach (var mapDecoration in Decorations)
{
mapDecoration.Render(g, mvp);
}
}
}
_variableLayers.Pause = false;
}
/// <summary>
/// Returns a cloned copy of this map-object.
/// Layers are not cloned. The same instances are referenced from the cloned copy as from the original.
/// The property <see cref="DisposeLayersOnDispose"/> is however false on this object (which prevents layers beeing disposed and then not usable from the original map)
/// </summary>
/// <returns>Instance of <see cref="Map"/></returns>
public Map Clone()
{
Map clone;
lock (_lockMapTransform)
{
clone = new Map
{
BackColor = BackColor,
#pragma warning disable 612,618
Disclaimer = Disclaimer,
DisclaimerLocation = DisclaimerLocation,
#pragma warning restore 612,618
MaximumZoom = MaximumZoom,
MinimumZoom = MinimumZoom,
MaximumExtents = MaximumExtents,
EnforceMaximumExtents = EnforceMaximumExtents,
PixelAspectRatio = PixelAspectRatio,
Zoom = Zoom,
DisposeLayersOnDispose = false,
SRID = SRID,
_id = ID
};
#pragma warning disable 612,618
if (DisclaimerFont != null)
clone.DisclaimerFont = (Font)DisclaimerFont.Clone();
#pragma warning restore 612,618
if (MapTransform != null)
clone.MapTransform = MapTransform;
if (!Size.IsEmpty)
clone.Size = new Size(Size.Width, Size.Height);
if (Center != null)
clone.Center = Center.Copy();
}
if (BackgroundLayer != null)
clone.BackgroundLayer.AddCollection(BackgroundLayer.Clone());
for (int i = 0; i < Decorations.Count; i++)
clone.Decorations.Add(Decorations[i]);
if (Layers != null)
clone.Layers.AddCollection(Layers.Clone());
if (VariableLayers != null)
clone.VariableLayers.AddCollection(VariableLayers.Clone());
return clone;
}
[Obsolete]
private void RenderDisclaimer(Graphics g)
{
//Disclaimer
if (!String.IsNullOrEmpty(_disclaimer))
{
var size = VectorRenderer.SizeOfString(g, _disclaimer, _disclaimerFont);
size.Width = (Single)Math.Ceiling(size.Width);
size.Height = (Single)Math.Ceiling(size.Height);
StringFormat sf;
switch (DisclaimerLocation)
{
case 0: //Right-Bottom
sf = new StringFormat();
sf.Alignment = StringAlignment.Far;
g.DrawString(Disclaimer, DisclaimerFont, Brushes.Black,
g.VisibleClipBounds.Width,
g.VisibleClipBounds.Height - size.Height - 2, sf);
break;
case 1: //Right-Top
sf = new StringFormat();
sf.Alignment = StringAlignment.Far;
g.DrawString(Disclaimer, DisclaimerFont, Brushes.Black,
g.VisibleClipBounds.Width, 0f, sf);
break;
case 2: //Left-Top
g.DrawString(Disclaimer, DisclaimerFont, Brushes.Black, 0f, 0f);
break;
case 3://Left-Bottom
g.DrawString(Disclaimer, DisclaimerFont, Brushes.Black, 0f,
g.VisibleClipBounds.Height - size.Height - 2);
break;
}
}
}
/// <summary>
/// Returns an enumerable for all layers containing the search parameter in the LayerName property
/// </summary>
/// <param name="layername">Search parameter</param>
/// <returns>IEnumerable</returns>
public IEnumerable<ILayer> FindLayer(string layername)
{
return Layers.Where(l => l.LayerName.Contains(layername));
}
/// <summary>
/// Returns a layer by its name
/// </summary>
/// <param name="name">Name of layer</param>
/// <returns>Layer</returns>
public ILayer GetLayerByName(string name)
{
ILayer lay = null;
if (Layers != null)
{
lay = Layers.GetLayerByName(name);
}
if (lay == null && BackgroundLayer != null)
{
lay = BackgroundLayer.GetLayerByName(name);
}
if (lay == null && VariableLayers != null)
{
lay = VariableLayers.GetLayerByName(name);
}
return lay;
}
/// <summary>
/// Zooms to the extents of all layers
/// </summary>
public void ZoomToExtents()
{
ZoomToBox(GetExtents(), true);
}
/// <summary>
/// Zooms the map to fit a bounding box
/// </summary>
/// <remarks>