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