2016-11-29 3 views
0

ちょっと、golangとmongodbを使用して店舗ロケータを構築しようとしています。 私は両方に新しいです。私は検索しようとしましたが、golangでmongodbに名前と座標のストアを挿入し、指定された緯度と経度の3000メートルの半径の店舗を検索するのに役立つコードを見つけることができませんでした。golangとmongodbのstorelocator

注:IDを持っている場合は、店舗を簡単に取得できるように、私は自分でIDを提供したいと思います。

の下に与えられたように私が試したが、何も起こりません、DBには、エラーや店舗の挿入が

test.goは以下の通りではありません:Goがあるようuser7227958

@

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

が見えますあなたの座標の浮動小数点数の正確さの欠如のためにあなたとトリックをする。

これを確認してください: := 39.70、lat:= 35.69あなたのレコードを選択するには、scope = 3000000が必要です。 より正確な座標を使用する場合は、 long := 39.6910592 lat := 35.6909623 とすると、1メートルの範囲で店を見つけることができます。

乾杯、 -d

関連する問題