Log in  ::  Register  ::  Not logged in

## Question about rounding the points in a Geometry.

 Author Message junkie-1029661 Grasshopper Group: General Forum Members Points: 24 Visits: 10 Here's a POLYGON from my MS SQL 2008 database that I pulled to use here as an example:POLYGON ((-64.8040519990027 18.366768000647426, -64.8011230006814 18.367451999336481, -64.797389999032021 18.369273999705911, -64.8034599982202 18.368359999731183, ...trunkated for readability... -64.703370001167059 18.301725000143051, -64.703745998442173 18.29857200011611, -64.7031709998846 18.298143999651074))Notice how many digits are involved in each x/y coordinate, this happens after I run STUnion() or STBuffer() on the polygon. Originally, each x/y coordinate was up to six decimal places before running one of these functions on it. And it is important that I use these two functions for my application. However, I'm dealing with a lot of polygons and the extra digits are creating way too much overhead in my app.My question: Does anyone know a way to round each x/y coordinate to the nearest, say, six decimal places? Where the first point, "-64.8040519990027 18.366768000647426" can be converted to "-64.804051 18.366768" and so on for the rest of the points. Or is there any way to truncate the points to the sixth digit (where it just cuts off the excess digits without rounding). I've been searching for a solution to this for days and haven't found anything yet. I figured posting on here would be a good shot.Any help in this area would be truly appreciated.Thanks junkie-1029661 Grasshopper Group: General Forum Members Points: 24 Visits: 10 P.S. - I'm sure I could convert the POLYGON to text (using STAsText), parse through each number to round each coordinate, and then convert it back to a geometry (using STPolyFromText) but I'm hoping there's a more efficient way to do it. zerko Ten Centuries Group: General Forum Members Points: 1266 Visits: 712 If I understand the Geometry construct correctly, (and I'm not claiming to be an expert here, this is just based on frustrating experiences) the latitude and longitude values are stored internally as 'float', and reducing the accuracy is not going to solve your 'overhead' problem. I think there is a different issue here that you may want to address, and that is the number of additional points introduced into a geography/geometry by using STBuffer() - as a quick example try running the following code:`DECLARE @g geometry;SET @g = geometry::STGeomFromText('POLYGON((0 2, 2 0, 4 2, 0 2))', 0);SELECT @g.STNumPoints() as PointCount, @g.STBuffer(0.00001).STNumPoints() as countAfterBuffer;`One solution to your 'overhead' could be to just rein in the number of points created by the .STBuffer() function by following it with .Reduce(n) (depending on your requirements for using STBuffer in the first place, you will need to play around with values of n to get a reasonable number of points without sacrificing accuracy of the geometry)`DECLARE @g geometry;SET @g = geometry::STGeomFromText('POLYGON((0 2, 2 0, 4 2, 0 2))', 0);SELECT @g.STNumPoints() as PointCount, @g.STBuffer(0.00001).STNumPoints() as countAfterBuffer,@g.STBuffer(0.00001).Reduce(0.01).STNumPoints() as countAfterReduce;`I suspect that reducing the number of points in your buffered geometries will give a better performance increase than rounding the accuracy of the points. See how it goes, if it is still necessary to truncate the points after trying this, then maybe I can help. I am currently working on 'dismantling' aggregated geometries to feed into HTML for google maps, and encountered a similar issue. I used the following code snippet to generate the HTML string to create the polygon, with accuracy of the points rounded to 6 decimal places by converting float to STR ... which is also the only way I could find to get a FLOAT value into a CHAR format.`DECLARE @g geometry;SET @g = geometry::STGeomFromText('POLYGON((0 2, 2 0, 4 2, 0 2))', 0);SELECT 'var L=google.maps.LatLng;' UNION ALL SELECT 'var polyg = [' UNION ALL SELECT 'new L(' + str(@g.STPointN(n).STY, 10,6)+',' + str(@g.STPointN(n).STX, 10,6) +'),' from dbo.Tally where N < @g.STNumPoints() UNION ALLSELECT 'new L(' + str(@g.STPointN(n).STY, 10,6)+',' + str(@g.STPointN(n).STX, 10,6) +')' from dbo.Tally where N = @g.STNumPoints() UNION ALLSELECT '];'`Note: the code snippet above uses a 'tally table' to walk through the points of the geometry, but it is only working for geometries with a single polygon - ie @g.STNumGeometries() = 1 ... if anyone could point me to a way of using tally tables to process nested loops I would be very grateful. I need to generate the above sequence for each polygon in @g.STGeometryN(x) (where x <= @g.STNumGeometries()) then add a couple of lines of code after each polygon to add it to the map. Thanks. dwain.c SSC-Forever Group: General Forum Members Points: 44627 Visits: 6431 zerko (1/17/2013)... if anyone could point me to a way of using tally tables to process nested loops I would be very grateful. I need to generate the above sequence for each polygon in @g.STGeometryN(x) (where x <= @g.STNumGeometries()) then add a couple of lines of code after each polygon to add it to the map. Thanks.Could you do something like:`FROM dbo.Tally aCROSS APPLY dbo.Tally b`And then use a.n for the inner loop and b.n as the outer loop of the nested loops? My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!My thought question: Have you ever been told that your query runs too fast?My advice:INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.Need to UNPIVOT? Why not CROSS APPLY VALUES instead?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables zerko Ten Centuries Group: General Forum Members Points: 1266 Visits: 712 Thanks Dwain, OK it's not pretty because of all the slicing and dicing of the geometries into sub-geometries, then points, then X's and Y's then assembling into a formatted string, then adding pre- and post - text strings, (which I've removed from the code here, but still not talking correctly to the google maps API) then adding sort orders so the text lines came out in the right sequence ...BUT ...for my first venture into the world of Cross Apply, it did work! `DECLARE @g geometry;--Create a multi-polygon geometrySET @g = geometry::STGeomFromText('POLYGON((0 2, 2 0, 4 2, 0 2))', 0)SELECT @g = @g.STUnion(geometry::STGeomFromText('POLYGON((3 3, 3 4, 4 4, 3 3))',0));IF @g.STNumGeometries() > 1 PRINT 'Multi-polygon detected'; SELECT c.LineText FROM dbo.tally a CROSS APPLY (SELECT 0 as N, 'var polyg = [' as LineText UNION ALL -- this line appears first, so sort order is zero SELECT b.N, 'new L(' + str(@g.STGeometryN(a.N).STPointN(b.N).STY, 10,6)+',' + str(@g.STGeometryN(a.N).STPointN(n).STX, 10,6) +'),' FROM dbo.Tally b where b.N < @g.STGeometryN(a.N).STNumPoints() UNION ALL SELECT b.N, 'new L(' + str(@g.STGeometryN(a.N).STPointN(b.N).STY, 10,6)+',' + str(@g.STGeometryN(a.N).STPointN(n).STX, 10,6) +')' FROM dbo.Tally b where b.N = @g.STGeometryN(a.N).STNumPoints() -- above select is for the last line of the list, no trailing comma -- following lines sort to appear after each geometry definition list UNION ALL Select @g.STGeometryN(a.N).STNumPoints() + 1, '];' UNION ALL Select @g.STGeometryN(a.N).STNumPoints() + 2, '//map cmds here//;' ) c WHERE a.N <= @g.STNumGeometries() --and a.N = 1order by a.N, c.N;`As an added bonus, it also works if I throw a single polygon geometry at it. dwain.c SSC-Forever Group: General Forum Members Points: 44627 Visits: 6431 Glad to hear my off-the-cuff idea worked!Thanks for the feedback as I don't believe I've actually tried it myself. :-) My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!My thought question: Have you ever been told that your query runs too fast?My advice:INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.Need to UNPIVOT? Why not CROSS APPLY VALUES instead?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables mickyT SSCertifiable Group: General Forum Members Points: 5824 Visits: 3320 Hi If you are working with Lat/Lon coordinates, you probably should use the Geography data type rather than the Geometry. Unfortunately these data types do use float to store the coordinates with the inherent issues that they have. Basically any method that returns a geometry will likely cause slight shifts to the points. The one that annoys me the most is MakeValid(). The good news is 2012 uses a higher precision float than 2008, but you still get the shift all be it smaller.Zerko, another thing you may want to consider when breaking apart your polygons is polygons with interior rings (donuts). I usually break the polygons into parts and then into rings.Here's an example`CREATE TABLE #rings (RegisterID int not null, PartNum int not null, RingNum int not null, Ring Geometry, NumPoints int);ALTER TABLE #rings ADD CONSTRAINT rings_pk PRIMARY KEY (RegisterId, PartNum, RingNum);;WITH e1(N) AS (SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ), e2(N) AS (SELECT 1 FROM E1 a, E1 b), --100-- e3(N) AS (SELECT 1 FROM E2 a, E2 b), --10000 cteTally(N) AS ( SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) N FROM e2 ),-- Get Individual polygons from Geometry GetPolygonParts AS ( SELECT RegisterID, RegisteredExtent.STGeometryN(t.N) Part, RegisteredExtent.STGeometryN(t.N).STNumPoints() NumPoints, t.N PartNum FROM Register a CROSS APPLY (select TOP(a.RegisteredExtent.STNumGeometries()) n from cteTally z ) t WHERE RegisteredExtent is not null ),-- Split to internal and external rings GetRings AS ( SELECT a.RegisterID, a.PartNum, 0 RingNum, Part.STExteriorRing() Ring, Part.STExteriorRing().STNumPoints() NumPoints FROM GetPolygonParts a UNION ALL SELECT a.RegisterID, a.PartNum, t.N RingNum, Part.STInteriorRingN(t.N) Ring, Part.STInteriorRingN(t.N).STNumPoints() NumPoints FROM GetPolygonParts a CROSS APPLY (select TOP(a.Part.STNumInteriorRing()) n from cteTally z ) t )INSERT INTO #rings SELECT * FROM GetRingsCREATE TABLE #coords (RegisterID int not null, PartNum int not null, RingNum int not null, X float not null, Y float not null)ALTER TABLE #coords ADD CONSTRAINT int_pk PRIMARY KEY (RegisterId, PartNum, RingNum, x, y);;WITH e1(N) AS (SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ), e2(N) AS (SELECT 1 FROM E1 a, E1 b), --100 e3(N) AS (SELECT 1 FROM E2 a, E2 b), --10000 cteTally(N) AS ( SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) N FROM e3 ), GetRingCoords AS ( SELECT RegisterID, p.PartNum, p.RingNum ,p.Ring.STPointN(t.N).STX X, p.Ring.STPointN(t.N).STY Y FROM #rings p CROSS APPLY (select TOP (p.NumPoints - 1) n from cteTally z) t )INSERT INTO #coords SELECT * FROM GetRingCoords `Putting them together into another format from that should be relatively easy. I found it worked better with the TOP clause in the cross apply.I use a double cast to put the coordinates into a varchar ... CAST(CAST(@x AS NUMERIC(10,6)) AS VARCHAR(11))-Micky

