phongyewtong
phongyewtong

Reputation: 5309

Get lat and lng using $near and $geometry not working on Mongo + meteor

I am trying to get the all docs that is within 200m from a center point but i am having this error

Exception from sub getLocNearMe id hg3jRDv8onsZEGvBM Error: Exception while polling query {"collectionName":"Col_Location","selector":{"loc":{"$near":{"$geometry":{"type":"Point","coordinates":[1.3852457,103.88112509999999]},"$maxDistance":200}}},"options":{"transform":null}}: $near requires a point, given { type: "Point", coordinates: [ 1.3852457, 103.8811251 ] }

client/component/map.jsx

navigator.geolocation.getCurrentPosition(function (pos) {    
    const sub = Meteor.subscribe("getLocNearMe", pos.coords.latitude, pos.coords.longitude)

    Tracker.autorun(function () {
        if (sub.ready()) {
            Data.MarkersRawData = Col_Location.find().fetch()
        }
    })
})

lib/collections.jsx

Meteor.publish("getLocNearMe", function(lng, lat) {
    check(lat, Number)
    check(lng, Number)

    const data = Col_Location.find({
        loc: {
            $near: {
                $geometry: {
                    type: "Point" ,
                    coordinates: [lng, lat]
                },
                $maxDistance: 200
            }
        }
    })

    console.log(data)
    if (data) {
        return data
    }

    return this.ready()
})

server/server.jsx

Col_AllQuestion._ensureIndex({"loc": "2dsphere"})

    Col_Location.insert({
        loc: {
            type: "Point",
            coordinates: [103.8, 1.31]
        }
    })

Upvotes: 0

Views: 95

Answers (1)

Tristan
Tristan

Reputation: 1014

Testing you "Point" with http://geojsonlint.com/ gives several problems. It seems the (somewhat nitpicky) spec demands your keys to be quoted strings (which i think meteor handles for you) but also the fact that your coordinates are flipped (lat/long).

Putting you sample in like this gives a valid GeoJSON result:

{ 
  "type": "Point", 
  "coordinates": [ 103.8811251, 1.3852457 ] 
}

Upvotes: 1

Related Questions