{"version":3,"sources":["jsdelivr-header.js","/npm/openstreetmap-mongo@0.0.1/lib/util/settings.js","/npm/openstreetmap-mongo@0.0.1/lib/geometry/bbox.js","/npm/openstreetmap-mongo@0.0.1/lib/geometry/geomath.js","/npm/openstreetmap-mongo@0.0.1/lib/geometry/way.js","/npm/openstreetmap-mongo@0.0.1/lib/geometry/node.js","/npm/openstreetmap-mongo@0.0.1/lib/geometry/relation.js","/npm/openstreetmap-mongo@0.0.1/lib/mongo/mongo-connect.js","/npm/openstreetmap-mongo@0.0.1/lib/util/logger.js","/npm/openstreetmap-mongo@0.0.1/lib/mongo/tmp-node-mongo.js","/npm/openstreetmap-mongo@0.0.1/lib/mongo/relation-mongo.js","/npm/openstreetmap-mongo@0.0.1/lib/mongo/way-mongo.js","/npm/openstreetmap-mongo@0.0.1/lib/mongo/node-mongo.js","/npm/openstreetmap-mongo@0.0.1/lib/parser/osm-parser.js","/npm/openstreetmap-mongo@0.0.1/lib/access/node-converter.js","/npm/openstreetmap-mongo@0.0.1/lib/access/way-converter.js","/npm/openstreetmap-mongo@0.0.1/lib/geometry/polygon-utils.js","/npm/openstreetmap-mongo@0.0.1/lib/access/relation-converter.js","/npm/openstreetmap-mongo@0.0.1/lib/access/osm-converter.js","/npm/openstreetmap-mongo@0.0.1/lib/access/osm-complete.js","/npm/openstreetmap-mongo@0.0.1/lib/mongo/tiles-mongo.js","/npm/openstreetmap-mongo@0.0.1/lib/parser/tile-registry.js","/npm/openstreetmap-mongo@0.0.1/lib/index.js","/npm/openstreetmap-mongo@0.0.1/index.js"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,qwnCCCI,GAAW,CACb,WAAc,YACd,WAAc,MACd,SAAY,MACZ,cAAiB,sBACjB,uBAA0B,iDAC1B,kBAAqB,WACrB,uBAA0B,IAC1B,qBAAwB,EACxB,yBAA4B,wDAC5B,qBAAuB,EACvB,iBAAoB,sHACpB,YAAe,CAAC,6CAChB,oBAAuB,wCACvB,eAAkB,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GAGjB,EAAA,SAAmB,GAA2B,cAG9B,EAAA,SAAG,GACN,EAAA,MAAG,GACE,EAAA,WAAG,GACJ,EAAA,UAAG,GACN,EAAA,OAAG,GAGjB,EAAA,kBAA4B,GAAuC,kBAGnE,EAAA,KAAe,GAA2B,KAC3B,EAAA,QAAG,GAClB,EAAA,UAAoB,GAA8B,UAC9B,EAAA,aAAG,GAGH,EAAA,aAAG,GAAkC,aCxCzD,IAAA,GAAiB,E","file":"/npm/openstreetmap-mongo@0.0.1/index.js/+esm","sourceRoot":"","sourcesContent":["/**\n * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0.\n * Original file: /npm/openstreetmap-mongo@0.0.1/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","/*\n* Load settings file for application.\n*\n* Stefan Wehner (2012)\n*/\n\n\nvar Settings = {\n  \"MONGO_HOST\": \"localhost\"\n, \"MONGO_PORT\": 27017\n, \"MONGO_DB\": \"osm\"\n, \"MONGO_DB_help\": \"mongo database name\"\n, \"LOGGER_COLLECTION_help\": \"log to this mongo collection instead of stdout\"\n, \"LOGGER_COLLECTION\": \"beet_log\"\n, \"LOGGER_COLLECTION_SIZE\": 1000000\n, \"LOGGER_CONSOLE_LEVEL\": 3\n, \"FOLLOW_MISSING_WAYS_help\": \"load ways outside the tile if referenced by relations\"\n, \"FOLLOW_MISSING_WAYS\": false\n, \"OSM_API_URL_help\": \"a list of openstreetmap XAPI servers (must include name, port, and path with last slash up to the parameter string)\"\n, \"OSM_API_URL\": [\"http://open.mapquestapi.com/xapi/api/0.6/\"]\n, \"OSM_COLLECTION_help\": \"store all osm data in this collection\"\n, \"OSM_COLLECTION\": \"osm\"\n, \"TILES_COLLECTION_help\": \"store here all downloaded tiles\"\n, \"TILES_COLLECTION\": \"tiles\"\n}\n\nexports.setSettings = function(settings) {\n    Settings = settings;\n}\n\nexports.getSettings = function() {\n    return Settings;\n}\n","/* Bounding box\n*\n* Stefan Wehner (2012)\n*/\n\nvar util = require(\"util\");\nvar assert = require(\"assert\");\n\nvar Settings = require('../util/settings').getSettings;\n\nexports.BBox = BBox;\n\nexports.TestInterface = {\n    injectGridSize: function(grid) {Grid = grid},\n}\n\n// gridsize\nvar Grid = Settings().GRID || 0.2;\n\nfunction BBox(obj) {\n    // Create bounding box for the nodes in the object.\n    // obj is a list of [lon,lat]\n\n    this.north = undefined;\n    this.south = undefined;\n    this.east = undefined;\n    this.west = undefined;\n    if (obj) {\n        if (obj[0][0]) {\n            this.includeNodes(obj);\n        } else {\n            this.includeNode(obj);\n        }\n    }\n}\n\nBBox.prototype.includeNodes = function(nodes) {\n    var bbox = this;\n    // nodes is a list of [lon,lat]\n    for (var i=0; i<nodes.length; i++) {\n        bbox.includeNode(nodes[i]);\n    }\n}\n\n// extend the bounding box to include the node\nBBox.prototype.includeNode = function(node) {\n    // node is a [lon,lat] pair\n\n    lon = node[0];\n    lat = node[1];\n    if (!this.south || lat < this.south) {\n        this.south = lat;\n    }\n    if (!this.north || lat > this.north) {\n        this.north = lat;\n    }\n    if (!this.west || lon < this.west) {\n        this.west = lon;\n    }\n    if (!this.east || lon > this.east) {\n        this.east = lon;\n    }\n}\n\nBBox.prototype.isDefined = function() {\n    return (this.north != undefined && this.south != undefined && this.east != undefined && this.west != undefined);\n}\n\n// return true if box is inside the bounding box\nBBox.prototype.isBoxInside = function(box) {\n    return 4 == this.cornersInside(box);\n}\n\n// return true if box overlaps with bounding box\nBBox.prototype.isBoxOverlap = function(box) {\n    return this.cornersInside(box) > 0;\n}\n\n// count how many corners of box are inside bounding box\nBBox.prototype.cornersInside = function(box) {\n    var inside = 0;\n    var bbox = this;\n    box.fourCorners().forEach(function(corner) {\n        if (bbox.isInside(corner)) {\n            inside++;\n        }\n    })\n    return inside;\n}\n\n\n// return true if node is inside the bounding box\nBBox.prototype.isInside = function(node) {\n    assert(this.isDefined());\n    lon = node[0];\n    lat = node[1];\n    return (lat <= this.north && lat >= this.south && lon >= this.west && lon <= this.east);\n}\n\n// returns all four corners bounding box\n// TODO: replace with parallelogram\nBBox.prototype.fourCorners = function() {\n    assert(this.isDefined());\n    return [[this.west,this.south],[this.west,this.north],[this.east,this.north],[this.east,this.south]];\n}\n\n// returns bounding box left,bottom,right,top\nBBox.prototype.bbox = function() {\n    assert(this.isDefined());\n    return [[this.west,this.south],[this.east,this.north]];\n}\n\nBBox.prototype.toString = function() {\n    return util.format(\"(W %f, S %f),(E %f, N %f)\",this.west,this.south,this.east,this.north);\n}\n\nBBox.prototype.hash = function() {\n    assert(this.isDefined());\n    return this.west+\"#\"+this.south+\"#\"+this.east+\"#\"+this.north;\n}\n// round down to the next grid point\nfunction roundUpToGrid(deg) {\n    return Math.ceil(deg/Grid)*Grid;\n}\n\n// round up to the next grid point\nfunction roundDownToGrid(deg) {\n    return Math.floor(deg/Grid)*Grid;\n}\n\n// inflate bounding box to fit to the next grid line\n// (round up/down to the next third decimal)\n// return bbox\nBBox.prototype.inflateToNextGridLine = function() {\n    assert(this.isDefined());\n    this.west = roundDownToGrid(this.west);\n    this.south = roundDownToGrid(this.south);\n    this.north = roundUpToGrid(this.north);\n    this.east = roundUpToGrid(this.east);\n\n    return this;\n}\n\n// Divide BBox object into a micro degree raster of bboxes and call callback\n// function with those bbox tiles one by one untile the parent BBox is covered.\nBBox.prototype.forEachGridBBox = function(callback) {\n    // instantiate copy\n    var bbox = new BBox(this.bbox()).inflateToNextGridLine();\n    if (bbox.west == bbox.east && bbox.south == bbox.north) {\n        // single point box shall retrieve one grid box\n        bbox.east = bbox.west + Grid/2;\n        bbox.north = bbox.south + Grid/2;\n    }\n    for (var x=bbox.west; bbox.east-x > 1e-6; x += Grid) {\n        for (var y=bbox.south; bbox.north-y > 1e-6; y += Grid) {\n            callback(new BBox([[x,y],[x+Grid,y+Grid]]));\n        }\n    }\n}\n\n","/*\n* Some useful functions for geometrical calculations\n*\n* Stefan Wehner (2012)\n*/\nvar Line = require('sylvester').Line;\nvar assert = require('assert');\n\nvar R = 6371000; // earth radius meters\nvar deg2rad = Math.PI / 180;\nvar deg2meter = Math.PI*R/180;\n\nexports.TestInterface = {\n    dropTheMiddleman: dropTheMiddleman,\n    processForwardInTriplets: processForwardInTriplets,\n    processBackwardInTriplets: processBackwardInTriplets\n}\n\n\n// Return spherical distance between points on earth surface in meters\n// p1 and p2 given as array [lon,lat]\nfunction pointDistance(p1, p2) {\n    var lon1 = p1[0] * deg2rad;\n    var lon2 = p2[0] * deg2rad;\n    var lat1 = p1[1] * deg2rad;\n    var lat2 = p2[1] * deg2rad;\n\n    a =  Math.sin(lat1)*Math.sin(lat2) +\n                  Math.cos(lat1)*Math.cos(lat2) *\n                  Math.cos(lon2-lon1);\n    // due to rounding errors a may exceed the legal argument range for acos\n    if (a < -1.0) {\n        a = -1.0;\n    }\n    if (a > 1.0) {\n        a = 1.0;\n    }\n    return Math.acos(a) * R;\n}\n\nexports.pointDistance = pointDistance;\n\n\nexports.wayLength = function(coords) {\n    var len = 0;\n    coords.forEach(function(c, i, ca) {\n        if (i > 0) {\n            len += pointDistance(c,ca[i-1]);\n        }\n    })\n    return len;\n}\n\n\n// Eliminate points from a way unnecessary at a coarse precision\nfunction scarceWay(coords, deviation) {\n    // one node minimum\n    assert(coords.length);\n    if (coords.length < 2) {\n        return coords;\n    }\n\n    // 2-node way\n    if (coords.length == 2) {\n        if (pointDistance(coords[0],coords[1]) <= deviation) {\n            // for a 2-point way with minimal length, shrink to a single point\n            return [[(coords[0][0]+coords[1][0])*0.5, (coords[0][1]+coords[1][1])*0.5]];\n        } else {\n            return coords;\n        }\n    }\n\n    // 3-plus-node-way\n    var scarce = processForwardInTriplets(coords, deviation, dropTheMiddleman);\n    scarce = processBackwardInTriplets(coords, deviation, dropTheMiddleman);\n\n    // call recursively as long as the scarcity can be improved\n    if (scarce.length < coords.length) {\n        return scarceWay(scarce, deviation);\n    }\n\n    return scarce;\n}\n\nexports.scarceWay = scarceWay;\n\nfunction dropTheMiddleman(p0,p1,p2,deviation) {\n    var tf = new Transform(p0);\n    var line = Line.create([0,0],tf.getXY(p2));\n    var middleman_deviation;\n    if (line == null) {\n        // happens when p2 == p0\n        middleman_deviation = pointDistance(p0, p1);\n    } else {\n        middleman_deviation = line.distanceFrom(tf.getXY(p1))\n    }\n    // if the middle node is off by less than deviation from the\n    // direct line between node[0] and node[2] it can be eliminated.\n    // Do not eliminate if the distance between nodes becomes too big.\n    if (middleman_deviation >= deviation\n        || pointDistance(p0, p2) > (7 * deviation) )\n    {\n        // keep middle point\n        return [p0,p1,p2];\n    }\n    return [p0,p2];\n}\n\nfunction processForwardInTriplets(coords, deviation, processor) {\n    var scarce = [coords[0]];\n    var i;\n    for (i=2; i < coords.length; i+=2) {\n        var reminder = processor(coords[i-2], coords[i-1], coords[i], deviation);\n        reminder.slice(1).forEach(function(c) {\n            scarce.push(c);\n        });\n    }\n    if (i == coords.length) {\n        // last point was skipped\n        scarce.push(coords[coords.length-1]);\n    }\n    return scarce;\n}\n\nfunction processBackwardInTriplets(coords, deviation, processor) {\n    var scarce = [coords[coords.length-1]];\n    var i;\n    for (i=coords.length-3; i >= 0; i-=2) {\n        var reminder = processor(coords[i], coords[i+1], coords[i+2], deviation);\n        if (reminder.length == 3) {\n            scarce.unshift(reminder[1]);\n        };\n        scarce.unshift(reminder[0]);\n    }\n    if (i == -1) {\n        // last point was skipped\n        scarce.unshift(coords[0]);\n    }\n    return scarce;\n}\n\n\n// Initialize transformation routines with a base point [lon,lat]\nTransform = function(p0) {\n    this.lon = p0[0];\n    this.lat = p0[1];\n}\n\n// return XY coordinats of point p1 with respect to the class base point p0\nTransform.prototype.getXY = function(p1) {\n    var x = (p1[0] - this.lon) * deg2meter;\n    var y = (p1[1] - this.lat) * deg2meter * Math.log(Math.tan(0.25*Math.PI + 0.5*this.lat*deg2rad));\n\n    return [x,y];\n}\n\n// return lat,lon coordinates of a point in the local merkator tangential plane\nTransform.prototype.getLatLon = function(xy) {\n    var lon = this.lon + xy[0] / deg2meter;\n    var lat = this.lat + xy[1] / deg2meter / Math.log(Math.tan(0.25*Math.PI + 0.5*this.lat*deg2rad));\n\n    return [lon,lat];\n}\n\nexports.Transform = Transform;\n\n\n\n\n","/* OSM way object\n*\n* Stefan Wehner (2012)\n*/\n\nvar assert = require(\"assert\");\nvar BBox = require(\"./bbox\").BBox;\nvar geomath = require(\"./geomath\");\n\nexports.Way = Way;\n\nfunction Way(osm_id, version, visible) {\n    this.visible = visible;\n    this.nodes = undefined;\n    this.osm_id = osm_id;\n    this.version = version;\n    this.attrs = undefined;\n    this.coordinates = undefined;\n    this.bbox = undefined;\n}\n\nWay.prototype.isPolygon = function() {\n    if (this.nodes && this.nodes.length > 0) {\n        // we have node id's - easy\n        return this.nodes[0] == this.nodes[this.nodes.length-1];\n    } else {\n        // compare coordinates\n        return (Math.abs(this.coordinates[0][0] - this.coordinates[this.coordinates.length-1][0]) < 1e-6\n                && Math.abs(this.coordinates[0][1] - this.coordinates[this.coordinates.length-1][1]) < 1e-6)\n    }\n}\n\nWay.prototype.addNodeId = function(id) {\n    if (!this.nodes) {\n        this.nodes = [];\n    }\n    this.nodes.push(id);\n}\n\nWay.prototype.setCoordinates = function(coord) {\n    if (this.nodes && coord.length != this.nodes.length) {\n        throw new Error(\"Length of coordinate array does not correspond to nodes array: \"+coord.length+\" != \"+this.nodes.length);\n    }\n    this.coordinates = coord;\n    this.bbox = new BBox(coord);\n}\n\nWay.prototype.addTags = function(tags) {\n    if (!this.attrs) {\n        this.attrs = {};\n    }\n    for (key in tags) {\n        if (tags.hasOwnProperty(key)) {\n            this.attrs[key] = tags[key];\n        }\n    }\n}\n\n// store reference to relations which use this way\n// rel_memberships is a list of objects with id and role attributes.\nWay.prototype.setRel = function(rel_memberships) {\n    this.rel = rel_memberships;\n}\n\n// calculate the length of the way in meters\nWay.prototype.getLengthMeters = function() {\n    assert(this.coordinates != undefined);\n    assert(this.coordinates.length > 1);\n\n    return geomath.wayLength(this.coordinates);\n}\n\n// return a simplified way which omits most points\nWay.prototype.getScarceWay = function() {\n    assert(this.coordinates != undefined);\n\n    if (this.sketch == undefined) {\n        this.sketch = geomath.scarceWay(this.coordinates, 300);\n    }\n\n    return this.sketch;\n}\n\n\n\n","/* Node object\n*\n* Stefan Wehner (2012)\n*/\n\nexports.Node = Node;\n\nfunction Node(osm_id,lat,lon,version,visible) {\n    this.visible = visible;\n    this.lat = lat;\n    this.lon = lon;\n    this.osm_id = osm_id;\n    this.version = version;\n    this.attrs = undefined;\n    this.rel = undefined;\n}\n\n// store reference to relations which use this node\n// rel_memberships is a list of objects with id and role attributes.\nNode.prototype.setRel = function(rel_memberships) {\n    this.rel = rel_memberships;\n}\n\nNode.prototype.setTags = function(tags) {\n    this.attrs = tags;\n}\n\nNode.prototype.getLoc = function() {\n    return [this.lon,this.lat];\n}\n","/* OSM relation object\n*\n* Stefan Wehner (2012)\n*/\n\nexports.Relation = Relation;\n\nfunction Relation(osm_id,version,visible) {\n    this.visible = visible;\n    this.nodes = {};  // list of nodes by role\n    this.ways = {};   // list of ways by role\n    this.osm_id = osm_id;\n    this.version = version;\n    this.attrs = undefined;\n}\n\n\nRelation.prototype.addTags = function(tags) {\n    if (!this.attrs) {\n        this.attrs = {};\n    }\n    for (key in tags) {\n        if (tags.hasOwnProperty(key)) {\n            this.attrs[key] = tags[key];\n        }\n    }\n}\n\n\nRelation.prototype.addNodeMember = function(role, node) {\n    if (!this.nodes[role]) {\n        this.nodes[role] = [];\n    }\n    this.nodes[role].push(node);\n}\n\n// coordinates parameter is only used when relation object is read from DB.\n// coordinates is undefined when this function is called during xml parsing\nRelation.prototype.addWayMember = function(role, way) {\n    // An empty role: '' is treated as role: 'outer'\n    role = (role == '') ? 'outer' : role;\n    if (!this.ways[role]) {\n        this.ways[role] = [];\n    }\n    this.ways[role].push(way);\n}\n\n","/**\n* Handle mongo db operations\n*\n* Stefan Wehner 2012\n*/\n\nvar Mongojs = require('mongodb');\nvar assert = require('assert');\n\nvar Settings = require('../util/settings').getSettings();\n\n// DB connection\nvar DB = undefined;\n\n// keep a pool of collections\nvar availableCollections = {};\n\n// Connect to database and the predefind collections (in collections Array)\nexports.connect = function(host, port, callback) {\n    var outstanding_collections = 0;\n\n    function waitForCollections() {\n        if (outstanding_collections == 0) {\n            callback();\n        } else {\n            setTimeout(waitForCollections,30);\n        }\n    }\n\n    db = new Mongojs.Db('osm', new Mongojs.Server(host, port, {auto_reconnect: true}, {}));\n    db.open(function(error, db) {\n        if (error) {\n            throw new Error(\"Can't connect to MongoDB. Is mongod running?\\n\"+error);\n        }\n        DB = db;\n        console.log(\"Opened MongoDb on \"+host+\":\"+port);\n        if (Settings.LOGGER_COLLECTION) {\n            outstanding_collections++;\n            db.collectionNames(Settings.LOGGER_COLLECTION, function(err, items) {\n                assert.equal(null, err);\n                if (items.length == 0) {\n                    // create capped collection\n                    db.createCollection(Settings.LOGGER_COLLECTION, {capped: true, size: Settings.LOGGER_COLLECTION_SIZE, safe:true}, function(err, collection) {\n                        assert.equal(null, err);\n                        availableCollections[Settings.LOGGER_COLLECTION] = collection;\n                        outstanding_collections--;\n                    })\n                } else {\n                    db.collection(Settings.LOGGER_COLLECTION, function(error, collection) {\n                        assert.equal(null,error);\n                        availableCollections[Settings.LOGGER_COLLECTION] = collection;\n                        outstanding_collections--;\n                    })\n                }\n            })\n        }\n        if (Settings.OSM_COLLECTION) {\n            outstanding_collections++;\n            db.collection(Settings.OSM_COLLECTION, function(error, collection) {\n                assert.equal(null,error);\n                availableCollections[Settings.OSM_COLLECTION] = collection;\n                collection.ensureIndex({'loc': \"2d\"});\n                collection.ensureIndex({'_id.osm': 1});\n                collection.ensureIndex({'rel.id': 1});\n                // indexes for the most common osm keys\n                collection.ensureIndex({'tags.name': 1});\n                collection.ensureIndex({'tags.highway': 1});\n                collection.ensureIndex({'tags.ref': 1});\n                collection.ensureIndex({'tags.waterway': 1});\n                collection.ensureIndex({'tags.railway': 1});\n                collection.ensureIndex({'tags.amenity': 1});\n                collection.ensureIndex({'tags.leisure': 1});\n                collection.ensureIndex({'tags.tourism': 1});\n                collection.ensureIndex({'tags.service': 1});\n                collection.ensureIndex({'tags.natural': 1});\n                collection.ensureIndex({'tags.landuse': 1});\n                outstanding_collections--;\n            })\n        }\n        if (Settings.TILES_COLLECTION) {\n            outstanding_collections++;\n            db.collection(Settings.TILES_COLLECTION, function(error, collection) {\n                assert.equal(null,error);\n                availableCollections[Settings.TILES_COLLECTION] = collection;\n                collection.ensureIndex({'_id.loc': \"2d\", 'data_timestamp': -1});\n                outstanding_collections--;\n            })\n        }\n        // temporary collection for nodes\n        outstanding_collections++;\n        var node_tmp_collection = Settings.NODE_TMP_COLLECTION || 'tmp_nodes';\n        db.collection(node_tmp_collection, function(error, collection) {\n            assert.equal(null,error);\n            availableCollections[node_tmp_collection] = collection;\n            outstanding_collections--;\n        })\n        process.nextTick(waitForCollections);\n    });\n}\n\nexports.getCollection = function(coll) {\n    if (!DB) {\n        throw new Error(\"No database connection.\");\n    }\n    if (!availableCollections[coll]) {\n        throw new Error(\"Unknown collection \"+coll+\" Use: \"+function(){var res=\"\"; for (coll in availableCollections) res+=coll+\", \"; return res}());\n    }\n    return availableCollections[coll];\n}\n\n","/*\n* Write logs with timestamp to mongo or console\n*\n* Stefan Wehner (2012)\n*/\n\nvar util = require('util');\nvar Settings = require('../util/settings').getSettings;\nvar MongoOsm = require('../mongo/mongo-connect');\n\nvar last_timestamp = undefined;\nvar beyond_timstamp = 0;\nvar collection = undefined;\n\nexports.TestInterface = {\n    injectMongoOsm: function(mongo) {MongoOsm = mongo},\n    overrideLogToStderr: function(toStderr) {logToStderr = toStderr},\n    toMessageObject: toMessageObject,\n    getId: getId\n}\n\n\nfunction getId(level) {\n    var t = new Date();\n\n    if (t == last_timestamp) {\n        // gives some extra precision if time has not changed\n        beyond_timestamp++;\n    } else {\n        last_timestamp = t;\n        beyond_timestamp = 0;\n    }\n    return {'t': t, 'b': beyond_timestamp, 'level': level};\n}\n\nfunction toMessageObject(level, msg, obj) {\n    // timestamp is id\n    var out = {'_id': getId(level)};\n    out.message = msg;\n    if (obj) {\n        for (o in obj) {\n            if (obj.hasOwnProperty(o)) {\n                if (typeof obj[o] == 'object' && obj[o] != null) {\n                    out[o] = obj[o].toString();\n                } else {\n                    out[o] = obj[o]\n                }\n            }\n        }\n    }\n    return out;\n}\n\nvar Level = ['TRACE', 'DEBUG', 'INFO', 'WARNING', 'ERROR'];\n\nlogToStderr = function(level, msg, obj) {\n    if (obj) {\n        console.warn(\"%s %s %s %s\", new Date(), Level[level], msg, util.inspect(obj, false, 2, true));\n    } else {\n        console.warn(\"%s %s %s\", new Date(), Level[level], msg);\n    }\n}\n\nvar LogBuffer = [];\n\n// log to mongo collection (if defined)\n// log to stderr (if level > configured level)\nfunction write(level, msg, obj) {\n    if (Settings().LOGGER_COLLECTION) {\n        // buffer logs in case that DB is not yet open\n        LogBuffer.push(toMessageObject(level, msg, obj));\n        try {\n            var collection = MongoOsm.getCollection(Settings().LOGGER_COLLECTION);\n            collection.insert(LogBuffer, {safe: false});\n            LogBuffer = [];\n        } catch (e) {}\n    }\n    var user_level = Settings().LOGGER_CONSOLE_LEVEL == undefined ? 3 : Settings().LOGGER_CONSOLE_LEVEL;\n    if (level >= user_level) {\n        logToStderr(level, msg, obj);\n    }\n}\n\n// log levels take a string or an object\nexports.trace = function(msg, obj) {\n    write(0, msg, obj);\n}\n\nexports.debug = function(msg, obj) {\n    write(1, msg, obj);\n}\n\nexports.info = function(msg, obj) {\n    write(2, msg, obj);\n}\n\nexports.warning = function(msg, obj) {\n    write(3, msg, obj);\n}\n\nexports.error = function(msg, obj) {\n    write(4, msg, obj);\n}\n\n","/*\n* Store nodes temporarily in mongo\n*\n* Stefan Wehner (2012)\n*/\n\nvar DB = require(\"../mongo/mongo-connect\");\nvar Settings = require('../util/settings').getSettings;\n\nvar Node = require(\"../geometry/node\").Node;\n\nvar NODE_TMP_COLLECTION = Settings().NODE_TMP_COLLECTION || 'tmp_nodes';\n\nexports.add = function(node) {\n    var nodedata = {_id: node.osm_id, loc: [node.lon,node.lat]};\n    DB.getCollection(NODE_TMP_COLLECTION).insert(nodedata);\n}\n\nexports.TestInterface = {\n    injectDB: function(mock) {DB = mock}\n}\n\n// node_ids is a list of node id's. Returns an array with the lon,lat pairs\nexports.getLocations = function(node_ids, callback) {\n    var loc = [];\n    getNodes(node_ids, function(error,nodes) {\n        if (!error) {\n            var missing = [];\n            node_ids.forEach(function(id) {\n                if (!nodes[id]) {\n                    missing.push(id);\n                }\n                loc.push(nodes[id]);\n            })\n            if (missing.length) {\n                error = missing.join();\n            }\n        }\n        callback(error,loc);\n    })\n}\n\nexports.getNodes = getNodes;\n\nfunction getNodes(node_ids, callback) {\n    var query = {_id: {$in: node_ids}};\n    DB.getCollection(NODE_TMP_COLLECTION).find(query, function(error, result) {\n        result.toArray(function(err,nodes) {\n            // convert to dictionary\n            nodes_dic = {};\n            nodes.forEach(function(nd) {\n                nodes_dic[nd._id] = nd.loc;\n            })\n            callback(err,nodes_dic);\n        })\n    });\n}\n\nexports.getNode = getNode;\n\nfunction getNode(node_id, callback) {\n    var query = {_id: node_id};\n    DB.getCollection(NODE_TMP_COLLECTION).findOne(query, function(error, node) {\n        callback(error, node);\n    });\n}\n\nexports.drop = function() {\n    DB.getCollection(NODE_TMP_COLLECTION).drop();\n}\n\n","/*\n* Store relations in MongoDb\n*\n* Stefan Wehner (2012)\n*/\n\nvar Mongojs = require('mongodb');\nvar assert = require('assert');\n\nvar DB = require(\"../mongo/mongo-connect\");\n\nvar Way = require(\"../geometry/way\").Way;\nvar Relation = require(\"../geometry/relation\").Relation;\nvar NodeTmpDB = require(\"../mongo/tmp-node-mongo\");\n\nexports.TestInterface = {\n    injectTmpNodesDB: function(mock) {NodeTmpDB = mock;},\n    injectDB: function(mock) {DB = mock}\n}\n\nexports.storeRelation = function(relation, decrDBQueue, missingWay) {\n    var dots = [];\n    var outstanding_nodes = 0;\n    // loop over all nodes for all roles\n    for (role in relation.nodes) {\n        if (relation.nodes.hasOwnProperty(role)) {\n            relation.nodes[role].forEach(function(node) {\n                outstanding_nodes++;\n                NodeTmpDB.getNode(Mongojs.Long(node.osm_id), function(error, nd) {\n                    if (error) {\n                        throw new Error(\"Error reading node: \"+node.osm_id+\" \"+error);\n                    }\n                    if (!nd) {\n                        // as below for ways, we may consider calling a missingNode callback here\n                        outstanding_nodes--;\n                    } else {\n                        dots.push(nd.loc);\n                        var q_node = {'_id': {osm: Mongojs.Long(nd._id)}};\n                        var nodedata = {\n                            $set: {type: 'n', loc: nd.loc},\n                            $addToSet: {rel: {id: Mongojs.Long(relation.osm_id), r: role}}\n                        }\n                        DB.getCollection('osm').findAndModify(q_node, [], nodedata, {safe: true, upsert: true}, function(error,result) {\n                            if (error) {\n                                throw new Error(\"Could not update node: \"+node.osm_id+\" \"+error);\n                            }\n                            outstanding_nodes--;\n                        })\n                    }\n                })\n            })\n        }\n    }\n\n    // update reference to relation in ways already stored in database\n    var outstanding_ways = 0;\n    // loop over all ways for all roles\n    for (role in relation.ways) {\n        if (relation.ways.hasOwnProperty(role)) {\n            relation.ways[role].forEach(function(way) {\n                outstanding_ways++;\n                var q_way = {_id: {osm: Mongojs.Long(way.osm_id), seg: 0}};\n                var data = {$addToSet: {rel: {id: Mongojs.Long(relation.osm_id), r: role}}};\n                DB.getCollection('osm').findAndModify(q_way, [], data, {safe: true}, function(error,result) {\n                    if (error) {\n                        throw new Error(\"Could not update way: \"+way.osm_id+\" \"+error);\n                    }\n                    if (result && result.loc) {\n                        dots = dots.concat(result.loc);\n                        outstanding_ways--;\n                    } else {\n                        // not all relation members may be included in the input file\n                        // store segment-0 dataset to have the reference to the relation but give it\n                        // version -1 so that it will be updated as soon as the way data is loaded\n                        data[\"$set\"] = {v: -1, type: 'w'};\n                        DB.getCollection('osm').findAndModify(q_way, [], data, {safe: true, upsert: true}, function(error,result) {\n                            assert.equal(null,error);\n                            outstanding_ways--;\n                        })\n                        missingWay(way.osm_id);\n                    }\n                })\n            })\n        }\n    }\n\n    function storeRelationWithDotsCB() {\n        if (outstanding_ways || outstanding_nodes) {\n            // still waiting for the bbox to be completed\n            setTimeout(storeRelationWithDotsCB,30);\n            return;\n        }\n        // store relation itself with location dots for all members\n        var q_rel = {_id: {osm: Mongojs.Long(relation.osm_id)}};\n        var reldata = {$set: {v: relation.version, type: 'r'\n                      , tags: relation.attrs}\n                  }\n        // relations without any downloaded data don't have a bbox\n        reldata[\"$set\"][\"loc\"] = dots;\n        DB.getCollection('osm').update(q_rel, reldata, {upsert: true, safe: true}, function(error) {\n            if (error) {\n                throw new Error(\"Could not update/insert relation: \"+relation.osm_id+\" \"+error);\n            }\n            decrDBQueue();\n        });\n    }\n\n    // wait for all ways belonging to the relation to be updated and have returned their location\n    setTimeout(storeRelationWithDotsCB,30);\n}\n\n\n","/*\n* Store ways in MongoDb\n*\n* Stefan Wehner (2012)\n*/\nvar assert = require(\"assert\");\n\nvar DB = require(\"../mongo/mongo-connect\");\nvar Nodes = require(\"../mongo/tmp-node-mongo\");\nvar logger = require(\"../util/logger\");\n\nvar Way = require(\"../geometry/way\").Way;\n\nexports.TestInterface = {\n    injectDB: function(mock) {DB = mock},\n    injectNodes: function(mock) {Nodes = mock}\n}\n\n// Store way in MongoDb. Each way is stored as at least two documents\n// 1: The way-metadata, like version, tags, type. Indexed by {_id.osm: way.osm_id}\n// 2..n: One or more way segments, depending on the length of the way.\n//       Segments contain the nodes [[lon,lat],..]\n//       Indexed by {_id: {osm: osm_id, seg: sementCounter}}\nexports.storeWay = function(way, decrDBQueue, elementCB) {\n    Nodes.getLocations(way.nodes, function(error, loc) {\n        if (error != null) {\n            logger.warning(\"Could not get (all) nodes for way: \"+way.osm_id, error);\n            decrDBQueue();\n            return;\n        }\n        way.setCoordinates(loc);\n        elementCB({elementBBox: way.bbox});\n\n        // findAndModify (or insert) reference element\n        var waydata = {\"$set\": {\n                                  loc: way.getScarceWay()\n                                , v: way.version\n                                , type: way.isPolygon() ? 'p' : 'w'\n                                , tags: way.attrs\n                                }\n                      };\n        DB.getCollection('osm').findAndModify({_id: {osm: way.osm_id, seg: 0}}\n                            , [], waydata\n                            , {upsert: true, safe: true}\n                            , function(error,found) {\n            if (error) {\n                throw new Error(\"Failed to update/insert way \"+way.osm_id+\" \"+error);\n            }\n            if (!found._id || found.v < way.version) {\n                var segments = exports.waySegments(way, 60);\n                if (found._id) {\n                    // way needs update. remove existing segments in DB\n                    DB.getCollection('osm').remove({\"_id.osm\": way.osm_id, \"_id.seg\": {$gt: 0}}, {safe: true}, function(error) {\n                        if (error) {\n                            throw new Error(\"Could not remove existing segments for way: \"+way.osm_id+\" \"+error);\n                        }\n                        wayInsert(segments,decrDBQueue);\n                    });\n                } else {\n                    // way is entirely new\n                    wayInsert(segments,decrDBQueue);\n                }\n            } else {\n                // way doesn't need update\n                decrDBQueue();\n            }\n        });\n    });\n\n}\n\n// helper function for inserting a way\nfunction wayInsert(waydata, decrDBQueue) {\n    DB.getCollection('osm').insert(waydata, {safe: true}, function(error) {\n        if (error) {\n            throw new Error(\"Could not insert segments for way: \"+waydata[0][\"_id\"][\"osm\"]+\" \"+error);\n        }\n        decrDBQueue();\n    });\n}\n\n\n// Split way to segments with max. segment_size nodes per segment\n// return an array of way segments ready to instert to mongo DB\nexports.waySegments = function(way, segment_size) {\n    assert(way.coordinates, \"Set coordinates first.\")\n\n    ln = way.coordinates.length;\n    // split into almost equally sized segments\n    var sn = Math.ceil(ln / Math.ceil(ln / segment_size));\n    var res = [];\n    for (var i=0; i<ln; i+=sn) {\n        // segment counting starts at 1 (seg 0 is the way metadata)\n        mongoway = {_id: {osm: way.osm_id, seg: i+1}, nd: way.coordinates.slice(i,i+sn)};\n        res.push(mongoway);\n    }\n    return res;\n}\n\n\n\n\n","/*\n* Store nodes in MongoDb\n*\n* Stefan Wehner (2012)\n*/\n\nvar Mongojs = require('mongodb');\n\nvar DB = require(\"../mongo/mongo-connect\");\n\nvar BBox = require(\"../geometry/bbox\").BBox;\nvar Way = require(\"../geometry/way\").Way;\nvar Node = require(\"../geometry/node\").Node;\n\nexports.storeNode = function(node, decrDBQueue) {\n    var nodedata = {$set: {v: node.version, type: 'n', tags: node.attrs, loc: [node.lon,node.lat]}};\n    if (node.rel) {\n        nodedata[\"$addToSet\"] = {rel: {$each: node.rel}};\n    }\n    var q_node = {\"_id\": {\"osm\": node.osm_id}};\n    DB.getCollection('osm').update(q_node, nodedata, {upsert: true, safe: true}, function(error,data) {\n        if (error) {\n            throw new Error(\"Could not update/insert node: \"+node.osm_id+\" \"+error);\n        }\n        decrDBQueue();\n    })\n}\n\n\n","/*\n* Parse Osm (XML) file\n*\n* Stefan Wehner (2012)\n*/\n\n\nvar util = require(\"util\");\nvar assert = require(\"assert\");\n\nvar sax = require(\"sax\");\nvar Mongojs = require('mongodb');\n\nvar BBox = require(\"../geometry/bbox\").BBox;\nvar Node = require(\"../geometry/node\").Node;\nvar Way = require(\"../geometry/way\").Way;\nvar logger = require(\"../util/logger\");\nvar RelationDB = require(\"../mongo/relation-mongo\");\nvar WayDB = require(\"../mongo/way-mongo\");\nvar NodeDB = require(\"../mongo/node-mongo\");\nvar NodeTmpDB = require(\"../mongo/tmp-node-mongo\");\n\nvar Relation = require(\"../geometry/relation\").Relation;\n\nexports.TestInterface = {\n    bboxFromXAPIBound: bboxFromXAPIBound,\n    injectWayDB: function(mock) {WayDB = mock},\n    injectNodeDB: function(mock) {NodeDB = mock},\n    injectNodeTmpDB: function(mock) {NodeTmpDB = mock},\n    injectRelationDB: function(mock) {RelationDB = mock},\n}\n\n\nexports.OsmParser = OsmParser;\n\n/**\n* Parse openstreetmap xml data stream and store nodes, ways and relations in database\n* stream      - incoming data stream\n* url         - url or filename (to keep track of previously parsed data)\n* missing     - called if node or way is referenced in data but wasn't present in the data\n*              stream.\n* element     - is called with a data bounding box and timestamp and bbox information\n*               for all elements processed.\n* heartbeat   - (optional) callback function is invoked every second by the parser to\n*              deliver status information\n* callback    - invoked when parsing has finished\n*/\nfunction OsmParser(stream, url, missing, registryCb, heartbeat, callback) {\n    logger.trace(\"OsmParser\", arguments);\n    // heartbeat is optional, callback is required\n    if (!callback) {\n        callback = heartbeat;\n        heartbeat = undefined;\n    }\n\n    var _osm_parser = this;\n\n    this.url = url;\n    var strict = true;\n    var saxStream = sax.createStream(strict);\n    var heartbeatTimerId = undefined;\n\n    // delete existing tmp_node collection\n    // NodeTmpDB.drop();\n\n    // status information. count ways and relations\n    this.status = {ways: 0\n              , relations: 0\n              , nodes: 0\n              , dbqueue: 0\n              , done: false\n              }\n\n    // update status callbacks\n    function decrDBQueue() { _osm_parser.status.dbqueue--; };\n    function missingWay(way) { missing({way: way}); };\n\n    // check periodically if work is done. Call heartbeat and finally call callback\n    function checkStatus() {\n        // done: the whole input is parsed\n        // dbqueue == 0: Nothing is queued for writing\n        if (_osm_parser.status.done && _osm_parser.status.dbqueue == 0) {\n            clearTimeout(heartbeatTimerId);\n\n            if (heartbeat) heartbeat(_osm_parser.status);\n            callback(null);\n        } else {\n            setTimeout(checkStatus,300);\n        }\n    }\n    setTimeout(checkStatus,300);\n\n    // call heartbeat every second, if defined\n    function heartbeatCallback() {\n        heartbeat(_osm_parser.status);\n        heartbeatTimerId = setTimeout(heartbeatCallback,1000);\n    }\n    if (heartbeat) {\n        heartbeatTimerId = setTimeout(heartbeatCallback,1000);\n    }\n\n    // start parsing\n    stream.pipe(saxStream);\n\n    // SAX parser events follow\n\n    saxStream.on(\"error\", function (e) {\n        logger.warning(e);\n        // clear the error\n        this._parser.error = null\n        this._parser.resume()\n    })\n\n    saxStream.on(\"opentag\", function (tag) {\n        // switch on tags: node, way, relation and their attributes\n        switch(tag.name.toLowerCase()) {\n        case 'osm':\n            if (tag.attributes.version < parseFloat(0.6)) {\n                throw new Error (\"Unsupported OSM file version.\");\n            }\n            break;\n        case 'bound':\n            // XAPI answers with 'bound' tag and swapped lat/lon\n            registryCb({bbox: bboxFromXAPIBound(tag.attributes.box)});\n            break;\n        case 'bounds':\n            var bbox = new BBox([[parseFloat(tag.attributes.minlon), parseFloat(tag.attributes.minlat)], [parseFloat(tag.attributes.maxlon), parseFloat(tag.attributes.maxlat)]])\n            registryCb({bbox: bbox});\n            break;\n        case 'node':\n            _osm_parser.element = new Node(Mongojs.Long(tag.attributes.id)\n                                  ,parseFloat(tag.attributes.lat)\n                                  ,parseFloat(tag.attributes.lon)\n                                  ,parseInt(tag.attributes.version,10)\n                                  ,tag.attributes.visible == 'false' ? false : true\n                                  );\n            registryCb({timestamp: new Date(tag.attributes.timestamp)});\n            break;\n        case 'way':\n            _osm_parser.element = new Way(Mongojs.Long(tag.attributes.id)\n                                  ,parseInt(tag.attributes.version,10)\n                                  ,tag.attributes.visible == 'false' ? false : true\n                                  );\n            registryCb({timestamp: new Date(tag.attributes.timestamp)});\n            break;\n        case 'relation':\n            _osm_parser.element = new Relation(Mongojs.Long(tag.attributes.id)\n                                        ,parseInt(tag.attributes.version,10)\n                                        ,tag.attributes.visible == 'false' ? false : true\n                                        );\n            registryCb({timestamp: new Date(tag.attributes.timestamp)});\n            break;\n        case 'nd':\n            // element is a Way object\n            _osm_parser.element.addNodeId(Mongojs.Long(tag.attributes.ref));\n            break;\n        case 'member':\n            // element is a Relation object\n            if (tag.attributes.type == 'node') {\n                var node = new Node(Mongojs.Long(tag.attributes.ref));\n                _osm_parser.element.addNodeMember(tag.attributes.role, node);\n            } else if (tag.attributes.type == 'way') {\n                var way = new Way(Mongojs.Long(tag.attributes.ref));\n                _osm_parser.element.addWayMember(tag.attributes.role, way);\n            }\n            break;\n        case 'tag':\n            // mongo cannot have a dot in keys\n            key = tag.attributes.k.replace('\\.',':')\n            if (!_osm_parser.element.attrs) {\n                _osm_parser.element.attrs = {};\n            }\n            _osm_parser.element.attrs[key] = tag.attributes.v;\n            break;\n        }\n    });\n\n    saxStream.on(\"closetag\", function (name) {\n        switch(name.toLowerCase()) {\n        case 'node':\n            var node = _osm_parser.element;\n            // store node in temporary DB table\n            NodeTmpDB.add(node);\n            // nodes with properties are also stored in osm table\n            if (node.attrs && node.visible) {\n                _osm_parser.status.dbqueue++;\n                NodeDB.storeNode(node, decrDBQueue);\n            }\n            _osm_parser.status.nodes++;\n            break;\n        case 'way':\n            _osm_parser.status.ways++;\n            if (_osm_parser.element.visible) {\n                _osm_parser.status.dbqueue++;\n                WayDB.storeWay(_osm_parser.element, decrDBQueue, registryCb);\n            }\n            break;\n        case 'relation':\n            _osm_parser.status.relations++;\n            if (_osm_parser.element.visible) {\n                _osm_parser.status.dbqueue++;\n                RelationDB.storeRelation(_osm_parser.element, decrDBQueue, missingWay);\n            }\n            break;\n        }\n    });\n\n\n    saxStream.on(\"end\", function () {\n        _osm_parser.status.done = true;\n    })\n\n}\n\n\nfunction bboxFromXAPIBound(bound) {\n    var parseBound = /([\\-\\.0-9]+),([\\-\\.0-9]+),([\\-\\.0-9]+),([\\-\\.0-9]+)/g;\n    var boundMatch = parseBound.exec(bound);\n    return new BBox([[parseFloat(boundMatch[2]),parseFloat(boundMatch[1])],[parseFloat(boundMatch[4]),parseFloat(boundMatch[3])]]);\n}\n\n\n\n","/**\n* Convert OSM data from Mongo DB to proper node.\n*\n* Stefan Wehner (2012)\n*/\n\nvar Node = require('../geometry/node').Node;\n\n\nexports.NodeConverter = NodeConverter;\n\n// relation_id parameter is only used if feature is part of a relation\nfunction NodeConverter(collection, osm, callback) {\n    this.collection = collection;\n    this.osm = osm;\n    this.node = new Node(osm._id.osm, osm.loc[1], osm.loc[0]);\n    this.node.setTags(osm.tags);\n    // applies for nodes which are part of a relation\n    this.node.setRel(osm.rel);\n    var context = this;\n\n    process.nextTick(function() {callback(null, context.node)});\n}\n\n","/**\n* Convert OSM data from Mongo DB to proper way.\n*\n* Stefan Wehner (2012)\n*/\n\nvar Way = require('../geometry/way').Way;\n\nexports.WayConverter = WayConverter;\n\nWayConverter.prototype.waySegmentsLookup = function(callback) {\n    var query = {\"_id.osm\": this.way.osm_id,\n                 \"_id.seg\": {\"$gt\": 0}\n                };\n    this.coordinates = [];\n\n    // for use by inner function\n    var context = this;\n\n    this.collection.find(query, {sort: '_id.seg'}).toArray(function(error, result) {\n        if( !error ) {\n            for (var rx=0; rx<result.length; rx++) {\n                var nodes;\n                if (result[rx]._id.seg > 1) {\n                    // drop the common node\n                    nodes = result[rx].nd.slice(1);\n                } else {\n                    nodes = result[rx].nd;\n                }\n\n                context.coordinates = context.coordinates.concat(nodes);\n            }\n            context.way.setCoordinates(context.coordinates);\n        }\n        process.nextTick(function() {callback(error,context.way)});\n    });\n}\n\n\nfunction WayConverter(collection, osm, callback) {\n    this.collection = collection;\n    this.osm = osm;\n    this.way = new Way(osm._id.osm, osm.v);\n    this.way.addTags(osm.tags);\n    // applies to ways which are part of a relation\n    this.way.setRel(osm.rel);\n\n    this.waySegmentsLookup(callback);\n}\n\n","/**\n* Concatenate ways to form polygons.\n*\n* Stefan Wehner 2012\n*/\n\nexports.reduceMembers = reduce;\nexports.removeAtIndex = removeAtIndex;\nexports.same = same;\n\n// returns true if p0 and p1 have the same coordinates\nfunction same(p0, p1) {\n    return (Math.abs(p0[0] - p1[0]) < 1e-9 && Math.abs(p0[1] - p1[1]) < 1e-9);\n}\n\n// returns a new array with the i-th element removed from a.\n// Note: a will be changed in the process!\nfunction removeAtIndex(a,ri) {\n    if (ri < a.length) {\n        for (var ix=ri; ix>0; ix--) {\n            a[ix]=a[ix-1];\n        }\n        return a.slice(1);\n    } else {\n        return a;\n    }\n}\n\n\n/**\n* A relation (polygon) in openstreetmap is made from 1..n ways. This routine finds ways\n* in the relations members which connect to each other.\n*/\n\nfunction reduce(mem) {\n    var m0 = mem[0];\n    // go over all members (ways) in mem\n    for (var i=1; i<mem.length; i++) {\n        var m1 = mem[i];\n        // test if any of their endpoints are the same and reverse array if necessary\n        if (same (m0[m0.length-1], m1[m1.length-1])) {\n            m1.reverse();\n        } else if (same (m0[0], m1[0])) {\n            m0.reverse();\n        } else if (same (m0[0], m1[m1.length-1])) {\n            m0.reverse();\n            m1.reverse();\n        }\n        // last node in m0 is the same as first node in m1\n        if (same(m0[m0.length-1], m1[0])) {\n            mem[0] = m0.concat(m1.splice(1));\n            mem = removeAtIndex(mem,i);\n            if (mem.length > 1) {\n                mem = reduce(mem);\n            }\n            break;\n        }\n    }\n    // no connecting member was found for m1. Try with the rest\n    if (mem.length > 2) {\n        var mx = reduce(mem.splice(1));\n        return mem.concat(mx);\n    }\n    return mem;\n}\n\n","/**\n* Convert OSM data from Mongo DB to proper relation.\n*\n* Stefan Wehner (2012)\n*/\n\nvar Node = require('../geometry/node').Node;\nvar Way = require('../geometry/way').Way;\nvar Relation = require('../geometry/relation').Relation;\n\nvar NodeConverter = require('../access/node-converter').NodeConverter;\nvar WayConverter = require('../access/way-converter').WayConverter;\n\nvar reduceMembers = require('../geometry/polygon-utils').reduceMembers;\n\n\n/*\n* All way members of the relation which have the same role will be combined\n* into longer ways or polygons.\n*\n*/\nRelationConverter.prototype.combineWays = function() {\n    var context = this;\n\n    // go over existing roles\n    for (role in context.relation.ways) {\n        if (context.relation.ways.hasOwnProperty(role)) {\n            // combine all way coordinates in one list of list of coordinates\n            var segments = [];\n            context.relation.ways[role].forEach(function(way) {\n                segments.push(way.coordinates);\n            })\n            // Reduce and save the new way object\n            context.relation.ways[role] = [];\n            reduceMembers(segments).forEach(function(coords) {\n                var way = new Way();\n                way.setCoordinates(coords);\n                context.relation.ways[role].push(way);\n            });\n        }\n    }\n}\n\n// wait for the node and way converters to call back\nRelationConverter.prototype.featureCb = function(error, feature) {\n    this.outstanding_members--;\n    var context = this;\n    var role = undefined;\n    var errors = [];\n\n    if (error) {\n        errors.push(error);\n    } else {\n        if (feature) {\n            if (!feature.rel) {\n                throw new Error(\"Relation \"+context.relation.osm_id+\" member \"+feature.osm_id+\" missing 'rel' field.\");\n            }\n            // determine the role in the relation\n            feature.rel.forEach(function(rp) {\n                if (rp.id == context.relation.osm_id) {\n                    role = rp.r;\n                }\n            })\n            if (role === undefined) {\n                throw new Error(\"Relation \"+context.relation.osm_id+\" member \"+feature.osm_id+\" missing role.\");\n            }\n\n            // add node and way members to relation. We only care about the member's id\n            // its coordinates and its role. The member's tags are not preserved as they\n            // should not matter for the relation.\n            if (feature instanceof Node) {\n                this.relation.addNodeMember(role, feature);\n            } else if (feature instanceof Way) {\n                this.relation.addWayMember(role, feature);\n            } else {\n                throw new Error(\"Relation \"+context.relation.osm_id+\" Unknown member type: \"+feature);\n            }\n        }\n    }\n\n    if (context.outstanding_members <= 0) {\n        // combine all way members with the same role into a single path.\n        context.combineWays();\n\n        var error = errors.length ? errors : null;\n        process.nextTick(function() {context.callback(error, context.relation)});\n    }\n};\n\nexports.RelationConverter = RelationConverter;\n\nfunction RelationConverter(collection, osm, callback) {\n    this.collection = collection;\n    this.osm = osm;\n    this.callback = callback;\n    this.relation = new Relation(osm._id.osm, osm.v);\n    this.relation.addTags(osm.tags);\n    this.outstanding_members = 0;\n\n    // for use by inner function\n    var context = this;\n\n    // query for relation members\n    var query = {\"rel.id\": this.osm._id.osm};\n    this.collection.find(query).toArray(function(error, result) {\n        if( !error && result.length > 0) {\n            for (var ix=0; ix<result.length; ix++) {\n                var osm = result[ix];\n                switch(osm.type) {\n                case 'n':\n                  context.outstanding_members++;\n                  new NodeConverter(context.collection, osm, function(error, node) {context.featureCb(error, node);});\n                  break;\n                case 'w':\n                case 'p':\n                  context.outstanding_members++;\n                  new WayConverter(context.collection, osm, function(error, way) {context.featureCb(error, way);});\n                  break;\n                default:\n                  throw new Error(\"Unknown type \"+osm.type+\" for osm data id: \"+osm._id.osm);\n                }\n            }\n        } else {\n            process.nextTick(function() {callback(error,context.relation) });\n        }\n    });\n\n\n}\n\n","/**\n* Convert mongo query results to proper OSM nodes, ways and relations\n*\n* Stefan Wehner 2012\n*/\n\nvar Node = require('../geometry/node').Node;\nvar Way = require('../geometry/way').Way;\nvar Relation = require('../geometry/relation').Relation;\n\nvar NodeConverter = require('../access/node-converter').NodeConverter;\nvar WayConverter = require('../access/way-converter').WayConverter;\nvar RelationConverter = require('../access/relation-converter').RelationConverter;\n\nexports.convertToOsm = function(collection, result, callback) {\n    var dedup = {};\n    var res = { nodes: []\n              , ways: []\n              , relations: []\n              };\n\n    var oustanding_requests = 0;\n    var errors = [];\n\n    // wait for the individual converters to call back\n    function featureCb(error, feature) {\n        oustanding_requests--;\n        if (error) {\n            errors.push(error);\n        } else {\n            if (feature instanceof Node) {\n                res.nodes.push(feature);\n            }\n            if (feature instanceof Way) {\n                res.ways.push(feature);\n            }\n            if (feature instanceof Relation) {\n                res.relations.push(feature);\n            }\n        }\n        if (oustanding_requests <= 0) {\n            var error = null;\n            if (errors.length) {\n                error = errors.join('\\n');\n            }\n            callback(error, res);\n        }\n    };\n\n    for (var ix=0; ix<result.length; ix++) {\n        var osm = result[ix];\n        // do not process duplicate finds from $within queries\n        if (!dedup[osm._id.osm]) {\n            dedup[osm._id.osm] = true;\n            switch(osm.type) {\n            case 'n':\n              oustanding_requests++;\n              new NodeConverter(collection, osm, featureCb);\n              break;\n            case 'w':\n            case 'p':\n              oustanding_requests++;\n              new WayConverter(collection, osm, featureCb);\n              break;\n            case 'r':\n              oustanding_requests++;\n              new RelationConverter(collection, osm, featureCb);\n              break;\n            default:\n                throw new Error(\"Unknown type \"+osm.type+\" for osm data id: \"+osm._id.osm);\n            }\n        }\n    }\n\n    // this will produce a callback even if no data was found\n    oustanding_requests++;\n    process.nextTick(featureCb);\n}\n","/**\n* Create singleton instance per osm database.\n*\n* Stefan Wehner 2012\n*/\n\nvar Mongojs = require('mongodb');\n\nvar MongoOsm = require('../mongo/mongo-connect');\nvar logger = require('../util/logger');\nvar Settings = require('../util/settings').getSettings();\nvar OsmConverter = require('./osm-converter');\n\nvar OsmDb = {};\n\nvar EarthRadius = 6378 // km\n\n\nexports.OsmComplete = function(mongo_host, mongo_port) {\n    if (!OsmDb.hasOwnProperty(mongo_host+mongo_port)) {\n        OsmDb[mongo_host+mongo_port] = new OsmComplete(mongo_host, mongo_port);\n    }\n    return OsmDb[mongo_host+mongo_port];\n}\n\nexports.TestInterface = {\n    injectMongoDb: function(mock) {MongoOsm = mock;},\n    injectLogger: function(mock) {logger = mock;},\n    injectOsmConverter: function(mock) {OsmConverter = mock;},\n    tagsPrefix: tagsPrefix\n}\n\nfunction OsmComplete(mongo_host, mongo_port) {\n    this.host = mongo_host;\n    this.port = mongo_port;\n    this.collection = undefined;\n    this.queued = [];\n    var context = this;\n\n    function connectedCb(error) {\n        if (error) {\n            throw new Error(\"Could not connect to Mongo: \"+error);\n        }\n        context.collection = MongoOsm.getCollection(Settings.OSM_COLLECTION);\n        context.callEnqueued(context.collection);\n    }\n\n    MongoOsm.connect(mongo_host, mongo_port, connectedCb);\n}\n\nOsmComplete.prototype.findOsm = function(tags, callback) {\n    logger.debug(\"OsmComplete.findOsm\", tags);\n    var query = tagsPrefix(tags);\n    var context = this;\n    this.callWhenReady( function(collection) {find(context.collection, query, callback)} );\n}\n\nOsmComplete.prototype.findOsmNear = function(loc, distance_km, tags, callback) {\n    logger.debug(\"OsmComplete.findOsmNear loc=\"+loc+\" distance=\"+distance_km+\"km\", tags);\n\n    function osmGeoNear(collection, query, callback) {\n        var options = {\n            query: query,\n            spherical: true,\n            maxDistance: distance_km / EarthRadius,\n            uniqueDocs: true\n        }\n        collection.geoNear(loc[0], loc[1], options, function(error, result) {\n            if (error) {\n                callback(\"Failed to execute query <\"+query+\"> Error: \"+error);\n            }\n            var osm = [];\n            result.results.forEach(function(res) {\n                osm.push(res.obj);\n            });\n            OsmConverter.convertToOsm(collection, osm, callback);\n        });\n    }\n\n    var context = this;\n    this.callWhenReady( function(collection) {osmGeoNear(context.collection, tagsPrefix(tags), callback)} );\n}\n\nOsmComplete.prototype.findOsmBox = function(bbox, tags, callback) {\n    logger.debug(\"OsmComplete.findOsmBox bbox=\"+bbox, tags);\n    var query = tagsPrefix(tags);\n    query.loc = {$within: {$box: bbox.bbox()}};\n    var context = this;\n    this.callWhenReady( function(collection) {find(context.collection, query, callback)} );\n}\n\nOsmComplete.prototype.findOsmPolygon = function(polygon, tags, callback) {\n    logger.debug(\"OsmComplete.findOsmPolygon polygon=\", {polygon: polygon, tags: tags});\n    var query = tagsPrefix(tags);\n    query.loc = {$within: {$polygon: polygon}};\n    var context = this;\n    this.callWhenReady( function(collection) {find(context.collection, query, callback)} );\n}\n\n// queue up Db calls in case DB connection is not established\nOsmComplete.prototype.callWhenReady = function(dbfind) {\n    this.queued.push( dbfind );\n    if (this.collection) {\n        this.callEnqueued();\n    }\n}\n\n// call enqueued DB requests\nOsmComplete.prototype.callEnqueued = function() {\n    while (this.queued.length) {\n        this.queued.pop()(this.collection);\n    }\n}\n\n\nfunction find(collection, query, callback) {\n    collection.find(query).toArray(function(error, result) {\n        if (error) {\n            callback(\"Failed to execute query <\"+query+\"> Error: \"+error);\n        }\n        OsmConverter.convertToOsm(collection, result, callback);\n    });\n}\n\n\n// prefix property names with 'tags.' as so they are named in the DB\nfunction tagsPrefix(user_query) {\n    var query = {};\n    for (var tag in user_query) {\n        if (tag.slice(0,1) != '$') {\n            query[\"tags.\"+tag] = user_query[tag];\n        } else {\n            query[tag] =  user_query[tag];\n        }\n    };\n    return query;\n}\n","/*\n* Tile grid access functions\n*\n* Stefan Wehner (2012)\n*/\n\nvar logger = require(\"../util/logger\");\n\nvar DB = require(\"../mongo/mongo-connect\");\nvar Settings = require('../util/settings').getSettings();\n\nvar TILES_COLLECTION = Settings.TILES_COLLECTION || 'tiles';\n\n\nexports.storeTiles = function(tilesdata) {\n    logger.trace(\"Register tiles.\", tilesdata);\n    DB.getCollection(TILES_COLLECTION).insert(tilesdata, function(error) {\n        if (error) {\n            throw new Error(\"Could not insert tile information: \"+error);\n        }\n    });\n}\n","/*\n* Keep track of downloaded or file-read data tiles\n*\n* Stefan Wehner (2012)\n*/\n\n\nvar DB = require(\"../mongo/mongo-connect\");\nvar BBox = require(\"../geometry/bbox\").BBox;\n\nvar Mongojs = require('mongodb');\n\nexports.TileRegistry = TileRegistry;\n\nfunction TileRegistry(url) {\n    this.url = url;\n    this.tiles = {};\n    this.bbox = undefined;\n    this.read_timestamp = new Date();\n    this.data_timestamp = new Date(1990,1,1);\n}\n\n// set primary bbox for the whole data. Nothing will be registered outside this box\nTileRegistry.prototype.setBBox = function(bbox) {\n    this.bbox = bbox;\n}\n\n// update latest date in data\nTileRegistry.prototype.updateTimestamp = function(date) {\n    if (this.data_timestamp < date) {\n        this.data_timestamp = date;\n    }\n}\n\n// call for each way and node with the element's bbox and date\nTileRegistry.prototype.updateElementBBox = function(box) {\n    var bbox = this.bbox;\n    var tiles = this.tiles;\n    new BBox(box.bbox()).inflateToNextGridLine().forEachGridBBox(function(bb) {\n        // check that new tile box is inside the overall box (if defined)\n        if (!bbox || bbox.isBoxOverlap(bb)) {\n            // update existing box or add new one to the tiles object\n            if (!tiles[bb.hash()]) {\n                tiles[bb.hash()] = bb;\n            }\n        }\n    });\n}\n\n// return a batch of tiles ready to be stored in MongoDB\nTileRegistry.prototype.getMongoEntry = function() {\n    var data = [];\n    var tiles = this.tiles;\n    for (var b in tiles) {\n        if (tiles.hasOwnProperty(b)) {\n            var bb = tiles[b];\n            data.push({_id: {url: this.url\n                          , loc: [bb.west,bb.south]\n                        }\n                        , read_timestamp: this.read_timestamp\n                        , data_timestamp: this.data_timestamp  // latest data\n                      })\n        }\n    }\n    return data;\n}\n\n","/*\n* Main\n*\n* Stefan Wehner (2012)\n*/\n\n// Classes for OSM primitives\nexports.Way = require('./geometry/way').Way;\nexports.Node = require('./geometry/node').Node;\nexports.Relation = require('./geometry/relation').Relation;\n\n// Parser\nexports.OsmParser = require('./parser/osm-parser').OsmParser;\n\n// Database views\nexports.OsmComplete = require('./access/osm-complete').OsmComplete;\n\n// logger\nexports.Logger = require('./util/logger');\n\n// settings\nexports.Settings = require('./util/settings').getSettings();\n\n// store OSM primitives to MongoDB\nexports.MongoOsm = require('./mongo/mongo-connect');\nexports.WayDb = require('./mongo/way-mongo');\nexports.RelationDb = require('./mongo/relation-mongo');\nexports.TmpNodeDb = require('./mongo/tmp-node-mongo');\nexports.TileDB = require('./mongo/tiles-mongo');\n\n// convert from MongoDb representation to OSM primitive\nexports.RelationConverter = require('./access/relation-converter').RelationConverter;\n\n// GIS geometry\nexports.BBox = require('./geometry/bbox').BBox;\nexports.Geomath = require('./geometry/geomath');\nexports.Transform = require('./geometry/geomath').Transform;\nexports.PolygonUtils = require('./geometry/polygon-utils');\n\n// registry for downloaded data\nexports.TileRegistry = require('./parser/tile-registry').TileRegistry;\n\n","module.exports = require('./lib/');\n"]}