2016-11-29 34 views
0

嘿,我试图建立一个使用golang和mongodb的商店定位器。 我是新来的。我尝试搜索,但无法找到golang中的代码,它可以帮助我将商店名称和坐标插入到mongodb中,然后在提供的经度和纬度值的3000米范围内搜索商店。storelocator与golang和mongodb

注意:我想自己提供身份证,以便我可以轻松地取得商店,如果我有身份证。

我试过下面给出,但什么也没有发生,在数据库中没有错误或存储插入

test.go是如下:

package main 

import (
    "encoding/json" 
    "fmt" 
    "gopkg.in/mgo.v2" 
    "gopkg.in/mgo.v2/bson" 
    "log" 
) 

type Store struct { 
    ID  string `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"` 
} 

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 := 39.70 
    lat := 35.69 
    scope := 3000 // max distance in metres 

    var results []Store // to hold the results 

    // query the database 
    c := session.DB("test").C("stores") 

    // insert 
    man := Store{} 
    man.ID = "1" 
    man.Name = "vinka medical store" 
    man.Location.Type = "Point" 
    man.Location.Coordinates = []float64{lat, long} 

    // insert 
    err = c.Insert(man) 
    fmt.Printf("%v\n", man) 
    if err != nil { 
     fmt.Println("There is insert error") 
     panic(err) 
    } 

    // ensure 
    // Creating the indexes 
    index := mgo.Index{ 
     Key: []string{"$2dsphere:location"}, 
     Bits: 26, 
    } 
    err = c.EnsureIndex(index) 
    if err != nil { 
     fmt.Println("There is index error") 
     panic(err) 
    } 

    //find 
    err = c.Find(bson.M{ 
     "location": bson.M{ 
      "$nearSphere": bson.M{ 
       "$geometry": bson.M{ 
        "type":  "Point", 
        "coordinates": []float64{long, lat}, 
       }, 
       "$maxDistance": scope, 
      }, 
     }, 
    }).All(&results) 

    //err = c.Find(bson.M{"_id": "1"}).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)) 
} 

回答

0

@ user7227958

看起来像围棋由于(缺少)float64坐标的精确度而与你玩弄技巧。

选中此项: with long:= 39.70 and lat:= 35.69您需要一个scope = 3000000来选择您的记录。 但是,如果您要使用更精确的坐标,请说 long := 39.6910592 lat := 35.6909623 那么即使在1米范围内(预期),您也可以找到您的店铺。

干杯, -D