├── .gitignore ├── GoogleMaps.Net.Clustering.sln ├── GoogleMaps.Net.Clustering ├── Algorithm │ ├── ClusterAlgorithmBase.cs │ ├── GridCluster.cs │ └── IGridCluster.cs ├── Data │ ├── Algo │ │ ├── Boundary.cs │ │ ├── Bucket.cs │ │ └── ClusterInfo.cs │ ├── CacheKeys.cs │ ├── Configuration │ │ ├── GmcSettings.cs │ │ └── IGmcSettings.cs │ ├── DatasetToSerialize.cs │ ├── FilterData.cs │ ├── Geometry │ │ ├── IMapPoint.cs │ │ ├── LatLongInfo.cs │ │ ├── Line.cs │ │ ├── MapPoint.cs │ │ ├── MapPointBase.cs │ │ ├── Numbers.cs │ │ └── Rectangle.cs │ ├── MarkersInput.cs │ ├── Params │ │ └── GetMarkersParams.cs │ ├── Repository │ │ ├── IPointsDatabase.cs │ │ └── PointsDatabase.cs │ └── Responses │ │ ├── ClusterMarkersResponse.cs │ │ ├── MarkerInfoResponse.cs │ │ └── ResponseBase.cs ├── Documents │ ├── Design │ │ ├── GoogleMapsClustering_SD_ver1.png │ │ ├── GoogleMapsClustering_SD_ver1.vsd │ │ ├── googlemaps-clustering-viewport_ver1.png │ │ └── googlemaps-clustering-viewport_ver1.vsd │ ├── FAQ.txt │ └── License.txt ├── Extensions │ ├── DataExtension.cs │ └── IEnumerableExtension.cs ├── GoogleMaps.Net.Clustering.csproj ├── Infrastructure │ ├── IMemCache.cs │ ├── IPointCollection.cs │ ├── MemCache.cs │ └── PointCollection.cs ├── Properties │ └── AssemblyInfo.cs ├── Services │ ├── ClusterService.cs │ └── IClusterService.cs ├── Utility │ ├── ExceptionUtil.cs │ ├── FilterUtil.cs │ └── MathTool.cs └── packages.config ├── LICENSE ├── README.md ├── cluster-map.png └── nuget-icon.png /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | 24 | # Visual Studio 2015 cache/options directory 25 | .vs/ 26 | # Uncomment if you have tasks that create the project's static files in wwwroot 27 | #wwwroot/ 28 | 29 | # MSTest test Results 30 | [Tt]est[Rr]esult*/ 31 | [Bb]uild[Ll]og.* 32 | 33 | # NUNIT 34 | *.VisualState.xml 35 | TestResult.xml 36 | 37 | # Build Results of an ATL Project 38 | [Dd]ebugPS/ 39 | [Rr]eleasePS/ 40 | dlldata.c 41 | 42 | # DNX 43 | project.lock.json 44 | artifacts/ 45 | 46 | *_i.c 47 | *_p.c 48 | *_i.h 49 | *.ilk 50 | *.meta 51 | *.obj 52 | *.pch 53 | *.pdb 54 | *.pgc 55 | *.pgd 56 | *.rsp 57 | *.sbr 58 | *.tlb 59 | *.tli 60 | *.tlh 61 | *.tmp 62 | *.tmp_proj 63 | *.log 64 | *.vspscc 65 | *.vssscc 66 | .builds 67 | *.pidb 68 | *.svclog 69 | *.scc 70 | 71 | # Chutzpah Test files 72 | _Chutzpah* 73 | 74 | # Visual C++ cache files 75 | ipch/ 76 | *.aps 77 | *.ncb 78 | *.opendb 79 | *.opensdf 80 | *.sdf 81 | *.cachefile 82 | 83 | # Visual Studio profiler 84 | *.psess 85 | *.vsp 86 | *.vspx 87 | *.sap 88 | 89 | # TFS 2012 Local Workspace 90 | $tf/ 91 | 92 | # Guidance Automation Toolkit 93 | *.gpState 94 | 95 | # ReSharper is a .NET coding add-in 96 | _ReSharper*/ 97 | *.[Rr]e[Ss]harper 98 | *.DotSettings.user 99 | 100 | # JustCode is a .NET coding add-in 101 | .JustCode 102 | 103 | # TeamCity is a build add-in 104 | _TeamCity* 105 | 106 | # DotCover is a Code Coverage Tool 107 | *.dotCover 108 | 109 | # NCrunch 110 | _NCrunch_* 111 | .*crunch*.local.xml 112 | nCrunchTemp_* 113 | 114 | # MightyMoose 115 | *.mm.* 116 | AutoTest.Net/ 117 | 118 | # Web workbench (sass) 119 | .sass-cache/ 120 | 121 | # Installshield output folder 122 | [Ee]xpress/ 123 | 124 | # DocProject is a documentation generator add-in 125 | DocProject/buildhelp/ 126 | DocProject/Help/*.HxT 127 | DocProject/Help/*.HxC 128 | DocProject/Help/*.hhc 129 | DocProject/Help/*.hhk 130 | DocProject/Help/*.hhp 131 | DocProject/Help/Html2 132 | DocProject/Help/html 133 | 134 | # Click-Once directory 135 | publish/ 136 | 137 | # Publish Web Output 138 | *.[Pp]ublish.xml 139 | *.azurePubxml 140 | # TODO: Comment the next line if you want to checkin your web deploy settings 141 | # but database connection strings (with potential passwords) will be unencrypted 142 | *.pubxml 143 | *.publishproj 144 | 145 | # NuGet Packages 146 | *.nupkg 147 | # The packages folder can be ignored because of Package Restore 148 | **/packages/* 149 | # except build/, which is used as an MSBuild target. 150 | !**/packages/build/ 151 | # Uncomment if necessary however generally it will be regenerated when needed 152 | #!**/packages/repositories.config 153 | 154 | # Microsoft Azure Build Output 155 | csx/ 156 | *.build.csdef 157 | 158 | # Microsoft Azure Emulator 159 | ecf/ 160 | rcf/ 161 | 162 | # Microsoft Azure ApplicationInsights config file 163 | ApplicationInsights.config 164 | 165 | # Windows Store app package directory 166 | AppPackages/ 167 | BundleArtifacts/ 168 | 169 | # Visual Studio cache files 170 | # files ending in .cache can be ignored 171 | *.[Cc]ache 172 | # but keep track of directories ending in .cache 173 | !*.[Cc]ache/ 174 | 175 | # Others 176 | ClientBin/ 177 | ~$* 178 | *~ 179 | *.dbmdl 180 | *.dbproj.schemaview 181 | *.pfx 182 | *.publishsettings 183 | node_modules/ 184 | orleans.codegen.cs 185 | 186 | # RIA/Silverlight projects 187 | Generated_Code/ 188 | 189 | # Backup & report files from converting an old project file 190 | # to a newer Visual Studio version. Backup files are not needed, 191 | # because we have git ;-) 192 | _UpgradeReport_Files/ 193 | Backup*/ 194 | UpgradeLog*.XML 195 | UpgradeLog*.htm 196 | 197 | # SQL Server files 198 | *.mdf 199 | *.ldf 200 | 201 | # Business Intelligence projects 202 | *.rdl.data 203 | *.bim.layout 204 | *.bim_*.settings 205 | 206 | # Microsoft Fakes 207 | FakesAssemblies/ 208 | 209 | # GhostDoc plugin setting file 210 | *.GhostDoc.xml 211 | 212 | # Node.js Tools for Visual Studio 213 | .ntvs_analysis.dat 214 | 215 | # Visual Studio 6 build log 216 | *.plg 217 | 218 | # Visual Studio 6 workspace options file 219 | *.opt 220 | 221 | # Visual Studio LightSwitch build output 222 | **/*.HTMLClient/GeneratedArtifacts 223 | **/*.DesktopClient/GeneratedArtifacts 224 | **/*.DesktopClient/ModelManifest.xml 225 | **/*.Server/GeneratedArtifacts 226 | **/*.Server/ModelManifest.xml 227 | _Pvt_Extensions 228 | 229 | # Paket dependency manager 230 | .paket/paket.exe 231 | 232 | # FAKE - F# Make 233 | .fake/ 234 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.24720.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GoogleMaps.Net.Clustering", "GoogleMaps.Net.Clustering\GoogleMaps.Net.Clustering.csproj", "{CEE02707-BBC1-4C90-BB96-66CA79BA48D6}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {CEE02707-BBC1-4C90-BB96-66CA79BA48D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {CEE02707-BBC1-4C90-BB96-66CA79BA48D6}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {CEE02707-BBC1-4C90-BB96-66CA79BA48D6}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {CEE02707-BBC1-4C90-BB96-66CA79BA48D6}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Algorithm/ClusterAlgorithmBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using GoogleMaps.Net.Clustering.Data.Algo; 5 | using GoogleMaps.Net.Clustering.Data.Configuration; 6 | using GoogleMaps.Net.Clustering.Data.Geometry; 7 | using GoogleMaps.Net.Clustering.Extensions; 8 | using GoogleMaps.Net.Clustering.Utility; 9 | 10 | namespace GoogleMaps.Net.Clustering.Algorithm 11 | { 12 | /// 13 | /// /// Author: Kunuk Nykjaer 14 | /// 15 | internal abstract class ClusterAlgorithmBase 16 | { 17 | protected readonly IList points; 18 | 19 | // id, bucket 20 | public readonly Dictionary BucketsLookup = new Dictionary(); 21 | 22 | protected ClusterAlgorithmBase(IList points) 23 | { 24 | this.points = points; 25 | } 26 | 27 | public List GetClusterResult(Boundary grid) 28 | { 29 | // Collect used buckets and return the result 30 | var clusterPoints = new List(); 31 | 32 | // O(m*n) 33 | foreach (var item in BucketsLookup) 34 | { 35 | var bucket = item.Value; 36 | if (!bucket.IsUsed) continue; 37 | 38 | if (bucket.Points.Count < GmcSettings.Get.MinClusterSize) 39 | { 40 | clusterPoints.AddRange(bucket.Points); 41 | } 42 | else 43 | { 44 | bucket.Centroid.Count = bucket.Points.Count; 45 | clusterPoints.Add(bucket.Centroid); 46 | } 47 | } 48 | 49 | // var filtered = FilterDataset(clusterPoints, grid); // post filter data for client viewport 50 | // return filtered; //not working properly when zoomed far out. 51 | return clusterPoints; // return not post filtered 52 | } 53 | 54 | 55 | // Circular mean, very relevant for points around New Zealand, where lon -180 to 180 overlap 56 | // Adapted Centroid Calculation of N Points for Google Maps usage 57 | // If you are working with points in a specific country only such as India or USA then a simpler centroid calc can be used 58 | // http://en.wikipedia.org/wiki/Centroid 59 | public static MapPoint GetCentroidFromClusterLatLon(List list) //O(n) 60 | { 61 | int count; 62 | if (list == null || (count = list.Count) == 0) return null; 63 | 64 | if (count == 1) 65 | { 66 | return list.First(); 67 | } 68 | 69 | // http://en.wikipedia.org/wiki/Circular_mean 70 | // http://stackoverflow.com/questions/491738/how-do-you-calculate-the-average-of-a-set-of-angles 71 | /* 72 | 1/N* sum_i_from_1_to_N sin(a[i]) 73 | a = atan2 --------------------------- 74 | 1/N* sum_i_from_1_to_N cos(a[i]) 75 | */ 76 | 77 | double longSin = 0; 78 | double longCos = 0; 79 | double latSin = 0; 80 | double latCos = 0; 81 | foreach (var p in list) 82 | { 83 | longSin += Math.Sin(p.X.LatLongToRadian()); 84 | longCos += Math.Cos(p.X.LatLongToRadian()); 85 | latSin += Math.Sin(p.Y.LatLongToRadian()); 86 | latCos += Math.Cos(p.Y.LatLongToRadian()); 87 | } 88 | 89 | longSin /= count; 90 | longCos /= count; 91 | 92 | double radx = 0; 93 | double rady = 0; 94 | 95 | // if both are zero-ish 96 | if (Math.Abs(longSin - 0) > Numbers.Epsilon && Math.Abs(longCos - 0) > Numbers.Epsilon) 97 | { 98 | radx = Math.Atan2(longSin, longCos); 99 | rady = Math.Atan2(latSin, latCos); 100 | } 101 | var x = radx.RadianToLatLong(); 102 | var y = rady.RadianToLatLong(); 103 | 104 | var centroid = new MapPoint { X = x, Y = y, Count = count }; 105 | return centroid; 106 | } 107 | 108 | 109 | // O(k*n) 110 | public static void SetCentroidForAllBuckets(IEnumerable buckets) 111 | { 112 | foreach (var item in buckets) 113 | { 114 | item.Centroid = GetCentroidFromClusterLatLon(item.Points); 115 | } 116 | } 117 | 118 | public MapPoint GetClosestPoint(MapPoint from, List list) // O(n) 119 | { 120 | var min = double.MaxValue; 121 | MapPoint closests = null; 122 | foreach (var p in list) 123 | { 124 | var dist = MathTool.Distance(from, p); 125 | if (dist >= min) continue; 126 | 127 | // update 128 | min = dist; 129 | closests = p; 130 | } 131 | return closests; 132 | } 133 | 134 | // Assign all points to nearest cluster 135 | public void UpdatePointsByCentroid() // O(n*k) 136 | { 137 | // Clear points in the buckets, they will be re-inserted 138 | foreach (var bucket in BucketsLookup.Values) 139 | { 140 | bucket.Points.Clear(); 141 | } 142 | 143 | foreach (var p in this.points) 144 | { 145 | var minDist = Double.MaxValue; 146 | var index = string.Empty; 147 | foreach (var i in BucketsLookup.Keys) 148 | { 149 | var bucket = BucketsLookup[i]; 150 | if (bucket.IsUsed == false) 151 | { 152 | continue; 153 | } 154 | 155 | var centroid = bucket.Centroid; 156 | var dist = MathTool.Distance(p, centroid); 157 | if (dist < minDist) 158 | { 159 | // update 160 | minDist = dist; 161 | index = i; 162 | } 163 | } 164 | // re-insert 165 | var closestBucket = BucketsLookup[index]; 166 | closestBucket.Points.Add(p); 167 | } 168 | } 169 | 170 | // Update centroid location to nearest point, 171 | // e.g. if you want to show cluster point on a real existing point area 172 | // O(n) 173 | public void UpdateCentroidToNearestContainingPoint(Bucket bucket) 174 | { 175 | if (bucket == null || bucket.Centroid == null || 176 | bucket.Points == null || bucket.Points.Count == 0) 177 | { 178 | return; 179 | } 180 | 181 | var closest = GetClosestPoint(bucket.Centroid, bucket.Points); 182 | bucket.Centroid.X = closest.X; // no normalize, points are already normalized by default 183 | bucket.Centroid.Y = closest.Y; 184 | } 185 | // O(k*n) 186 | public void UpdateAllCentroidsToNearestContainingPoint() 187 | { 188 | foreach (var bucket in BucketsLookup.Values) 189 | { 190 | UpdateCentroidToNearestContainingPoint(bucket); 191 | } 192 | } 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Algorithm/GridCluster.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using GoogleMaps.Net.Clustering.Contract; 4 | using GoogleMaps.Net.Clustering.Data; 5 | using GoogleMaps.Net.Clustering.Data.Algo; 6 | using GoogleMaps.Net.Clustering.Data.Configuration; 7 | using GoogleMaps.Net.Clustering.Data.Geometry; 8 | using GoogleMaps.Net.Clustering.Data.Responses; 9 | using GoogleMaps.Net.Clustering.Extensions; 10 | using GoogleMaps.Net.Clustering.Utility; 11 | 12 | namespace GoogleMaps.Net.Clustering.Algorithm 13 | { 14 | /// 15 | /// Author: Kunuk Nykjaer 16 | /// 17 | internal class GridCluster : ClusterAlgorithmBase, IGridCluster 18 | { 19 | private readonly MarkersInput _input; 20 | 21 | // Absolut position 22 | protected readonly Boundary Grid = new Boundary(); 23 | 24 | // Bucket placement calc, grid cluster algo 25 | protected readonly double DeltaX; 26 | protected readonly double DeltaY; 27 | 28 | public static Boundary GetBoundaryExtended(MarkersInput input) 29 | { 30 | var deltas = GetDelta(GmcSettings.Get.GridX, GmcSettings.Get.GridY, input.Zoomlevel); 31 | var deltaX = deltas[0]; 32 | var deltaY = deltas[1]; 33 | 34 | // Grid with extended outer grid-area non-visible 35 | var a = MathTool.FloorLatLon(input.Viewport.MinX, deltaX) - deltaX * GmcSettings.Get.OuterGridExtend; 36 | var b = MathTool.FloorLatLon(input.Viewport.MinY, deltaY) - deltaY * GmcSettings.Get.OuterGridExtend; 37 | var a2 = MathTool.FloorLatLon(input.Viewport.MaxX, deltaX) + deltaX * (1 + GmcSettings.Get.OuterGridExtend); 38 | var b2 = MathTool.FloorLatLon(input.Viewport.MaxY, deltaY) + deltaY * (1 + GmcSettings.Get.OuterGridExtend); 39 | 40 | // Latitude is special with Google Maps, they don't wrap around, then do constrain 41 | b = MathTool.ConstrainLatitude(b); 42 | b2 = MathTool.ConstrainLatitude(b2); 43 | 44 | var grid = new Boundary { MinX = a, MinY = b, MaxX = a2, MaxY = b2 }; 45 | grid.Normalize(); 46 | return grid; 47 | } 48 | 49 | 50 | /// 51 | /// O(1) 52 | /// 53 | /// 54 | public static double[] GetDelta(int gridX, int gridY, int zoomlevel) 55 | { 56 | // Heuristic specific values and grid size dependent. 57 | // used in combination with zoom level. 58 | 59 | // xZoomLevel1 and yZoomLevel1 is used to define the size of one grid-cell 60 | 61 | // Absolute base value of longitude distance, heuristic value 62 | const int xZoomLevel1 = 480; 63 | // Absolute base value of latitude distance, heuristic value 64 | const int yZoomLevel1 = 240; 65 | 66 | // Relative values, used for adjusting grid size 67 | var x = MathTool.Half(xZoomLevel1, zoomlevel - 1) / gridX; 68 | var y = MathTool.Half(yZoomLevel1, zoomlevel - 1) / gridY; 69 | return new double[] { x, y }; 70 | } 71 | 72 | 73 | 74 | /// 75 | /// todo use threads and threadData 76 | /// 77 | /// 78 | /// 79 | public GridCluster(IList points, MarkersInput input) 80 | : base(points) 81 | { 82 | this._input = input; 83 | double[] deltas = GetDelta(GmcSettings.Get.GridX, GmcSettings.Get.GridY, input.Zoomlevel); 84 | DeltaX = deltas[0]; 85 | DeltaY = deltas[1]; 86 | Grid = GetBoundaryExtended(input); 87 | } 88 | 89 | /// 90 | /// For debugging purpose 91 | /// Display the red grid lines on the map to show how the points are clustered 92 | /// 93 | /// 94 | public IList GetPolyLines() 95 | { 96 | if (!GmcSettings.Get.DoShowGridLinesInGoogleMap) return null; // server disabled it 97 | if (!_input.IsDebugLinesEnabled) return null; // client disabled it 98 | 99 | // Make the red lines data to be drawn in Google map 100 | 101 | var temp = new List(); 102 | 103 | const int borderLinesAdding = 1; 104 | var linesStepsX = (int)(Math.Round(Grid.AbsX / DeltaX) + borderLinesAdding); 105 | var linesStepsY = (int)(Math.Round(Grid.AbsY / DeltaY) + borderLinesAdding); 106 | 107 | var b = new Boundary(Grid); 108 | const double restrictLat = 5.5; // heuristic value, Google maps related 109 | b.MinY = MathTool.ConstrainLatitude(b.MinY, restrictLat); // Make sure it is visible on screen, restrict by some value 110 | b.MaxY = MathTool.ConstrainLatitude(b.MaxY, restrictLat); 111 | 112 | // Vertical lines 113 | for (var i = 0; i < linesStepsX; i++) 114 | { 115 | var xx = b.MinX + i * DeltaX; 116 | 117 | // Draw region 118 | if (_input.Zoomlevel > 3) // heuristic value, Google maps related 119 | { 120 | temp.Add(new Rectangle { MinX = xx, MinY = b.MinY, MaxX = xx, MaxY = b.MaxY }); 121 | } 122 | // World wrap issue when same latlon area visible multiple times 123 | // Make sure line is drawn from left to right on screen 124 | else 125 | { 126 | temp.Add(new Rectangle { MinX = xx, MinY = LatLongInfo.MinLatValue + restrictLat, MaxX = xx, MaxY = 0 }); 127 | temp.Add(new Rectangle { MinX = xx, MinY = 0, MaxX = xx, MaxY = LatLongInfo.MaxLatValue - restrictLat }); 128 | } 129 | } 130 | 131 | // Horizontal lines 132 | for (var i = 0; i < linesStepsY; i++) 133 | { 134 | var yy = b.MinY + i * DeltaY; 135 | 136 | // Draw region 137 | if (_input.Zoomlevel > 3) // heuristic value 138 | { 139 | // Don't draw lines outsize the world 140 | if (MathTool.IsLowerThanLatMin(yy) || MathTool.IsGreaterThanLatMax(yy)) continue; 141 | 142 | temp.Add(new Rectangle { MinX = b.MinX, MinY = yy, MaxX = b.MaxX, MaxY = yy }); 143 | } 144 | // World wrap issue when same latlon area visible multiple times 145 | // Make sure line is drawn from left to right on screen 146 | else 147 | { 148 | temp.Add(new Rectangle { MinX = LatLongInfo.MinLonValue, MinY = yy, MaxX = 0, MaxY = yy }); 149 | temp.Add(new Rectangle { MinX = 0, MinY = yy, MaxX = LatLongInfo.MaxLonValue, MaxY = yy }); 150 | } 151 | } 152 | 153 | var lines = new List(); 154 | 155 | // Normalize the lines and add as string 156 | foreach (var line in temp) 157 | { 158 | var x = (line.MinX).NormalizeLongitude().DoubleToString(); 159 | var x2 = (line.MaxX).NormalizeLongitude().DoubleToString(); 160 | var y = (line.MinY).NormalizeLatitude().DoubleToString(); 161 | var y2 = (line.MaxY).NormalizeLatitude().DoubleToString(); 162 | lines.Add(new Line { X = x, Y = y, X2 = x2, Y2 = y2 }); 163 | } 164 | return lines; 165 | } 166 | 167 | // Dictionary lookup key used by grid cluster algo 168 | public static string GetId(int idx, int idy) //O(1) 169 | { 170 | return string.Concat(idx, ";", idy); 171 | } 172 | 173 | // Average running time (m*n) 174 | // worst case might actually be 175 | // ~ O(n^2) if most of centroids are merged, due to centroid re-calculation, very very unlikely 176 | void MergeClustersGrid() 177 | { 178 | foreach (var key in BucketsLookup.Keys) 179 | { 180 | var bucket = BucketsLookup[key]; 181 | if (!bucket.IsUsed) continue; // skip not used 182 | 183 | var x = bucket.Idx; 184 | var y = bucket.Idy; 185 | 186 | // get keys for neighbors 187 | var N = GetId(x, y + 1); 188 | var NE = GetId(x + 1, y + 1); 189 | var E = GetId(x + 1, y); 190 | var SE = GetId(x + 1, y - 1); 191 | var S = GetId(x, y - 1); 192 | var SW = GetId(x - 1, y - 1); 193 | var W = GetId(x - 1, y); 194 | var NW = GetId(x - 1, y - 1); 195 | var neighbors = new[] { N, NE, E, SE, S, SW, W, NW }; 196 | 197 | MergeClustersGridHelper(key, neighbors); 198 | } 199 | } 200 | 201 | void MergeClustersGridHelper(string currentKey, IEnumerable neighborKeys) 202 | { 203 | double minDistX = DeltaX / GmcSettings.Get.MergeWithin; 204 | double minDistY = DeltaY / GmcSettings.Get.MergeWithin; 205 | // If clusters in grid are too close to each other, merge them 206 | double withinDist = Math.Max(minDistX, minDistY); 207 | 208 | foreach (var neighborKey in neighborKeys) 209 | { 210 | if (!BucketsLookup.ContainsKey(neighborKey)) continue; 211 | 212 | var neighbor = BucketsLookup[neighborKey]; 213 | if (neighbor.IsUsed == false) continue; 214 | 215 | var current = BucketsLookup[currentKey]; 216 | var dist = MathTool.Distance(current.Centroid, neighbor.Centroid); 217 | if (dist > withinDist) continue; 218 | 219 | current.Points.AddRange(neighbor.Points); //O(n) 220 | 221 | // recalc centroid 222 | var centroidPoint = GetCentroidFromClusterLatLon(current.Points); 223 | current.Centroid = centroidPoint; 224 | neighbor.IsUsed = false; // merged, then not used anymore 225 | neighbor.Points.Clear(); // clear mem 226 | } 227 | } 228 | 229 | // To work properly it requires the p is already normalized 230 | protected static int[] GetPointMappedIds(MapPoint point, Boundary grid, double deltaX, double deltaY) 231 | { 232 | #region Naive 233 | // Naive version, lon points near 180 and lat points near 90 are not clustered together 234 | //idx = (int)(relativeX / deltax); 235 | //idy = (int)(relativeY / deltay); 236 | //var relativeX = p.X - grid.Minx; 237 | #endregion Naive 238 | 239 | /* 240 | You have to draw a line with longitude values 180, -180 on papir to understand this 241 | 242 | e.g. _deltaX = 20 243 | longitude 150 170 180 -170 -150 244 | | | | | 245 | 246 | 247 | idx = 7 8 9 -9 -8 248 | -10 249 | 250 | here we want idx 8, 9, -10 and -9 be equal to each other, we set them to idx=8 251 | then the longitudes from 170 to -170 will be clustered together 252 | */ 253 | 254 | var relativeY = point.Y - grid.MinY; 255 | 256 | var overlapMapMinX = (int)(LatLongInfo.MinLonValue / deltaX) - 1; 257 | var overlapMapMaxX = (int)(LatLongInfo.MaxLonValue / deltaX); 258 | 259 | // The deltaX = 20 example scenario, then set the value 9 to 8 and -10 to -9 260 | 261 | // Similar to if (LatLonInfo.MaxLonValue % deltax == 0) without floating presicion issue 262 | if (Math.Abs(LatLongInfo.MaxLonValue % deltaX - 0) < Numbers.Epsilon) 263 | { 264 | overlapMapMaxX--; 265 | overlapMapMinX++; 266 | } 267 | 268 | var idxx = (int)(point.X / deltaX); 269 | if (point.X < 0) idxx--; 270 | 271 | if (Math.Abs(LatLongInfo.MaxLonValue % point.X - 0) < Numbers.Epsilon) 272 | { 273 | if (point.X < 0) idxx++; 274 | else idxx--; 275 | } 276 | if (idxx == overlapMapMinX) idxx = overlapMapMaxX; 277 | 278 | var idx = idxx; 279 | 280 | // Latitude never wraps around with Google Maps, ignore 90, -90 wrap-around for latitude 281 | var idy = (int)(relativeY / deltaY); 282 | 283 | return new[] { idx, idy }; 284 | } 285 | 286 | 287 | public IList RunCluster() 288 | { 289 | // Skip points outside the grid, not visible to user then skip those 290 | //IList filtered = ClusterInfo.DoFilterData(this._jsonReceive.Zoomlevel) // TODO: by kit 291 | // ? FilterUtil.FilterDataByViewport(this.points, Grid) 292 | // : this.points; 293 | 294 | IList filtered = this.points; 295 | 296 | // Put points in buckets 297 | foreach (var p in filtered) 298 | { 299 | var idxy = GetPointMappedIds(p, Grid, DeltaX, DeltaY); 300 | var idx = idxy[0]; 301 | var idy = idxy[1]; 302 | 303 | // Bucket id 304 | var id = GetId(idx, idy); 305 | 306 | // Bucket exists, add point 307 | if (BucketsLookup.ContainsKey(id)) 308 | { 309 | BucketsLookup[id].Points.Add(p); 310 | } 311 | // New bucket, create and add point 312 | else 313 | { 314 | var bucket = new Bucket(idx, idy, id); 315 | bucket.Points.Add(p); 316 | BucketsLookup.Add(id, bucket); 317 | } 318 | } 319 | 320 | // Calculate centroid for all buckets 321 | SetCentroidForAllBuckets(BucketsLookup.Values); 322 | 323 | // Merge if gridpoint is to close 324 | if (GmcSettings.Get.DoMergeGridIfCentroidsAreCloseToEachOther) MergeClustersGrid(); 325 | 326 | if (GmcSettings.Get.DoUpdateAllCentroidsToNearestContainingPoint) UpdateAllCentroidsToNearestContainingPoint(); 327 | 328 | // Check again 329 | // Merge if gridpoint is to close 330 | if (GmcSettings.Get.DoMergeGridIfCentroidsAreCloseToEachOther 331 | && GmcSettings.Get.DoUpdateAllCentroidsToNearestContainingPoint) 332 | { 333 | MergeClustersGrid(); 334 | // And again set centroid to closest point in bucket 335 | UpdateAllCentroidsToNearestContainingPoint(); 336 | } 337 | 338 | return GetClusterResult(Grid); 339 | } 340 | } 341 | } -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Algorithm/IGridCluster.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using GoogleMaps.Net.Clustering.Data.Geometry; 3 | 4 | namespace GoogleMaps.Net.Clustering.Algorithm 5 | { 6 | internal interface IGridCluster 7 | { 8 | IList RunCluster(); 9 | 10 | IList GetPolyLines(); // Google Maps debug lines 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Algo/Boundary.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using GoogleMaps.Net.Clustering.Data.Geometry; 3 | using GoogleMaps.Net.Clustering.Extensions; 4 | 5 | namespace GoogleMaps.Net.Clustering.Data.Algo 6 | { 7 | public class Boundary : Rectangle 8 | { 9 | public Boundary() { } 10 | public Boundary(Rectangle rectangle) 11 | { 12 | this.MinX = rectangle.MinX; 13 | this.MinY = rectangle.MinY; 14 | this.MaxX = rectangle.MaxX; 15 | this.MaxY = rectangle.MaxY; 16 | } 17 | 18 | 19 | /// 20 | /// Normalize lat and lon values to their boundary values 21 | /// O(1) 22 | /// 23 | public void Normalize() 24 | { 25 | MinX = MinX.NormalizeLongitude(); 26 | MaxX = MaxX.NormalizeLongitude(); 27 | MinY = MinY.NormalizeLatitude(); 28 | MaxY = MaxY.NormalizeLatitude(); 29 | } 30 | 31 | 32 | public void ValidateLatLon() 33 | { 34 | if ((MinX > LatLongInfo.MaxLonValue || MinX < LatLongInfo.MinLonValue) 35 | || (MaxX > LatLongInfo.MaxLonValue || MaxX < LatLongInfo.MinLonValue) 36 | || (MinY > LatLongInfo.MaxLatValue || MinY < LatLongInfo.MinLatValue) 37 | || (MaxY > LatLongInfo.MaxLatValue || MaxY < LatLongInfo.MinLatValue) 38 | ) 39 | throw new Exception(string.Concat("input Boundary.ValidateLatLon() error ", this)); 40 | } 41 | 42 | // Distance lon 43 | public double AbsX { get { return MinX.AbsLon(MaxX); } } 44 | 45 | // Distance lat 46 | public double AbsY { get { return MinY.AbsLat(MaxY); } } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Algo/Bucket.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using GoogleMaps.Net.Clustering.Data.Geometry; 3 | 4 | namespace GoogleMaps.Net.Clustering.Data.Algo 5 | { 6 | internal class Bucket 7 | { 8 | public string Id { get; private set; } 9 | 10 | public List Points { get; private set; } 11 | 12 | public MapPoint Centroid { get; set; } 13 | 14 | public int Idx { get; private set; } 15 | 16 | public int Idy { get; private set; } 17 | 18 | public double ErrorLevel { get; set; } // clusterpoint and points avg dist 19 | 20 | private bool _isUsed; 21 | 22 | public bool IsUsed 23 | { 24 | get { return _isUsed && Centroid != null; } 25 | set { _isUsed = value; } 26 | } 27 | 28 | public Bucket(string id) 29 | { 30 | IsUsed = true; 31 | Centroid = null; 32 | Points = new List(); 33 | Id = id; 34 | } 35 | 36 | public Bucket(int idx, int idy, string id) 37 | { 38 | IsUsed = true; 39 | Centroid = null; 40 | Points = new List(); 41 | Idx = idx; 42 | Idy = idy; 43 | Id = id; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Algo/ClusterInfo.cs: -------------------------------------------------------------------------------- 1 | namespace GoogleMaps.Net.Clustering.Data.Algo 2 | { 3 | internal static class ClusterInfo 4 | { 5 | // Don't filter when zoomed far out, because user json receive swlon and nelon values "jumps" to next overlapping lon point 6 | // and the program can't know from what to filter. 7 | // e.g. Is it from 160 to -160 or 160 to -160+360 ?? lon value 10 is filtered out in first case but should be included in 2nd case 8 | // heuristic and is based on html width value 9 | 10 | // Set a higher zoomlevel value if you increase the html window size. This works with width 800px, height 600px 11 | public static bool DoFilterData(int zoomlevel) 12 | { 13 | return zoomlevel >= 3; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/CacheKeys.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace GoogleMaps.Net.Clustering.Data 4 | { 5 | internal static class CacheKeys 6 | { 7 | private const string gmcKN = "gmcKN"; 8 | 9 | public static string PointsDatabase = String.Concat(gmcKN, "PointsDatabase"); 10 | 11 | public static string GetMarkers(int i) 12 | { 13 | return String.Concat(gmcKN, "GetMarkers", i); 14 | } 15 | 16 | public static string GetMarkerInfo(int i) 17 | { 18 | return String.Concat(gmcKN, "GetMarkerInfo", i); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Configuration/GmcSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | using System.Configuration; 5 | using GoogleMaps.Net.Clustering.Contract; 6 | 7 | namespace GoogleMaps.Net.Clustering.Data.Configuration 8 | { 9 | /// 10 | /// Configurations data 11 | /// Readonly fields 12 | /// Data are parsed from a config file 13 | /// 14 | public class GmcSettings : IGmcSettings 15 | { 16 | const string GoogleMapsSection = "googleMapsNetClustering"; 17 | 18 | private static IGmcSettings _algoConfig; 19 | 20 | /// 21 | /// Singleton 22 | /// 23 | public static IGmcSettings Get 24 | { 25 | get 26 | { 27 | return _algoConfig ?? (_algoConfig = new GmcSettings()); 28 | } 29 | } 30 | 31 | private GmcSettings() 32 | { 33 | var local = GetGoogleMapsSection(); 34 | string s; 35 | 36 | GridX = int.Parse(local[s = "GridX"] ?? Throw(s)); 37 | GridY = int.Parse(local[s = "GridY"] ?? Throw(s)); 38 | DoShowGridLinesInGoogleMap = bool.Parse(local[s = "DoShowGridLinesInGoogleMap"] ?? Throw(s)); 39 | OuterGridExtend = int.Parse(local[s = "OuterGridExtend"] ?? Throw(s)); 40 | DoUpdateAllCentroidsToNearestContainingPoint = bool.Parse(local[s = "DoUpdateAllCentroidsToNearestContainingPoint"] ?? Throw(s)); 41 | DoMergeGridIfCentroidsAreCloseToEachOther = bool.Parse(local[s = "DoMergeGridIfCentroidsAreCloseToEachOther"] ?? Throw(s)); 42 | MergeWithin = double.Parse(local[s = "MergeWithin"] ?? Throw(s)); 43 | MinClusterSize = int.Parse(local[s = "MinClusterSize"] ?? Throw(s)); 44 | MaxMarkersReturned = int.Parse(local[s = "MaxMarkersReturned"] ?? Throw(s)); 45 | AlwaysClusteringEnabledWhenZoomLevelLess = int.Parse(local[s = "AlwaysClusteringEnabledWhenZoomLevelLess"] ?? Throw(s)); 46 | ZoomlevelClusterStop = int.Parse(local[s = "ZoomlevelClusterStop"] ?? Throw(s)); 47 | MaxPointsInCache = int.Parse(local[s = "MaxPointsInCache"] ?? Throw(s)); 48 | CacheServices = bool.Parse(local[s = "CacheServices"] ?? Throw(s)); 49 | 50 | var types = (local[s = "MarkerTypes"] ?? Throw(s)).Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries); 51 | MarkerTypes = new HashSet(); 52 | foreach (var type in types) MarkerTypes.Add(int.Parse(type)); 53 | } 54 | 55 | // Use debug data 56 | public bool DoShowGridLinesInGoogleMap { get; private set; } // generate draw grid lines info to google map 57 | 58 | // How much data that is send to client 59 | // EDIT to extend to widen or shorten gridview for outside view, must be minimum 0 60 | // default value is 1 which returns same data as illustrated in the picture from my blog 61 | // (see googlemaps-clustering-viewport_ver1.png inside the Docements/Design folder) 62 | public int OuterGridExtend { get; private set; } 63 | 64 | // Move centroid point to nearest existing point? 65 | public bool DoUpdateAllCentroidsToNearestContainingPoint { get; private set; } 66 | 67 | // Merge clusterpoints if close to each other? 68 | public bool DoMergeGridIfCentroidsAreCloseToEachOther { get; private set; } 69 | 70 | // Cache get markers and get markers info services 71 | public bool CacheServices { get; private set; } 72 | 73 | // If neighbor cluster is within 1/n dist then merge, heuristic, higher value gives less merging 74 | public double MergeWithin { get; private set; } 75 | 76 | // Only cluster if minimum this number of points 77 | public int MinClusterSize { get; private set; } 78 | 79 | // If clustering is disabled, restrict number of markers returned 80 | public int MaxMarkersReturned { get; private set; } 81 | 82 | // Always cluster if equal or below this zoom level 83 | // to disable this effect set the value to -1 84 | public int AlwaysClusteringEnabledWhenZoomLevelLess { get; private set; } 85 | 86 | // Stop clustering from this zoom level and larger 87 | public int ZoomlevelClusterStop { get; private set; } 88 | 89 | // Grid array 90 | public int GridX { get; private set; } 91 | public int GridY { get; private set; } 92 | 93 | // Array of existing marker types 94 | public HashSet MarkerTypes { get; private set; } 95 | 96 | // Max allowed points in memory cache 97 | public int MaxPointsInCache { get; private set; } 98 | 99 | public string Environment { get; private set; } 100 | 101 | public NameValueCollection GetGoogleMapsSection() 102 | { 103 | return ConfigurationManager.GetSection(GoogleMapsSection) as NameValueCollection; 104 | } 105 | 106 | static string Throw(string s) 107 | { 108 | throw new Exception(string.Format("GmcGlobalKeySettings setup error: {0}", s)); 109 | } 110 | } 111 | } -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Configuration/IGmcSettings.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace GoogleMaps.Net.Clustering.Data.Configuration 4 | { 5 | public interface IGmcSettings 6 | { 7 | bool DoShowGridLinesInGoogleMap { get; } 8 | 9 | int OuterGridExtend { get; } 10 | 11 | bool DoUpdateAllCentroidsToNearestContainingPoint { get; } 12 | 13 | bool DoMergeGridIfCentroidsAreCloseToEachOther { get; } 14 | 15 | double MergeWithin { get; } 16 | 17 | int MinClusterSize { get; } 18 | 19 | int MaxMarkersReturned { get; } 20 | 21 | int AlwaysClusteringEnabledWhenZoomLevelLess { get; } 22 | 23 | int ZoomlevelClusterStop { get; } 24 | 25 | int GridX { get; } 26 | 27 | int GridY { get; } 28 | 29 | HashSet MarkerTypes { get; } 30 | 31 | int MaxPointsInCache { get; } 32 | 33 | string Environment { get; } 34 | 35 | bool CacheServices { get; } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/DatasetToSerialize.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Runtime.Serialization; 4 | using GoogleMaps.Net.Clustering.Data.Geometry; 5 | 6 | namespace GoogleMaps.Net.Clustering.Data 7 | { 8 | [Serializable] 9 | internal class DatasetToSerialize : ISerializable 10 | { 11 | private const string Name = "Dataset"; 12 | public List Dataset { get; set; } 13 | public DatasetToSerialize() 14 | { 15 | Dataset = new List(); 16 | } 17 | 18 | public DatasetToSerialize(SerializationInfo info, StreamingContext context) 19 | { 20 | this.Dataset = (List)info.GetValue(Name, typeof(List)); 21 | } 22 | 23 | public void GetObjectData(SerializationInfo info, StreamingContext context) 24 | { 25 | info.AddValue(Name, this.Dataset); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/FilterData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace GoogleMaps.Net.Clustering.Data 4 | { 5 | public class FilterData 6 | { 7 | public HashSet TypeFilterExclude { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Geometry/IMapPoint.cs: -------------------------------------------------------------------------------- 1 | namespace GoogleMaps.Net.Clustering.Data.Geometry 2 | { 3 | public interface IMapPoint 4 | { 5 | double X { get ; } 6 | 7 | double Y { get; } 8 | 9 | int Count { get; } 10 | 11 | int MarkerId { get; } 12 | 13 | int MarkerType { get; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Geometry/LatLongInfo.cs: -------------------------------------------------------------------------------- 1 | namespace GoogleMaps.Net.Clustering.Data.Geometry 2 | { 3 | internal static class LatLongInfo 4 | { 5 | public const double MinLatValue = -90; 6 | public const double MaxLatValue = 90; 7 | public static readonly double MinLonValue = -180; 8 | public const double MaxLonValue = 180; 9 | 10 | public const double MaxLatLength = 180; 11 | public const double MaxLonLength = 360; 12 | 13 | public const double MaxLengthWrap = 180; 14 | public const double MaxWorldLength = 360; 15 | 16 | public const double AngleConvert = 180; 17 | 18 | public const int Lat = 0; 19 | public const int Long = 1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Geometry/Line.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.Serialization; 3 | 4 | namespace GoogleMaps.Net.Clustering.Data.Geometry 5 | { 6 | /// 7 | /// Used for polylines display on google maps 8 | /// 9 | [Serializable] 10 | public class Line : ISerializable 11 | { 12 | public string X { get; set; } 13 | public string Y { get; set; } 14 | public string X2 { get; set; } 15 | public string Y2 { get; set; } 16 | 17 | public Line() 18 | { 19 | X = string.Empty; 20 | Y = string.Empty; 21 | X2 = string.Empty; 22 | Y2 = string.Empty; 23 | } 24 | 25 | public void GetObjectData(SerializationInfo info, StreamingContext context) 26 | { 27 | info.AddValue("X", this.X); 28 | info.AddValue("Y", this.Y); 29 | info.AddValue("X2", this.X2); 30 | info.AddValue("Y2", this.Y2); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Geometry/MapPoint.cs: -------------------------------------------------------------------------------- 1 | using GoogleMaps.Net.Clustering.Contract; 2 | using GoogleMaps.Net.Clustering.Extensions; 3 | using GoogleMaps.Net.Clustering.Utility; 4 | using System; 5 | using System.Runtime.Serialization; 6 | 7 | namespace GoogleMaps.Net.Clustering.Data.Geometry 8 | { 9 | /// 10 | /// Point class, overwrite it, modify it, extend it as you like 11 | /// 12 | [Serializable] 13 | public class MapPoint : MapPointBase, ISerializable, IMapPoint 14 | { 15 | public MapPoint() 16 | { 17 | } 18 | 19 | public MapPoint(double x, double y) : this() 20 | { 21 | X = x; 22 | Y = y; 23 | } 24 | 25 | public virtual MapPoint Normalize() 26 | { 27 | Long = Long.NormalizeLongitude(); 28 | Lat = Lat.NormalizeLatitude(); 29 | return this; 30 | } 31 | 32 | // Dist between two points on Earth 33 | public new virtual double Distance(double x, double y) 34 | { 35 | return MathTool.Haversine(this.Y, this.X, y, x); 36 | } 37 | 38 | public override string ToString() 39 | { 40 | return String.Format("Uid: {0}, X:{1}, Y:{2}, MarkerType:{3}, MarkerId:{4}", Uid, X, Y, MarkerType, MarkerId); 41 | } 42 | 43 | // Used for e.g. serialization to file 44 | public MapPoint(SerializationInfo info, StreamingContext ctxt) 45 | { 46 | this.Count = 1; 47 | this.MarkerId = (int)info.GetValue("MarkerId", typeof(int)); 48 | this.MarkerType = (int)info.GetValue("MarkerType", typeof(int)); 49 | this.X = ((string)info.GetValue("X", typeof(string))).ToDouble(); 50 | this.Y = ((string)info.GetValue("Y", typeof(string))).ToDouble(); 51 | } 52 | 53 | // Data returned as Json 54 | public virtual void GetObjectData(SerializationInfo info, StreamingContext ctxt) 55 | { 56 | info.AddValue("MarkerId", this.MarkerId); 57 | info.AddValue("MarkerType", this.MarkerType); 58 | info.AddValue("X", this.X); 59 | info.AddValue("Y", this.Y); 60 | info.AddValue("Count", this.Count); 61 | } 62 | 63 | public int CompareTo(MapPoint other, int dimension) 64 | { 65 | switch (dimension) 66 | { 67 | case 0: 68 | return this.X.CompareTo(other.X); 69 | case 1: 70 | return this.Y.CompareTo(other.Y); 71 | default: 72 | throw new ArgumentException("Invalid dimension."); 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Geometry/MapPointBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using GoogleMaps.Net.Clustering.Extensions; 3 | 4 | namespace GoogleMaps.Net.Clustering.Data.Geometry 5 | { 6 | [Serializable] 7 | public abstract class MapPointBase 8 | { 9 | private static int _counter; 10 | protected MapPointBase(){ Uid = ++_counter; Init();} 11 | 12 | public virtual int Uid { get; private set; } 13 | public virtual object Data { get; set; } // Data container for anything 14 | 15 | public virtual double X { get { return Long; } set { Long = value; } } 16 | public virtual double Y { get { return Lat; } set { Lat = value; } } 17 | public virtual int Type { get { return MarkerType; } set { MarkerType = value; } } 18 | 19 | public virtual int Count { get; set; } // count 20 | public virtual int MarkerId { get; set; } // marker id 21 | public virtual int MarkerType { get; set; } // marker type 22 | public virtual string Name { get; set; } // custom 23 | 24 | private double _lat; 25 | public virtual double Lat 26 | { 27 | get { return _lat.Round(); } 28 | set { _lat = value; } 29 | } 30 | 31 | private double _long; 32 | public virtual double Long 33 | { 34 | get { return _long.Round(); } 35 | set { _long = value; } 36 | } 37 | 38 | void Init() { Count = 1; } 39 | 40 | public virtual double Distance(MapPointBase mapPoint) 41 | { 42 | return Distance(mapPoint.X, mapPoint.Y); 43 | } 44 | 45 | // Euclidean distance 46 | public virtual double Distance(double x, double y) 47 | { 48 | var dX = X - x; 49 | var dY = Y - y; 50 | var dist = (dX * dX) + (dY * dY); 51 | //dist = Math.Sqrt(dist); 52 | return dist; 53 | } 54 | 55 | public override bool Equals(object obj) 56 | { 57 | var o = obj as MapPointBase; 58 | return GetHashCode() == o?.GetHashCode(); 59 | } 60 | 61 | public override int GetHashCode() 62 | { 63 | return Uid.GetHashCode(); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Geometry/Numbers.cs: -------------------------------------------------------------------------------- 1 | namespace GoogleMaps.Net.Clustering.Data.Geometry 2 | { 3 | internal static class Numbers 4 | { 5 | public const double Epsilon = 0.0000000001; 6 | public const int Round = 6; // lat long, 1 meter precision 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Geometry/Rectangle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace GoogleMaps.Net.Clustering.Data.Geometry 4 | { 5 | [Serializable] 6 | public class Rectangle 7 | { 8 | public double MinX { get; set; } 9 | public double MaxX { get; set; } 10 | public double MinY { get; set; } 11 | public double MaxY { get; set; } 12 | 13 | public override string ToString() 14 | { 15 | return String.Format("minx: {0} miny: {1} maxx: {2} maxy: {3}", MinX, MinY, MaxX, MaxY); 16 | } 17 | 18 | public override int GetHashCode() 19 | { 20 | return String.Format("{0}_{1}_{2}_{3}", MinX, MaxX, MinY, MaxY).GetHashCode(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/MarkersInput.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using GoogleMaps.Net.Clustering.Data.Algo; 5 | using GoogleMaps.Net.Clustering.Extensions; 6 | 7 | namespace GoogleMaps.Net.Clustering.Data 8 | { 9 | /// 10 | /// Parse json receive data 11 | /// 12 | internal class MarkersInput 13 | { 14 | // Data range are restricted if user abuse client-side 15 | private const int ZoomLevelMax = 30; 16 | public Boundary Viewport { get; private set; } 17 | 18 | private int _zoomlevel; 19 | public int Zoomlevel 20 | { 21 | get 22 | { 23 | return _zoomlevel; 24 | } 25 | private set 26 | { 27 | _zoomlevel = value; 28 | 29 | if (_zoomlevel < 0) 30 | _zoomlevel = 0; 31 | 32 | else if (_zoomlevel > ZoomLevelMax) 33 | _zoomlevel = ZoomLevelMax; 34 | } 35 | } 36 | 37 | public bool IsClusteringEnabled { get; private set; } 38 | 39 | public bool IsDebugLinesEnabled { get; private set; } 40 | 41 | public HashSet TypeFilterExclude { get; private set; } 42 | 43 | public MarkersInput(double nelat, double nelon, double swlat, double swlon, int zoomlevel, string filter) 44 | { 45 | Zoomlevel = zoomlevel; 46 | 47 | Viewport = new Boundary { MinX = swlon, MaxX = nelon, MinY = swlat, MaxY = nelat }; 48 | 49 | // Parse filter 50 | var typeFilter = new HashSet(); 51 | if (String.IsNullOrWhiteSpace(filter)) 52 | { 53 | // no filter used 54 | IsClusteringEnabled = true; 55 | IsDebugLinesEnabled = false; 56 | } 57 | else 58 | { 59 | int binarySum = 0; 60 | int.TryParse(filter, out binarySum); 61 | string binary = Convert.ToString(binarySum, 2); 62 | binary = Reverse(binary); // more easy to take index of when reversed 63 | 64 | // First two are reserved for cluster and debug lines flag 65 | IsClusteringEnabled = binary.Length >= 1 && binary[0] == '1'; 66 | IsDebugLinesEnabled = binary.Length >= 2 && binary[1] == '1'; 67 | 68 | // Rest are marker type filter 69 | var type1 = binary.Length >= 3 && binary[2] == '1'; 70 | var type2 = binary.Length >= 4 && binary[3] == '1'; 71 | var type3 = binary.Length >= 5 && binary[4] == '1'; 72 | 73 | if (!type1) typeFilter.Add(1); 74 | if (!type2) typeFilter.Add(2); 75 | if (!type3) typeFilter.Add(3); 76 | } 77 | 78 | TypeFilterExclude = typeFilter; 79 | } 80 | 81 | static string Reverse(string s) 82 | { 83 | char[] charArray = s.ToCharArray(); 84 | Array.Reverse(charArray); 85 | return new string(charArray); 86 | } 87 | 88 | public override int GetHashCode() 89 | { 90 | return String.Format("{0}_{1}_{2}", Viewport.GetHashCode(), Zoomlevel, FilterHashCode()).GetHashCode(); 91 | } 92 | 93 | public int FilterHashCode() 94 | { 95 | var filterKey = string.Concat(IsClusteringEnabled,IsDebugLinesEnabled); 96 | if (TypeFilterExclude.HasAny()) filterKey = TypeFilterExclude.Aggregate(filterKey, (a, b) => a + b + "_"); 97 | 98 | return filterKey.GetHashCode(); 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Params/GetMarkersParams.cs: -------------------------------------------------------------------------------- 1 | namespace GoogleMaps.Net.Clustering.Data.Params 2 | { 3 | public class GetMarkersParams 4 | { 5 | public double NorthEastLatitude { get; set; } 6 | 7 | public double NorthEastLongitude { get; set; } 8 | 9 | public double SouthWestLatitude { get; set; } 10 | 11 | public double SouthWestLongitude { get; set; } 12 | 13 | public int ZoomLevel { get; set; } 14 | 15 | public string Filter { get; set; } 16 | 17 | public string ClientWidth { get; set; } 18 | 19 | public string ClientHeigth { get; set; } 20 | 21 | /// 22 | /// Point type (optional). Used if you have different types of points on the map. 23 | /// For example - "Library", "Shop", "Hospital".. 24 | /// 25 | public string PointType { get; set; } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Repository/IPointsDatabase.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using GoogleMaps.Net.Clustering.Data.Geometry; 3 | 4 | namespace GoogleMaps.Net.Clustering.Contract 5 | { 6 | public interface IPointsDatabase 7 | { 8 | IList GetPoints(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Repository/PointsDatabase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using GoogleMaps.Net.Clustering.Contract; 6 | using GoogleMaps.Net.Clustering.Data.Configuration; 7 | using GoogleMaps.Net.Clustering.Data.Geometry; 8 | using GoogleMaps.Net.Clustering.Extensions; 9 | using GoogleMaps.Net.Clustering.Infrastructure; 10 | using GoogleMaps.Net.Clustering.Services; 11 | 12 | namespace GoogleMaps.Net.Clustering.Data.Repository 13 | { 14 | /// 15 | /// The database for all the existing points 16 | /// 17 | public class PointsDatabase : IPointsDatabase 18 | { 19 | public readonly string FilePath; 20 | 21 | protected readonly IMemCache _memCache; 22 | 23 | protected IList Points { get; set; } 24 | 25 | protected readonly object _threadsafe = new object(); 26 | 27 | public IList GetPoints() 28 | { 29 | return Points; 30 | } 31 | 32 | public PointsDatabase(IMemCache memCache, IList points) 33 | { 34 | _memCache = memCache; 35 | 36 | Points = _memCache.Get>(CacheKeys.PointsDatabase); 37 | if (Points != null) return; // cache hit 38 | 39 | lock (_threadsafe) 40 | { 41 | //Points = _memCache.Get>(CacheKeys.PointsDatabase); 42 | //if (Points != null) return; 43 | 44 | Points = new List(); 45 | 46 | // Not important, can be deleted, only for ensuring visual randomness of marker display 47 | // when not all can be displayed on screen 48 | // 49 | // Randomize order, when limit take is used for max marker display 50 | // random locations are selected 51 | // http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle 52 | var rnd = new Random(); 53 | var count = points.Count; 54 | for (var i = 0; i < count; i++) 55 | { 56 | MapPoint tmp = points[i]; 57 | int r = rnd.Next(count); 58 | points[i] = points[r]; 59 | points[r] = tmp; 60 | } 61 | 62 | Points = points; 63 | 64 | _memCache.Set>(CacheKeys.PointsDatabase, Points, TimeSpan.FromHours(24)); 65 | 66 | var data = _memCache.Get>(CacheKeys.PointsDatabase); 67 | if (data == null) 68 | { 69 | throw new Exception("cache not working"); 70 | } 71 | } 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Responses/ClusterMarkersResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using GoogleMaps.Net.Clustering.Data.Geometry; 3 | 4 | namespace GoogleMaps.Net.Clustering.Data.Responses 5 | { 6 | public class ClusterMarkersResponse : ResponseBase 7 | { 8 | public IList Markers { get; set; } // markers or clusters 9 | 10 | public IList Polylines { get; set; } // google map draw lines 11 | 12 | public int Count {get { return Markers.Count;} } // returned n markers 13 | 14 | public int Mia { get; set; } // truncated markers due to json restriction (missing in action) 15 | 16 | public ClusterMarkersResponse() 17 | { 18 | Markers = new List(); 19 | Polylines = new List(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Responses/MarkerInfoResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using GoogleMaps.Net.Clustering.Data.Geometry; 4 | 5 | namespace GoogleMaps.Net.Clustering.Data.Responses 6 | { 7 | public class MarkerInfoResponse : ResponseBase 8 | { 9 | public string Id { get; set; } 10 | public string Content { get; set; } 11 | public int Type { get; set; } 12 | public double Lat { get; set; } 13 | public double Long { get; set; } 14 | 15 | public void BuildContent(MapPoint point) 16 | { 17 | if (point == null) 18 | { 19 | Content = "Marker could not be found"; 20 | return; 21 | } 22 | 23 | Id = point.MarkerId.ToString(); 24 | Type = point.MarkerType; 25 | Lat = point.Lat; 26 | Long = point.Long; 27 | 28 | var stringBuilder = new StringBuilder(); 29 | stringBuilder.AppendLine("
"); 30 | stringBuilder.AppendFormat("Time: {0}
",DateTime.Now.ToString("HH:mm:ss")); 31 | stringBuilder.AppendFormat("Id: {0}
Type: {1}
", Id, Type); 32 | stringBuilder.AppendFormat("Lat: {0} Lon: {1}", point.Lat, point.Long); 33 | stringBuilder.AppendLine("
"); 34 | 35 | Content = stringBuilder.ToString(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Data/Responses/ResponseBase.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace GoogleMaps.Net.Clustering.Data.Responses 4 | { 5 | public abstract class ResponseBase 6 | { 7 | /// 8 | /// Server-side calculation elapsed time. 9 | /// 10 | public string Elapsed { get; set; } 11 | 12 | /// 13 | /// Operation result. 14 | /// 15 | public string OperationResult { get; set; } 16 | 17 | /// 18 | /// Error message. 19 | /// 20 | public string ErrorMessage { get; set; } 21 | 22 | /// 23 | /// Dev info. 24 | /// 25 | public string Debug { get; set; } 26 | 27 | /// 28 | /// Is data cached? 29 | /// 30 | [JsonProperty(Order = -2)] // makes it appear first in json response 31 | public bool? IsCached { get; set; } 32 | 33 | protected ResponseBase() 34 | { 35 | OperationResult = "1"; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Documents/Design/GoogleMapsClustering_SD_ver1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tihomir-kit/GoogleMaps.Net.Clustering/9ed96f748b792c584cd3691356dea553445288d6/GoogleMaps.Net.Clustering/Documents/Design/GoogleMapsClustering_SD_ver1.png -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Documents/Design/GoogleMapsClustering_SD_ver1.vsd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tihomir-kit/GoogleMaps.Net.Clustering/9ed96f748b792c584cd3691356dea553445288d6/GoogleMaps.Net.Clustering/Documents/Design/GoogleMapsClustering_SD_ver1.vsd -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Documents/Design/googlemaps-clustering-viewport_ver1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tihomir-kit/GoogleMaps.Net.Clustering/9ed96f748b792c584cd3691356dea553445288d6/GoogleMaps.Net.Clustering/Documents/Design/googlemaps-clustering-viewport_ver1.png -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Documents/Design/googlemaps-clustering-viewport_ver1.vsd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tihomir-kit/GoogleMaps.Net.Clustering/9ed96f748b792c584cd3691356dea553445288d6/GoogleMaps.Net.Clustering/Documents/Design/googlemaps-clustering-viewport_ver1.vsd -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Documents/FAQ.txt: -------------------------------------------------------------------------------- 1 | = Frequently Asked Questions = 2 | 3 | *Q. How do I get an overview of how this Google Maps Server-side clustering works?* 4 | 5 | A. Read my blog http://kunuk.wordpress.com/2011/11/05/google-map-server-side-clustering-with-asp-net/ 6 | 7 | --------------------------------- 8 | 9 | *Q. What do I need to run this?* 10 | 11 | A. Visual Studio 2010 or later, .Net v4. 12 | For deployment the web.config is configured for IIS 7 or later. 13 | 14 | --------------------------------- 15 | 16 | *Q. Where is the latest version?* 17 | 18 | A. The latest version is in the SVN repository, the trunk. 19 | If you want the latest version you should do SVN checkout. 20 | 21 | --------------------------------- 22 | 23 | *Q. How many points can I use?* 24 | 25 | A. With current implementation, the upper limit should be around 300.000 where the delay is below 1 sec. 26 | The server running time with an average laptop was about 300 msec. for 300.000 points. 27 | 28 | It should be possible to increase the number of points and keep a delay below 1 sec. 29 | by implementing a spatial data structure such as range search but it would only help if you are zoomed in. 30 | If you are zoomed all the way out you will have to iterate all the points 31 | then you would have to rely on pre-clustering for time complexity improvement. 32 | 33 | --------------------------------- 34 | 35 | *Q. How do I control the grid size?* 36 | 37 | A. In the file mapclustering.js 38 | specific values are set for gridx and gridy in the settings. 39 | 40 | --------------------------------- 41 | 42 | *Q. How do I load the dataset?* 43 | 44 | A. By default the dataset are loaded from a csv file to the Application session. 45 | Look how it is done in {{{Kunukn.GooglemapsClustering.Web.Application_Start}}} 46 | 47 | The csv file is located at 48 | {{{GoogleMapsClustering/Kunukn.GooglemapsClustering.Web/AreaGMC/Files/Points.csv}}} 49 | 50 | The format of the csv file is 51 | longitude; latitude; point id in GUID format; type id. 52 | 53 | The point id and type id data in this example are dummy data. 54 | The longitude and latitude are parsed to double values. 55 | point id and type id are parsed as int values. 56 | 57 | There is also the possible to load from a serialized file programmatically but no example file is included. 58 | Look in the code {{{Kunukn.GoogleMaps.Net.Clustering.Utility.Dataset.LoadDatasetFromDatabase()}}} 59 | 60 | --------------------------------- 61 | 62 | *Q. How do I set the initial zoom-level and position?* 63 | 64 | A. In the file mapclustering.js 65 | those values are set in the settings area. 66 | 67 | --------------------------------- 68 | 69 | *Q. When does the clustering stops?* 70 | 71 | A. You can define at which zoom-level the clustering should stop. 72 | In the file mapclustering.js in the settings set a value for zoomlevelClusterStop. 73 | 74 | --------------------------------- 75 | 76 | *Q. What are the red grid lines used for?* 77 | 78 | A. I made them for debugging purpose, i.e. to make sure the clustering behaved as intented. 79 | By default there can only be either one mark inside a grid. Either a cluster-point or a single point. 80 | 81 | --------------------------------- 82 | 83 | *Q. How do I enable/disable the red gridlines?* 84 | 85 | A. In the file {{{mapclustering.js }}} 86 | set the showGridLines to false or disable it server-side 87 | setting {{{GmcGlobalKeySettings.config DoShowGridLinesInGoogleMap}}} to false. 88 | I recommend to disable it server-side which will reduce the json-data size for the webservice call. 89 | 90 | --------------------------------- 91 | 92 | *Q. How do I extend the viewport data send to the client?* 93 | 94 | A. Increase or decrease the value in 95 | {{{GmcGlobalKeySettings.config OuterGridExtend}}} 96 | 97 | --------------------------------- 98 | 99 | *Q. How do I control the cluster merging point?* 100 | 101 | A. Increase or decrease the value in 102 | {{{GmcGlobalKeySettings.config MergeWithin}}} 103 | 104 | --------------------------------- 105 | 106 | *Q. How do I set the minimum count of points level before a cluster is made?* 107 | 108 | A. Increase or decrease the value in 109 | {{{GmcGlobalKeySettings.config MinClusterSize}}} 110 | 111 | --------------------------------- 112 | 113 | *Q. Is the clustering broken if I change the window size?* 114 | 115 | A. The clustering might behave buggy if you increase the window size. 116 | A quick fix is to edit the property {{{Kunukn.GooglemapsClustering.Data.ClusterInfo.IsFilterData}}} 117 | increase to higher value e.g. {{{ZoomLevel>=7}}}. This property is also used for filtering data returned to client. 118 | if set to never filter, then too much data will be send back to the client when zoomed far in. 119 | 120 | --------------------------------- 121 | 122 | *Q. How did you get the idea for the clustering part?* 123 | 124 | A. Inspiration from 125 | http://www.crunchpanorama.com/ and 126 | http://code.google.com/intl/da-DK/apis/maps/articles/toomanymarkers.html 127 | 128 | --------------------------------- 129 | 130 | *Q. What are the webservices used?* 131 | 132 | A. There are 3 get REST services 133 | 134 | * *{{{gmc.svc/getmarkers}}}* - for all the markers. 135 | * *{{{gmc.svc/getmarkerinfo}}}* - for specific info for seletected marker. 136 | * *{{{gmc.svc/knn}}}* - for k-nearest neighbors. 137 | 138 | For usage examples see {{{IAjaxService}}} interface and {{{AjaxService}}} class 139 | 140 | --------------------------------- 141 | 142 | *Q. Who made the Google Maps search function in this example?* 143 | 144 | A. The example code is with inspiration from 145 | http://tech.cibul.net/geocode-with-google-maps-api-v3/ 146 | 147 | --------------------------------- 148 | 149 | *Q. How many points are there in the demo example?* 150 | 151 | A. There are 130.530 points. 152 | 153 | --------------------------------- 154 | 155 | *Q. Where did you get the points?* 156 | 157 | A. The points are taken from the file cities1000 at http://download.geonames.org/export/dump/ 158 | 159 | --------------------------------- 160 | 161 | *Q. How can I customize this to use most points and keep fast performance?* 162 | 163 | A. 164 | In the file: {{{GmcGlobalKeySettings.config}}}. 165 | Set {{{OuterGridExtend}}} to 0. 166 | Set {{{DoMergeGridIfCentroidsAreCloseToEachOther}}} to false. 167 | Set {{{DoShowGridLinesInGoogleMap}}} to false. 168 | 169 | 170 | In the mapclustering.js in the settings. 171 | set gridx and gridy to low numbers, e.g. 2 and 2. 172 | --------------------------------- 173 | 174 | *Q. How do I generate random data points?* 175 | 176 | A. Use the method: {{{Kunukn.GooglemapsClustering.TestConsole.Program.GenerateRandomDatasetToCSVFile()}}} 177 | to update information for how many points you want and in which area you want them. 178 | 179 | --------------------------------- 180 | 181 | *Q. What license type is this?* 182 | 183 | A. MIT License. 184 | 185 | --------------------------------- 186 | 187 | *Q. How much does it cost to use Google Maps?* 188 | 189 | A. Google knows the answer. Try this link https://developers.google.com/maps/faq 190 | 191 | --------------------------------- 192 | 193 | *Q. What is the complexity of time and space?* 194 | 195 | A. Time complexity is on average(m*n) and space complexity is O(m*n) 196 | where n is the number of points used in total and m is the number of grids returned to the client. 197 | You are welcome to analyse it yourself :) I use hashset and hashmap to minimize the time complexity. 198 | 199 | Time complexity is ~ O(n^2) on worst case but extremely unlikely, 200 | happens if most centroids are merged with neighbor-centroids 201 | (not a likely scenario for common dataset, where data only exists at grid borderlines). 202 | 203 | --------------------------------- 204 | 205 | *Q. Why do the red gridlines look wierd when zoomed far out?* 206 | 207 | A. Because the world wraps and multiple areas are displayed for same latlon values. 208 | Some more logic can be applied to draw the grid lines properly for those conditions but has been left out. 209 | This happens only on zoom level below 3. 210 | 211 | --------------------------------- 212 | 213 | *Q. Who made this?* 214 | 215 | A. Kunuk Nykjaer spend the time in the weekends to make 216 | a stationary grid-based clustering after preliminary research on different clustering approach. 217 | On my time on the job I made a marker-clusterer version 218 | which I later discontinued because I felt the grid-based worked better. 219 | All the server-side clustering logic is made by Kunuk Nykjaer. 220 | The JS GUI-part is largely adapted and reworked by Kunuk Nykjaer and the inspiration came partly 221 | from JS-implementation by Jonas Olsen, Lars Gundersen and misc. http://stackoverflow.com/ pages. 222 | The server-side webservice definition (asmx files) are with inspiration from Lasse Rasch's implementations. 223 | The JS logic-part (cluster points updating, lines drawing) was made by Kunuk Nykjaer). 224 | The address search part done with inspiration 225 | from http://tech.cibul.net/geocode-with-google-maps-api-v3/. 226 | The cluster images are taken from Google's example images. 227 | The marker images are taken from http://mapicons.nicolasmollet.com/ 228 | 229 | * Kunuk Nykjaer http://dk.linkedin.com/in/kunukn/ 230 | * Jonas Olsen http://dk.linkedin.com/in/joolz/ 231 | * Lars Gundersen http://dk.linkedin.com/in/larsgundersen/ 232 | * Lasse Rasch http://dk.linkedin.com/pub/lasse-rasch/7/991/a10/ 233 | 234 | --------------------------------- -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Documents/License.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | The Software MIT License only includes 4 | the clustering implementation details. 5 | The images and JS address search implementation details 6 | is not included in this copyright. 7 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Extensions/DataExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Linq; 5 | using GoogleMaps.Net.Clustering.Data.Geometry; 6 | 7 | namespace GoogleMaps.Net.Clustering.Extensions 8 | { 9 | internal static class DataExtension 10 | { 11 | static readonly CultureInfo CultureEnUs = new CultureInfo("en-US"); 12 | const string S = "G"; 13 | 14 | const double Pi2 = Math.PI * 2; 15 | public const int RoundConvertError = 5; 16 | 17 | public static double Round(this double d) 18 | { 19 | return Math.Round(d, Numbers.Round); 20 | } 21 | 22 | public static void Normalize(this List list) 23 | { 24 | foreach (var p in list) p.Normalize(); 25 | } 26 | 27 | // Distance 28 | public static double AbsLat(this double beg, double end) 29 | { 30 | double b = beg; 31 | double e = end; 32 | if (b > e) 33 | { 34 | e += LatLongInfo.MaxLatLength; 35 | } 36 | 37 | double diff = e - b; 38 | if (diff < 0 || diff > LatLongInfo.MaxLatLength) 39 | { 40 | throw new ApplicationException(string.Format("Error AbsLat beg: {0} end: {1}", beg, end)); 41 | } 42 | 43 | return diff; 44 | } 45 | 46 | // Distance 47 | public static double AbsLon(this double beg, double end) 48 | { 49 | double b = beg; 50 | double e = end; 51 | if (b > e) 52 | { 53 | e += LatLongInfo.MaxLonLength; 54 | } 55 | double diff = e - b; 56 | if (diff < 0 || diff > LatLongInfo.MaxLonLength) 57 | { 58 | throw new ApplicationException(string.Format("Error AbsLon beg: {0} end: {1}", beg, end)); 59 | } 60 | 61 | return diff; 62 | } 63 | 64 | // positive version of lat, lon 65 | public static double Pos(this double latlon) 66 | { 67 | if (latlon < LatLongInfo.MinLonValue || latlon > LatLongInfo.MaxLonValue) 68 | { 69 | throw new ApplicationException("Pos"); 70 | } 71 | 72 | if (latlon < 0) 73 | { 74 | return latlon + LatLongInfo.MaxWorldLength; 75 | } 76 | 77 | return latlon; 78 | } 79 | 80 | 81 | // Lat or Lon 82 | public static double LatLongToDegree(this double latlon) 83 | { 84 | if (latlon < LatLongInfo.MinLonValue || latlon > LatLongInfo.MaxLonValue) 85 | { 86 | throw new ApplicationException("LatLonToDegree"); 87 | } 88 | 89 | return (latlon + LatLongInfo.AngleConvert + LatLongInfo.MaxWorldLength) % LatLongInfo.MaxWorldLength; 90 | } 91 | public static double DegreeToLatLong(this double degree) 92 | { 93 | if (degree < 0 || degree > 360) 94 | { 95 | throw new ApplicationException("DegreeToLatLon"); 96 | } 97 | 98 | return (degree - LatLongInfo.AngleConvert); 99 | } 100 | 101 | public static double LatLongToRadian(this double latlon) 102 | { 103 | if (latlon < LatLongInfo.MinLonValue || latlon > LatLongInfo.MaxLonValue) 104 | { 105 | throw new ApplicationException("LatLongToRadian"); 106 | } 107 | 108 | var degree = LatLongToDegree(latlon); 109 | var radian = DegreeToRadian(degree); 110 | return radian; 111 | } 112 | 113 | public static double RadianNormalize(this double r) 114 | { 115 | if (r < -Pi2 || r > Pi2) 116 | { 117 | throw new ApplicationException("RadianNormalize"); 118 | } 119 | 120 | var radian = (r + Pi2) % Pi2; 121 | if (radian < 0 || radian > Pi2) 122 | { 123 | throw new ApplicationException("RadianNormalize"); 124 | } 125 | 126 | return radian; 127 | } 128 | 129 | public static double DegreeNormalize(this double d) 130 | { 131 | if (d < -360 || d > 360) 132 | { 133 | throw new ApplicationException("DegreeNormalize"); 134 | } 135 | 136 | var degree = (d + 360) % 360; 137 | if (degree < 0 || degree > 360) 138 | { 139 | throw new ApplicationException("DegreeNormalize"); 140 | } 141 | 142 | return degree; 143 | } 144 | 145 | 146 | public static double RadianToLatLong(this double r) 147 | { 148 | var radian = RadianNormalize(r); 149 | if (radian < 0 || radian > Pi2) 150 | { 151 | throw new ApplicationException("RadianToLatLong"); 152 | } 153 | 154 | var degree = DegreeNormalize(RadianToDegree(radian) ); 155 | var degreeRounded = Math.Round(degree, RoundConvertError); 156 | var latlon = DegreeToLatLong(degreeRounded); 157 | return latlon; 158 | } 159 | 160 | public static double RadianToDegree(this double radian) 161 | { 162 | if (radian < 0 || radian > Pi2) 163 | { 164 | throw new ApplicationException("RadianToDegree"); 165 | } 166 | 167 | return (radian / Math.PI) * 180.0; 168 | } 169 | public static double DegreeToRadian(this double degree) 170 | { 171 | if (degree < 0 || degree > 360) 172 | { 173 | throw new ApplicationException("DegreeToRadian"); 174 | } 175 | 176 | return (degree * Math.PI) / 180.0; 177 | } 178 | 179 | 180 | // ]-180;180] 181 | // lon wrap around at value -180 and 180, nb. -180 = 180 182 | public static double NormalizeLongitude(this double lon) 183 | { 184 | // naive version 185 | //while(normalized LatLongInfo.MaxLonValue) 194 | { 195 | var m = lon % LatLongInfo.MaxLonValue; 196 | normalized = LatLongInfo.MinLonValue + m; 197 | } 198 | 199 | return normalized; 200 | } 201 | 202 | // [-90;90] 203 | // -90 is south pole, 90 is north pole thus -90 != 90 204 | // no wrap, because google map dont wrap on lat 205 | public static double NormalizeLatitude(this double lat) 206 | { 207 | double normalized = lat; 208 | if (lat < LatLongInfo.MinLatValue) 209 | { 210 | //var m = lat % -LatLonInfo.MaxLatValue; 211 | //normalized = LatLonInfo.MaxLatValue + m; 212 | normalized = LatLongInfo.MinLatValue; 213 | } 214 | if (lat > LatLongInfo.MaxLatValue) 215 | { 216 | //var m = lat % LatLonInfo.MaxLatValue; 217 | //normalized = -LatLonInfo.MaxLatValue + m; 218 | normalized = LatLongInfo.MaxLatValue; 219 | } 220 | 221 | return normalized; 222 | } 223 | 224 | public static double ToDouble(this string s) 225 | { 226 | return double.Parse(s, NumberStyles.Float, NumberFormatInfo.InvariantInfo); 227 | } 228 | 229 | public static int ToInt(this string s) 230 | { 231 | return int.Parse(s); 232 | } 233 | 234 | public static string DoubleToString(this double d) 235 | { 236 | double rounded = Math.Round(d, Numbers.Round); 237 | return rounded.ToString(S, CultureEnUs); 238 | } 239 | 240 | public static string ListToString(this List list ) 241 | { 242 | return list.Aggregate("", (a, b) => a + "[" + b + "]\n"); 243 | } 244 | 245 | public static int[] ToNumbers(this string s) 246 | { 247 | if(string.IsNullOrWhiteSpace(s)) return new int[]{}; 248 | 249 | var arr = s.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries); 250 | var ints = new int[arr.Length]; 251 | for (var i = 0; i < arr.Length; i++) 252 | { 253 | ints[i] = int.Parse(arr[i]); 254 | } 255 | 256 | return ints; 257 | } 258 | } 259 | } -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Extensions/IEnumerableExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace GoogleMaps.Net.Clustering.Extensions 6 | { 7 | internal static class IEnumerableExtension 8 | { 9 | public static bool HasAny(this IEnumerable enumerable) 10 | { 11 | return enumerable != null && enumerable.Any(); 12 | } 13 | 14 | public static bool None(this IEnumerable enumerable) 15 | { 16 | return enumerable == null || !enumerable.Any(); 17 | } 18 | 19 | public static void ForEach(this IEnumerable enumerable, Action action) 20 | { 21 | Array.ForEach(enumerable.ToArray(), action); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/GoogleMaps.Net.Clustering.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {CEE02707-BBC1-4C90-BB96-66CA79BA48D6} 8 | Library 9 | Properties 10 | GoogleMaps.Net.Clustering 11 | GoogleMaps.Net.Clustering 12 | v4.5 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | ..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll 36 | True 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 | 99 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Infrastructure/IMemCache.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace GoogleMaps.Net.Clustering.Infrastructure 4 | { 5 | public interface IMemCache // TODO: make internal? 6 | { 7 | T Get(string key) where T : class; 8 | 9 | bool Add(string key, T objectToCache, TimeSpan timespan); 10 | 11 | void Set(string key, T objectToCache, TimeSpan timespan); 12 | 13 | object Remove(string key); 14 | 15 | bool Exists(string key); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Infrastructure/IPointCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using GoogleMaps.Net.Clustering.Data.Geometry; 4 | 5 | namespace GoogleMaps.Net.Clustering.Infrastructure 6 | { 7 | public interface IPointCollection 8 | { 9 | IList Get(string pointType = null); 10 | 11 | bool Add(IList points, TimeSpan timespan, string pointType = null); 12 | 13 | void Set(IList points, TimeSpan timespan, string pointType = null); 14 | 15 | object Remove(string pointType = null); 16 | 17 | bool Exists(string pointType = null); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Infrastructure/MemCache.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using GoogleMaps.Net.Clustering.Contract; 3 | using System.Runtime.Caching; 4 | using GoogleMaps.Net.Clustering.Services; 5 | 6 | namespace GoogleMaps.Net.Clustering.Infrastructure 7 | { 8 | /// 9 | /// http://msdn.microsoft.com/library/system.runtime.caching.memorycache.aspx 10 | /// 11 | public class MemCache : IMemCache // TODO: make internal? 12 | { 13 | private readonly ObjectCache _cache = MemoryCache.Default; 14 | 15 | public T Get(string key) where T : class 16 | { 17 | var cachedObj = _cache[key]; 18 | if (cachedObj == null) 19 | return default(T); 20 | 21 | return cachedObj as T; 22 | } 23 | 24 | /// 25 | /// Only add if not already added 26 | /// return whether it was added 27 | /// 28 | public bool Add(string key, T objectToCache, TimeSpan timespan) 29 | { 30 | return _cache.Add(key, objectToCache, DateTime.Now.Add(timespan)); 31 | } 32 | 33 | public void Set(string key, T objectToCache, TimeSpan timespan) 34 | { 35 | _cache.Set(key, objectToCache, DateTime.Now.Add(timespan)); 36 | } 37 | 38 | public object Remove(string key) 39 | { 40 | return _cache.Remove(key); 41 | } 42 | public bool Exists(string key) 43 | { 44 | return _cache.Get(key) != null; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Infrastructure/PointCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using GoogleMaps.Net.Clustering.Contract; 4 | using System.Runtime.Caching; 5 | using GoogleMaps.Net.Clustering.Data; 6 | using GoogleMaps.Net.Clustering.Data.Geometry; 7 | using GoogleMaps.Net.Clustering.Services; 8 | using GoogleMaps.Net.Clustering.Utility; 9 | 10 | namespace GoogleMaps.Net.Clustering.Infrastructure 11 | { 12 | /// 13 | /// http://msdn.microsoft.com/library/system.runtime.caching.memorycache.aspx 14 | /// 15 | public class PointCollection : IPointCollection 16 | { 17 | protected readonly IMemCache _memCache; 18 | //public IMemCache MemCache => _memCache; 19 | 20 | protected readonly object _threadsafe = new object(); 21 | 22 | public PointCollection() 23 | { 24 | _memCache = new MemCache(); 25 | } 26 | 27 | public IList Get(string pointType = null) 28 | { 29 | var key = GetPointKey(pointType); 30 | return _memCache.Get>(key); 31 | } 32 | 33 | /// 34 | /// Only add if not already added 35 | /// return whether it was added 36 | /// 37 | public bool Add(IList points, TimeSpan timespan, string pointType = null) 38 | { 39 | var key = GetPointKey(pointType); 40 | return _memCache.Add(key, RandomizePointOrder(points), timespan); 41 | } 42 | 43 | public void Set(IList points, TimeSpan timespan, string pointType = null) 44 | { 45 | var key = GetPointKey(pointType); 46 | _memCache.Set(key, RandomizePointOrder(points), timespan); 47 | } 48 | 49 | public object Remove(string pointType = null) 50 | { 51 | var key = GetPointKey(pointType); 52 | return _memCache.Remove(key); 53 | } 54 | 55 | public bool Exists(string pointType = null) 56 | { 57 | var key = GetPointKey(pointType); 58 | return _memCache.Exists(key); 59 | } 60 | 61 | /// 62 | /// Not really that important, could be ommited. Used only for ensuring visual 63 | /// randomness of marker display when not all can be displayed on screen. 64 | /// 65 | /// Randomize order, when limit take is used for max marker display 66 | /// random locations are selected 67 | /// http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle 68 | /// 69 | /// Points to randomize. 70 | /// Points in randomized order. 71 | private IList RandomizePointOrder(IList points) 72 | { 73 | lock (_threadsafe) 74 | { 75 | var rnd = new Random(); 76 | for (var i = 0; i < points.Count; i++) 77 | { 78 | MapPoint tmp = points[i]; 79 | int r = rnd.Next(points.Count); 80 | points[i] = points[r]; 81 | points[r] = tmp; 82 | } 83 | 84 | return points; 85 | } 86 | } 87 | 88 | private static string GetPointKey(string pointType) 89 | { 90 | return String.Concat(CacheKeys.PointsDatabase, pointType); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("GoogleMaps.Net.Clustering")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("GoogleMaps.Net.Clustering")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("cee02707-bbc1-4c90-bb96-66ca79ba48d6")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Services/ClusterService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using GoogleMaps.Net.Clustering.Algorithm; 6 | using GoogleMaps.Net.Clustering.Contract; 7 | using GoogleMaps.Net.Clustering.Data; 8 | using GoogleMaps.Net.Clustering.Data.Configuration; 9 | using GoogleMaps.Net.Clustering.Data.Geometry; 10 | using GoogleMaps.Net.Clustering.Data.Params; 11 | using GoogleMaps.Net.Clustering.Data.Responses; 12 | using GoogleMaps.Net.Clustering.Extensions; 13 | using GoogleMaps.Net.Clustering.Infrastructure; 14 | using GoogleMaps.Net.Clustering.Services; 15 | using GoogleMaps.Net.Clustering.Utility; 16 | 17 | namespace GoogleMaps.Net.Clustering.Services 18 | { 19 | public class ClusterService : IClusterService 20 | { 21 | private readonly IPointCollection _pointCollection; 22 | private readonly IMemCache _memCache; 23 | 24 | public ClusterService(IPointCollection pointCollection) 25 | { 26 | _pointCollection = pointCollection; 27 | _memCache = new MemCache(); 28 | } 29 | 30 | public ClusterMarkersResponse GetClusterMarkers(GetMarkersParams getParams) 31 | { 32 | // Decorate with elapsed time 33 | var sw = new Stopwatch(); 34 | sw.Start(); 35 | var reply = GetMarkersHelper(getParams); 36 | sw.Stop(); 37 | reply.Elapsed = sw.Elapsed.ToString(); 38 | return reply; 39 | } 40 | 41 | /// 42 | /// Read Through Cache 43 | /// 44 | /// 45 | /// 46 | private ClusterMarkersResponse GetMarkersHelper(GetMarkersParams getParams) 47 | { 48 | try 49 | { 50 | var neLat = getParams.NorthEastLatitude; 51 | var neLong = getParams.NorthEastLongitude; 52 | var swLat = getParams.SouthWestLatitude; 53 | var swLong = getParams.SouthWestLongitude; 54 | var zoomLevel = getParams.ZoomLevel; 55 | var filter = getParams.Filter ?? ""; 56 | 57 | // values are validated there 58 | var markersInput = new MarkersInput(neLat, neLong, swLat, swLong, zoomLevel, filter); 59 | 60 | var grid = GridCluster.GetBoundaryExtended(markersInput); 61 | var cacheKeyHelper = string.Format("{0}_{1}_{2}", markersInput.Zoomlevel, markersInput.FilterHashCode(), grid.GetHashCode()); 62 | var cacheKey = CacheKeys.GetMarkers(cacheKeyHelper.GetHashCode()); 63 | 64 | var response = new ClusterMarkersResponse(); 65 | 66 | markersInput.Viewport.ValidateLatLon(); // Validate google map viewport input (should be always valid) 67 | markersInput.Viewport.Normalize(); 68 | 69 | // Get all points from memory 70 | IList points = _pointCollection.Get(getParams.PointType); // _pointsDatabase.GetPoints(); 71 | 72 | // Filter points 73 | points = FilterUtil.FilterByType( 74 | points, 75 | new FilterData { TypeFilterExclude = markersInput.TypeFilterExclude } 76 | ); 77 | 78 | 79 | 80 | // Create new instance for every ajax request with input all points and json data 81 | var clusterAlgo = new GridCluster(points, markersInput); 82 | 83 | var clusteringEnabled = markersInput.IsClusteringEnabled 84 | || GmcSettings.Get.AlwaysClusteringEnabledWhenZoomLevelLess > markersInput.Zoomlevel; 85 | 86 | // Clustering 87 | if (clusteringEnabled && markersInput.Zoomlevel < GmcSettings.Get.ZoomlevelClusterStop) 88 | { 89 | IList markers = clusterAlgo.RunCluster(); 90 | 91 | response = new ClusterMarkersResponse 92 | { 93 | Markers = markers, 94 | Polylines = clusterAlgo.GetPolyLines() 95 | }; 96 | } 97 | else 98 | { 99 | // If we are here then there are no clustering 100 | // The number of items returned is restricted to avoid json data overflow 101 | IList filteredDataset = FilterUtil.FilterDataByViewport(points, markersInput.Viewport); 102 | IList filteredDatasetMaxPoints = filteredDataset.Take(GmcSettings.Get.MaxMarkersReturned).ToList(); 103 | 104 | response = new ClusterMarkersResponse 105 | { 106 | Markers = filteredDatasetMaxPoints, 107 | Polylines = clusterAlgo.GetPolyLines(), 108 | Mia = filteredDataset.Count - filteredDatasetMaxPoints.Count, 109 | }; 110 | } 111 | 112 | // if client ne and sw is inside a specific grid box then cache the grid box and the result 113 | // next time test if ne and sw is inside the grid box and return the cached result 114 | if (GmcSettings.Get.CacheServices) 115 | _memCache.Set(cacheKey, response, TimeSpan.FromMinutes(10)); // cache data 116 | 117 | return response; 118 | } 119 | catch (Exception ex) 120 | { 121 | return new ClusterMarkersResponse 122 | { 123 | OperationResult = "0", 124 | ErrorMessage = string.Format("MapService says: exception {0}", ex.Message) 125 | }; 126 | } 127 | } 128 | 129 | 130 | public MarkerInfoResponse GetMarkerInfo(int uid, string pointType = null) 131 | { 132 | // Decorate with elapsed time 133 | var sw = new Stopwatch(); 134 | sw.Start(); 135 | var reply = GetMarkerInfoResponse(uid); 136 | sw.Stop(); 137 | reply.Elapsed = sw.Elapsed.ToString(); 138 | return reply; 139 | } 140 | 141 | 142 | /// 143 | /// Read Through Cache 144 | /// 145 | /// 146 | /// 147 | private MarkerInfoResponse GetMarkerInfoResponse(int uid, string pointType = null) 148 | { 149 | try 150 | { 151 | var cacheKey = CacheKeys.GetMarkerInfo(uid); 152 | var reply = _memCache.Get(cacheKey); 153 | if (reply != null) 154 | { 155 | // return cached data 156 | reply.IsCached = true; 157 | return reply; 158 | } 159 | 160 | MapPoint marker = _pointCollection.Get(pointType).SingleOrDefault(i => i.MarkerId == uid); 161 | 162 | reply = new MarkerInfoResponse { Id = uid.ToString() }; 163 | reply.BuildContent(marker); 164 | 165 | if (GmcSettings.Get.CacheServices) 166 | _memCache.Set(cacheKey, reply, TimeSpan.FromMinutes(10)); // cache data 167 | 168 | return reply; 169 | } 170 | catch (Exception ex) 171 | { 172 | return new MarkerInfoResponse 173 | { 174 | OperationResult = "0", 175 | ErrorMessage = string.Format("MapService says: Parsing error param: {0}", ex.Message) 176 | }; 177 | } 178 | } 179 | } 180 | } -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Services/IClusterService.cs: -------------------------------------------------------------------------------- 1 | using GoogleMaps.Net.Clustering.Data.Params; 2 | using GoogleMaps.Net.Clustering.Data.Responses; 3 | 4 | namespace GoogleMaps.Net.Clustering.Services 5 | { 6 | public interface IClusterService 7 | { 8 | ClusterMarkersResponse GetClusterMarkers(GetMarkersParams getParams); 9 | 10 | MarkerInfoResponse GetMarkerInfo(int uid, string pointType = null); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Utility/ExceptionUtil.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace GoogleMaps.Net.Clustering.Utility 4 | { 5 | internal static class ExceptionUtil 6 | { 7 | public static string GetException(Exception ex) 8 | { 9 | return String.Format("Msg:{0}\nStacktrace:{1}\nInnerExc:{2}", ex.Message, ex.StackTrace, ex.InnerException); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Utility/FilterUtil.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using GoogleMaps.Net.Clustering.Data; 4 | using GoogleMaps.Net.Clustering.Data.Algo; 5 | using GoogleMaps.Net.Clustering.Data.Configuration; 6 | using GoogleMaps.Net.Clustering.Data.Geometry; 7 | using GoogleMaps.Net.Clustering.Extensions; 8 | 9 | namespace GoogleMaps.Net.Clustering.Utility 10 | { 11 | internal static class FilterUtil 12 | { 13 | /// 14 | /// Supports threads 15 | /// 16 | /// 17 | /// 18 | /// 19 | public static IList FilterByType(IList points, FilterData filterData) 20 | { 21 | if (filterData.TypeFilterExclude.Count == GmcSettings.Get.MarkerTypes.Count) 22 | { 23 | // Filter all 24 | return new List(); // empty 25 | } 26 | if (filterData.TypeFilterExclude.None()) 27 | { 28 | // Filter none 29 | return points; 30 | } 31 | 32 | // Filter data by typeFilter value 33 | return FilterByTypeHelper(points, filterData); 34 | } 35 | 36 | // O(n) 37 | public static IList FilterDataByViewport(IList points, Boundary viewport) 38 | { 39 | return points 40 | .Where(i => MathTool.IsInside(viewport, i)) 41 | .ToList(); 42 | } 43 | 44 | // O(n) 45 | private static IList FilterByTypeHelper(IList points, FilterData filterData) 46 | { 47 | return points 48 | .Where(p => filterData.TypeFilterExclude.Contains(p.MarkerType) == false) 49 | .ToList(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/Utility/MathTool.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using GoogleMaps.Net.Clustering.Data.Algo; 3 | using GoogleMaps.Net.Clustering.Data.Geometry; 4 | using GoogleMaps.Net.Clustering.Extensions; 5 | 6 | namespace GoogleMaps.Net.Clustering.Utility 7 | { 8 | /// 9 | /// Author: Kunuk Nykjaer 10 | /// 11 | internal static class MathTool 12 | { 13 | const double Exp = 2; // 2=euclid, 1=manhatten 14 | 15 | // Minkowski dist 16 | // if lat lon precise dist is needed, use Haversine or similar formulas 17 | // this is approx calc for clustering, no precise dist is needed 18 | public static double Distance(MapPoint a, MapPoint b) 19 | { 20 | // lat lon wrap, values don't seem needed to be normalized to [0;1] for better distance calc 21 | var absx = LatLonDiff(a.X, b.X); 22 | var absy = LatLonDiff(a.Y, b.Y); 23 | 24 | return Math.Pow(Math.Pow(absx, Exp) + 25 | Math.Pow(Math.Abs(absy), Exp), 1.0 / Exp); 26 | } 27 | 28 | // O(1) while loop is maximum 2 29 | public static double LatLonDiff(double from, double to) 30 | { 31 | double difference = to - from; 32 | while (difference < -LatLongInfo.MaxLengthWrap) difference += LatLongInfo.MaxWorldLength; 33 | while (difference > LatLongInfo.MaxLengthWrap) difference -= LatLongInfo.MaxWorldLength; 34 | return Math.Abs(difference); 35 | 36 | //var differenceAngle = (to - from) % 180; //not working for -170 to 170 37 | //return Math.Abs(differenceAngle); 38 | } 39 | 40 | public static double Haversine(MapPoint p1, MapPoint p2) 41 | { 42 | return Haversine(p1.Y, p1.X, p2.Y, p2.X); 43 | } 44 | 45 | // http://en.wikipedia.org/wiki/Haversine_formula 46 | // Approx dist between two points on earth 47 | //public static double Haversine(double lat1, double lon1, double lat2, double lon2) 48 | //{ 49 | // const int r = 6371; // km 50 | // var dLat = ToRadians(lat2 - lat1); 51 | // var dLon = ToRadians(lon2 - lon1); 52 | // lat1 = ToRadians(lat1); 53 | // lat2 = ToRadians(lat2); 54 | 55 | // var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + 56 | // Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2); 57 | // var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); 58 | // var d = r * c; 59 | // return d; 60 | //} 61 | // http://en.wikipedia.org/wiki/Haversine_formula 62 | // Approx dist between two points on earth 63 | // http://rosettacode.org/wiki/Haversine_formula 64 | public static double Haversine(double lat1, double long1, double lat2, double long2) 65 | { 66 | const double r = 6372.8; // In kilometers 67 | var dLat = ToRadians(lat2 - lat1); 68 | var dLong = ToRadians(long2 - long1); 69 | lat1 = ToRadians(lat1); 70 | lat2 = ToRadians(lat2); 71 | 72 | var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + 73 | Math.Sin(dLong / 2) * Math.Sin(dLong / 2) * Math.Cos(lat1) * Math.Cos(lat2); 74 | var c = 2 * Math.Asin(Math.Sqrt(a)); 75 | var d = r * c; 76 | return d; 77 | } 78 | 79 | public static double ToRadians(double angle) 80 | { 81 | return Math.PI * angle / 180.0; 82 | } 83 | 84 | public static bool IsLowerThanLatMin(double d) 85 | { 86 | return d < LatLongInfo.MinLatValue; 87 | } 88 | public static bool IsGreaterThanLatMax(double d) 89 | { 90 | return d > LatLongInfo.MaxLatValue; 91 | } 92 | 93 | /// 94 | /// Lat Lon specific rect boundary check, is x,y inside boundary? 95 | /// 96 | /// 97 | /// 98 | /// 99 | /// 100 | /// 101 | /// 102 | /// /// 103 | /// /// 104 | /// 105 | public static bool IsInside(double minX, double minY, double maxX, double maxY, double x, double y, bool isInsideDetectedX, bool isInsideDetectedY) 106 | { 107 | // Normalize because of widen function, world wrapping might have occured 108 | // calc in positive value range only, nb. lon -170 = 10, lat -80 = 10 109 | var nMinX = minX.NormalizeLongitude(); 110 | var nMaxX = maxX.NormalizeLongitude(); 111 | 112 | var nMinY = minY.NormalizeLatitude(); 113 | var nMaxY = maxY.NormalizeLatitude(); 114 | 115 | var nX = x.NormalizeLongitude(); 116 | var nY = y.NormalizeLatitude(); 117 | 118 | bool isX = isInsideDetectedX; // skip checking? 119 | bool isY = isInsideDetectedY; 120 | 121 | if (!isInsideDetectedY) 122 | { 123 | // world wrap y 124 | if (nMinY > nMaxY) 125 | { 126 | //sign depended check, todo merge equal lines 127 | // - - 128 | if (nMaxY <= 0 && nMinY <= 0) 129 | { 130 | isY = nMinY <= nY && nY <= LatLongInfo.MaxLatValue || LatLongInfo.MinLatValue <= nY && nY <= nMaxY; 131 | } 132 | // + + 133 | else if (nMaxY >= 0 && nMinY >= 0) 134 | { 135 | isY = nMinY <= nY && nY <= LatLongInfo.MaxLatValue || LatLongInfo.MinLatValue <= nY && nY <= nMaxY; 136 | } 137 | // + - 138 | else 139 | { 140 | isY = nMinY <= nY && nY <= LatLongInfo.MaxLatValue || LatLongInfo.MinLatValue <= nY && nY <= nMaxY; 141 | } 142 | } 143 | 144 | else 145 | { 146 | // normal, no world wrap 147 | isY = nMinY <= nY && nY <= nMaxY; 148 | } 149 | } 150 | 151 | if (!isInsideDetectedX) 152 | { 153 | // world wrap x 154 | if (nMinX > nMaxX) 155 | { 156 | //sign depended check, todo merge equal lines 157 | // - - 158 | if (nMaxX <= 0 && nMinX <= 0) 159 | { 160 | isX = nMinX <= nX && nX <= LatLongInfo.MaxLonValue || LatLongInfo.MinLonValue <= nX && nX <= nMaxX; 161 | } 162 | // + + 163 | else if (nMaxX >= 0 && nMinX >= 0) 164 | { 165 | isX = nMinX <= nX && nX <= LatLongInfo.MaxLonValue || LatLongInfo.MinLonValue <= nX && nX <= nMaxX; 166 | } 167 | // + - 168 | else 169 | { 170 | isX = nMinX <= nX && nX <= LatLongInfo.MaxLonValue || LatLongInfo.MinLonValue <= nX && nX <= nMaxX; 171 | } 172 | } 173 | else 174 | { 175 | // normal, no world wrap 176 | isX = nMinX <= nX && nX <= nMaxX; 177 | } 178 | } 179 | 180 | return isX && isY; 181 | } 182 | 183 | public static bool IsInside(Boundary b, MapPoint p) 184 | { 185 | return IsInside(b.MinX, b.MinY, b.MaxX, b.MaxY, p.X, p.Y, false, false); 186 | } 187 | 188 | // used by zoom level and deciding the grid size, O(halfSteps) 189 | // O(halfSteps) ~ O(maxzoom) ~ O(k) ~ O(1) 190 | // Google Maps doubles or halves the view for 1 step zoom level change 191 | public static double Half(double d, int halfSteps) 192 | { 193 | // http://en.wikipedia.org/wiki/Decimal_degrees 194 | const double meter11 = 0.0001; //decimal degrees 195 | 196 | double half = d; 197 | for (int i = 0; i < halfSteps; i++) 198 | { 199 | half /= 2; 200 | } 201 | 202 | var halfRounded = Math.Round(half, 4); 203 | // avoid grid span less than this level 204 | return halfRounded < meter11 ? meter11 : halfRounded; 205 | } 206 | 207 | // Value x which is in range [a,b] is mapped to a new value in range [c;d] 208 | public static double Map(double x, double a, double b, double c, double d) 209 | { 210 | var r = (x - a) / (b - a) * (d - c) + c; 211 | return r; 212 | } 213 | 214 | // Grid location are stationary, this gives first left or lower grid line from current latOrLon 215 | public static double FloorLatLon(double latOrlon, double delta) 216 | { 217 | var floor = ((int)(latOrlon / delta)) * delta; 218 | if (latOrlon < 0) floor -= delta; 219 | 220 | return floor; 221 | } 222 | 223 | // 224 | public static bool IsValidLat(double latitude) 225 | { 226 | return LatLongInfo.MinLatValue <= latitude && latitude <= LatLongInfo.MaxLatValue; 227 | } 228 | public static bool IsValidLong(double longitude) 229 | { 230 | return LatLongInfo.MinLonValue <= longitude && longitude <= LatLongInfo.MaxLonValue; 231 | } 232 | 233 | // Value must be within a and b 234 | public static double Constrain(double x, double a, double b) 235 | { 236 | var r = Math.Max(a, Math.Min(x, b)); 237 | return r; 238 | } 239 | 240 | // Value must be within latitude boundary 241 | public static double ConstrainLatitude(double x, double offset = 0) 242 | { 243 | var r = Math.Max(LatLongInfo.MinLatValue + offset, Math.Min(x, LatLongInfo.MaxLatValue - offset)); 244 | return r; 245 | } 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /GoogleMaps.Net.Clustering/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Tihomir Kit 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GoogleMaps.Net.Clustering 2 | C# library for clustering map points. This library is very suitable for WebAPI (and similar-type) projects that don't depend on ASP.Net MVC. 3 | 4 | 5 | ![Clustering Img](https://raw.githubusercontent.com/pootzko/GoogleMaps.Net.Clustering/master/cluster-map.png "clustering image") 6 | 7 | **Original Lib** 8 | This is a fork of [Google Maps Server-side Clustering with C# 9 | ](https://github.com/kunukn/Google-Maps-Clustering-CSharp) repo. The guys made a fast, working implementation of Google Maps clustering for C#. However, they tightly coupled it with MVC and WebForms where all I needed was a simple C# way to crunch a bunch of simple map points and convert them into cluster points. 10 | 11 | **Installation** 12 | You can download the [GoogleMaps.Net.Clustering](https://www.nuget.org/packages/GoogleMaps.Net.Clustering/) package to install the latest version of GoogleMaps.Net.Clustering Lib. 13 | 14 | Sponsored by [Dovetail Technologies](http://www.dovetail.ie/). 15 | 16 | ## Usage 17 | 18 | This is an example of how to used cached clustering. 19 | 20 | ```cs 21 | public IList GetClusters(YourFilterObj filter) 22 | { 23 | var clusterPointsCacheKey = "somecachekey"; 24 | var points = GetClusterPointCollection(clusterPointsCacheKey); 25 | 26 | var mapService = new ClusterService(points); 27 | var input = new GetMarkersParams() 28 | { 29 | NorthEastLatitude = filter.NorthEastLatitude, 30 | NorthEastLongitude = filter.NorthEastLongitude, 31 | SouthWestLatitude = filter.SouthWestLatitude, 32 | SouthWestLongitude = filter.SouthWestLongitude, 33 | ZoomLevel = filter.ZoomLevel, 34 | PointType = clusterPointsCacheKey 35 | }; 36 | 37 | var markers = mapService.GetClusterMarkers(input); 38 | 39 | return markers.Markers; 40 | } 41 | 42 | private PointCollection GetClusterPointCollection(string clusterPointsCacheKey) 43 | { 44 | var points = new PointCollection(); 45 | if (points.Exists(clusterPointsCacheKey)) 46 | return points; 47 | 48 | var dbPoints = GetPoints(); // Get your points here 49 | var mapPoints = dbPoints.Select(p => new MapPoint() { X = p.X, Y = p.Y }).ToList(); 50 | var cacheDuration = TimeSpan.FromHours(6); 51 | points.Set(mapPoints, cacheDuration, clusterPointsCacheKey); 52 | 53 | return points; 54 | } 55 | ``` 56 | 57 | You will also need to add the following section to your `.conf` file (add it before the `connectionString` and/or `appSettings` section). 58 | 59 | ```xml 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 | -------------------------------------------------------------------------------- /cluster-map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tihomir-kit/GoogleMaps.Net.Clustering/9ed96f748b792c584cd3691356dea553445288d6/cluster-map.png -------------------------------------------------------------------------------- /nuget-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tihomir-kit/GoogleMaps.Net.Clustering/9ed96f748b792c584cd3691356dea553445288d6/nuget-icon.png --------------------------------------------------------------------------------