Created
October 18, 2014 07:37
-
-
Save icchan/bd42095afd8305594778 to your computer and use it in GitHub Desktop.
Geospatial Querying with GoLang and MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"gopkg.in/mgo.v2" | |
"gopkg.in/mgo.v2/bson" | |
"log" | |
) | |
// ===== models ===== | |
type ShopLocation struct { | |
ID bson.ObjectId `bson:"_id,omitempty" json:"shopid"` | |
Name string `bson:"name" json:"name"` | |
Location GeoJson `bson:"location" json:"location"` | |
} | |
type GeoJson struct { | |
Type string `json:"-"` | |
Coordinates []float64 `json:"coordinates"` | |
} | |
// ===== application ===== | |
func main() { | |
cluster := "localhost" // mongodb host | |
// connect to mongo | |
session, err := mgo.Dial(cluster) | |
if err != nil { | |
log.Fatal("could not connect to db: ", err) | |
panic(err) | |
} | |
defer session.Close() | |
session.SetMode(mgo.Monotonic, true) | |
// search criteria | |
long := 139.701642 | |
lat := 35.690647 | |
scope := 3000 // max distance in metres | |
var results []ShopLocation // to hold the results | |
// query the database | |
c := session.DB("test").C("shops") | |
err = c.Find(bson.M{ | |
"location": bson.M{ | |
"$nearSphere": bson.M{ | |
"$geometry": bson.M{ | |
"type": "Point", | |
"coordinates": []float64{long, lat}, | |
}, | |
"$maxDistance": scope, | |
}, | |
}, | |
}).All(&results) | |
if err != nil { | |
panic(err) | |
} | |
// convert it to JSON so it can be displayed | |
formatter := json.MarshalIndent | |
response, err := formatter(results, " ", " ") | |
fmt.Println(string(response)) | |
} |
I guess my question is, how are you saving this data to the db. The coordinates system to precise?
@Marlon-Monroy my guess is that you need to take a look to https://docs.mongodb.com/manual/geospatial-queries/
Doesn't seems to work anymore :/
I created a gist with the new driver
https://gist.github.com/Lebski/8f9b5992fec0bf175285f1c13b1e5051
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is this still working?