ChatAI 智能内容创作平台

登录

超智能内容创作平台,AI绘画、写文章、写策划、写文案、写代码,回答你所有问题

更原创、更完整、更智能

免费试用 Pro 版
联系客服

联系客服为您打造专属AI系统

绘图
发送
AI思考中...
生成一个按lat lng 计算距离的golang mongo 代码
2024-12-11 09:39:53
来自 天津市天津市 用户
"```go package main import ( "context" "fmt" "log" "math" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) const ( earthRadiusKm = 6371 ) // Coordinate represents a geographical coordinate type Coordinate struct { Lat float64 `bson:"lat"` Lng float64 `bson:"lng"` } // CalculateDistance calculates the distance between two coordinates in kilometers func CalculateDistance(coord1, coord2 Coordinate) float64 { lat1Rad := math.Pi * coord1.Lat / 180 lng1Rad := math.Pi * coord1.Lng / 180 lat2Rad := math.Pi * coord2.Lat / 180 lng2Rad := math.Pi * coord2.Lng / 180 deltaLat := lat2Rad - lat1Rad deltaLng := lng2Rad - lng1Rad a := math.Sin(deltaLat/2)*math.Sin(deltaLat/2) + math.Cos(lat1Rad)*math.Cos(lat2Rad)* math.Sin(deltaLng/2)*math.Sin(deltaLng/2) c := 2 * math.Asin(math.Min(1, math.Sqrt(a))) return earthRadiusKm * c } func main() { // Connect to MongoDB client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { log.Fatal(err) } defer client.Disconnect(context.TODO()) // Get a collection collection := client.Database("yourDatabase").Collection("yourCollection") // Query the collection var results []Coordinate err = collection.Find(context.TODO(), bson.M{}).Decode(&results) if err != nil { log.Fatal(err) } // Calculate distances for i, coord1 := range results { for _, coord2 := range results[i+1:] { distance := CalculateDistance(coord1, coord2) fmt.Printf("Distance between (%f, %f) and (%f, %f) is %f km\n", coord1.Lat, coord1.Lng, coord2.Lat, coord2.Lng, distance) } } } ``` 这段Golang代码使用了MongoDB的驱动来连接数据库,查询集合中的坐标点,并计算集合中每对坐标点之间的距离。请确保替换`"mongodb://localhost:27017"`、`"yourDatabase"`和`"yourCollection"`为实际的连接字符串、数据库名和集合名。代码中的`CalculateDistance`函数使用了Haversine公式来计算两点之间的距离。"

ChatAI 智能内容创作平台

内容数
浏览数
用户数
微信扫一扫
二维码失效
点击刷新
微信扫码登录/注册
首次扫码关注公众号后将自动注册新账号
请使用 Pro 版以继续
绘图功能及更多问答次数,请前往Pro版继续免费试用。
免费试用 Pro 版
取消
添加联系客服
服务时间:早上 9:00 - 22:00