Possibly take a look at the topojson project, which includes a simplification option for geometry.
If you wanted to do this yourself one algoritm would be as follows:
- Break each line into segments (pairs of points)
- Order these segments in a clockwise direction (sort vertices by x ascending, then y
descending)
- Calculate whether the segments are the same within some threshold
- If the segments are the same, determine how you will calculate the true value (average, priorities a over b etc).
- Replace updated segments in original shapes
Note this is a very simple algorithm - it doesn't take into account that you may wish to "snap" lines based on slope - to do that you'd have to calculate the line functions, compare them (the standard two-point function of a line is (x2 - x1)(y - y1) = (y2 - y1)(x - x1) for two points x1,y1 and x2,y2 - see Wikipedia for a more detailed explanation), and then decide on your rules for snapping them to the original line.
The author of the topojson projet, Mike Bostock, has also written a good article on line simplification which would certainly be worth a read.