geo_point.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2012-present Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic
  5. import (
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. )
  10. // GeoPoint is a geographic position described via latitude and longitude.
  11. type GeoPoint struct {
  12. Lat float64 `json:"lat"`
  13. Lon float64 `json:"lon"`
  14. }
  15. // Source returns the object to be serialized in Elasticsearch DSL.
  16. func (pt *GeoPoint) Source() map[string]float64 {
  17. return map[string]float64{
  18. "lat": pt.Lat,
  19. "lon": pt.Lon,
  20. }
  21. }
  22. // GeoPointFromLatLon initializes a new GeoPoint by latitude and longitude.
  23. func GeoPointFromLatLon(lat, lon float64) *GeoPoint {
  24. return &GeoPoint{Lat: lat, Lon: lon}
  25. }
  26. // GeoPointFromString initializes a new GeoPoint by a string that is
  27. // formatted as "{latitude},{longitude}", e.g. "40.10210,-70.12091".
  28. func GeoPointFromString(latLon string) (*GeoPoint, error) {
  29. latlon := strings.SplitN(latLon, ",", 2)
  30. if len(latlon) != 2 {
  31. return nil, fmt.Errorf("elastic: %s is not a valid geo point string", latLon)
  32. }
  33. lat, err := strconv.ParseFloat(latlon[0], 64)
  34. if err != nil {
  35. return nil, err
  36. }
  37. lon, err := strconv.ParseFloat(latlon[1], 64)
  38. if err != nil {
  39. return nil, err
  40. }
  41. return &GeoPoint{Lat: lat, Lon: lon}, nil
  42. }