geo_point.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package elastic
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. )
  7. // GeoPoint is a geographic position described via latitude and longitude.
  8. type GeoPoint struct {
  9. Lat, Lon float64
  10. }
  11. // Source returns the object to be serialized in Elasticsearch DSL.
  12. func (pt *GeoPoint) Source() map[string]float64 {
  13. return map[string]float64{
  14. "lat": pt.Lat,
  15. "lon": pt.Lon,
  16. }
  17. }
  18. // GeoPointFromLatLon initializes a new GeoPoint by latitude and longitude.
  19. func GeoPointFromLatLon(lat, lon float64) *GeoPoint {
  20. return &GeoPoint{Lat: lat, Lon: lon}
  21. }
  22. // GeoPointFromString initializes a new GeoPoint by a string that is
  23. // formatted as "{latitude},{longitude}", e.g. "40.10210,-70.12091".
  24. func GeoPointFromString(latLon string) (*GeoPoint, error) {
  25. latlon := strings.SplitN(latLon, ",", 2)
  26. if len(latlon) != 2 {
  27. return nil, fmt.Errorf("elastic: %s is not a valid geo point string", latLon)
  28. }
  29. lat, err := strconv.ParseFloat(latlon[0], 64)
  30. if err != nil {
  31. return nil, err
  32. }
  33. lon, err := strconv.ParseFloat(latlon[1], 64)
  34. if err != nil {
  35. return nil, err
  36. }
  37. return &GeoPoint{Lat: lat, Lon: lon}, nil
  38. }