## Permissions

 You can't post new topics. You can't post topic replies. You can't post new polls. You can't post replies to polls. You can't edit your own topics. You can't delete your own topics. You can't edit other topics. You can't delete other topics. You can't edit your own posts. You can't edit other posts. You can't delete your own posts. You can't delete other posts. You can't post events. You can't edit your own events. You can't edit other events. You can't delete your own events. You can't delete other events. You can't send private messages. You can't send emails. You can read topics. You can't vote in polls. You can't upload attachments. You can download attachments. You can't post HTML code. You can't edit HTML code. You can't post IFCode. You can't post JavaScript. You can post emoticons. You can't post or upload images.

##### Select a forum
 SQL Server 2017      SQL Server 2017 - Administration      SQL Server 2017 - Development SQL Server 2016      SQL Server 2016 - Administration      SQL Server 2016 - Development and T-SQL SQL Server 2014      Administration - SQL Server 2014      Development - SQL Server 2014 SQL Server 2012      SQL 2012 - General      SQL Server 2012 - T-SQL SQL Server vNext      SQL Server 15 - Administration      SQL Server 15 - Development SQL Server 2008      SQL Server 2008 - General      T-SQL (SS2K8)      June 2007 CTP      Working with Oracle      July CTP      SQL Server Newbies      Security (SS2K8)      SQL Server 2008 High Availability      SQL Server 2008 Administration      Data Corruption (SS2K8 / SS2K8 R2)      SQL Server 2008 Performance Tuning Cloud Computing      SQL Azure - Development      SQL Azure - Administration      Amazon AWS and other cloud vendors      General Cloud Computing Questions      CosmosDB      Azure Data Lake      Azure Machine Learning Reporting Services      Reporting Services      Reporting Services 2005 Administration      Reporting Services 2005 Development      Reporting Services 2008/R2 Administration      Reporting Services 2008 Development      SSRS 2012      SSRS 2014      SSRS 2016 Programming      Connecting      General      SMO/RMO/DMO      XML      Service Broker      Powershell      Testing      TFS/Data Dude/DBPro      SSDT      Continuous Integration, Deployment, and Delivery      R Services and R Language Data Warehousing      Integration Services      Strategies and Ideas      Analysis Services      Data Transformation Services (DTS)      Performance Point      Data Mining      PowerPivot      R language      Machine Learning Database Design      Disaster Recovery      Design Ideas and Questions      Relational Theory      Hardware      Virtualization      Security and Auditing SQLServerCentral.com      Anything that is NOT about SQL!      Contests!      Editorials      SQLServerCentral.com Announcements      SQLServerCentral.com Website Issues      Suggestions      Tag Issues with Content      Podcast Feedback      SQLServerCentral.com Test Forum      Articles Requested SQL Server 2005      Administering      Backups      Business Intelligence      CLR Integration and Programming.      Data Corruption      Development      Working with Oracle      SQL Server 2005 Compact Edition      SQL Server 2005 General Discussion      SQL Server 2005 Security      SQL Server 2005 Strategies      SS2K5 Replication      SQL Server Express      SQL Server 2005 Performance Tuning      SQL Server 2005 Integration Services      T-SQL (SS2K5)      SQL Server Newbies SQL Server 7,2000      Administration      Backups      Data Corruption      General      Globalization      In The Enterprise      Working with Oracle      Security      Strategies      SQL Server Newbies      Service Packs      SQL Server CE      Performance Tuning      Replication      Sarbanes-Oxley      T-SQL      SQL Server Agent SQL Server and other platforms      MySQL      Oracle      PostgreSQL      DB2      SQL Server and Sharepoint Older Versions of SQL (v6.5, v6.0, v4.2)      Older Versions of SQL (v6.5, v6.0, v4.2) Career      Certification      Employers and Employees      Events      Job Postings      Resumes and Job Hunters      Presentations and Speaking      Retired Members Testing Center      SQL Server Security Skills      Question of the Day (QOD) Microsoft Access      Microsoft Access Products and Books      Third Party Products         SQLCentric         Extreme Technologies.         Innovartis         Embarcadero         SQL Sentry         Sonasoft         Golden Gate Software         Idera         Lumigent         Red Gate Software         ApexSQL         Quest Software         CA      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss T-SQL Books          Discuss Data Warehousing Books          Discuss DTS Books          Discuss SQL Server 2000 Books         Discuss SQL Server 7.0 Books Notification Services      Administration Article Discussions Future Versions      SQL 12

## Search

 Copyright © 2002-2018 Redgate. All Rights Reserved. Privacy Policy. Terms of Use. Report Abuse.