I am working on a google map application, to display the items that are listed in the selected rectangular area. Below image give you some understanding.

Based on the co-ordinates (topLeft,bottomRight), i am running bounding box query to find the items in mongo db. But it always returns the this error when running the box queries

 Error: $box needs 2 fields (bottomLeft,topRight)

I know that i have passed topLeft,bottomRight points instead the mongo expected one (bottomLeft,topRight). I am not sure how to calculate the bottomLeft,topRight values based on the co-ordinates from google map.

I hope someone with the better geo knowledge can clarify this..


this is the actual value i got trouble with

bound_box = [[80.22050443383796, 13.051049734963444], [80.2393871853028, 13.043106313697518]]]

and ruby code for finding bounding box values in mongo db

items = Item.where(:loc => {"$within" => {"$box" => [bound_box]}},
                              :category => BSON::ObjectId(cat), :sub_category => BSON::ObjectId(sub)).order_by(:created_at => :desc).skip(@current_page * 5).limit(5).paginate

this is the line giving problem

items = Item.where(:loc => {"$within" => {"$box" => [bound_box]}})

which is similar to the mongodb query

 db.items.find({"loc" : {"$within" : {"$box" : bound_box}}})


enter image description here


Well, I'm not sure I understood well your question since it appears to be too simple. But let's go.

If your coordinates are y,x formatted, and you have :

  • topLeft : 42,10
  • bottomRight : 31,21

then, to calculate bottomLeft, you get the y from bottomRight and get the x from topLeft

and to calculate topRight, , you get the y from topLeft and get the x from bottomRight :

  • bottomLeft : 31,10
  • topRight : 42,21

In case it is not clear enough, just take a pen and a piece of paper and draw it!

  • yeah, thats what i did first after the problem, but the problem still persists with the new values too. so i got totally confused and asked whether there is any other way to do it.. :( – RameshVel Jun 13 '11 at 14:52
  • could it be a cache problem? or the problem is somewhere. Is your code online? – simo Jun 13 '11 at 14:53
  • i have updated th question with more info, check out – RameshVel Jun 13 '11 at 15:05
  • 2
    Just an idea. Are you sure mongodb is not expecting latitude first, then longitude. Like that : bound_box = [[13.051049734963444, 80.22050443383796], [13.043106313697518, 80.2393871853028]]] – simo Jun 13 '11 at 15:18
  • mongo expects longtitude first.. so it wont work.. Finally after hours of digging i found its a problem in ruby driver not in the new calculated bottomLeft, and topRight values.. it works fine now... – RameshVel Jun 14 '11 at 3:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.