geo_point.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2012-2015 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, Lon float64
  13. }
  14. // Source returns the object to be serialized in Elasticsearch DSL.
  15. func (pt *GeoPoint) Source() map[string]float64 {
  16. return map[string]float64{
  17. "lat": pt.Lat,
  18. "lon": pt.Lon,
  19. }
  20. }
  21. // GeoPointFromLatLon initializes a new GeoPoint by latitude and longitude.
  22. func GeoPointFromLatLon(lat, lon float64) *GeoPoint {
  23. return &GeoPoint{Lat: lat, Lon: lon}
  24. }
  25. // GeoPointFromString initializes a new GeoPoint by a string that is
  26. // formatted as "{latitude},{longitude}", e.g. "40.10210,-70.12091".
  27. func GeoPointFromString(latLon string) (*GeoPoint, error) {
  28. latlon := strings.SplitN(latLon, ",", 2)
  29. if len(latlon) != 2 {
  30. return nil, fmt.Errorf("elastic: %s is not a valid geo point string", latLon)
  31. }
  32. lat, err := strconv.ParseFloat(latlon[0], 64)
  33. if err != nil {
  34. return nil, err
  35. }
  36. lon, err := strconv.ParseFloat(latlon[1], 64)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return &GeoPoint{Lat: lat, Lon: lon}, nil
  41. }