1 // Boost.Geometry (aka GGL, Generic Geometry Library)
2 //
3 // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
4 // Use, modification and distribution is subject to the Boost Software License,
5 // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
6 // http://www.boost.org/LICENSE_1_0.txt)
7
8 // SOCI example
9
10 // b: using WKT to retrieve points
11
12 // To build and run this example, see comments in example a
13
14 #include <soci.h>
15 #include <soci-postgresql.h>
16
17 #include <boost/algorithm/string.hpp>
18 #include <boost/optional.hpp>
19 #include <boost/timer.hpp>
20 #include <boost/random.hpp>
21 #include <boost/tuple/tuple.hpp>
22
23 #include <iostream>
24 #include <istream>
25 #include <ostream>
26 #include <sstream>
27 #include <string>
28 #include <exception>
29
30 #include <boost/geometry/geometry.hpp>
31 #include <boost/geometry/geometries/geometries.hpp>
32
33 #include <boost/geometry/io/wkt/wkt.hpp>
34
35
36 struct city
37 {
38 boost::geometry::model::point<float, 2, boost::geometry::cs::geographic<boost::geometry::degree> > location;
39 std::string name;
40 };
41
42 namespace soci
43 {
44 template <>
45 struct type_conversion<city>
46 {
47 typedef soci::values base_type;
48
from_basesoci::type_conversion49 static void from_base(const base_type& v, soci::indicator ind, city& value)
50 {
51 try
52 {
53 value.name = v.get<std::string>("name");
54 boost::geometry::read_wkt(v.get<std::string>("wkt"), value.location);
55 }
56 catch(const std::exception& e)
57 {
58 std::cout << e.what() << std::endl;
59 }
60 }
61
to_basesoci::type_conversion62 static void to_base(const city& value, base_type& v, soci::indicator& ind)
63 {
64 v.set("name", value.name);
65 std::ostringstream out;
66 out << boost::geometry::wkt(value.location);
67 v.set("wkt", out.str());
68 ind = i_ok;
69 }
70 };
71 }
72
main()73 int main()
74 {
75 try
76 {
77 soci::session sql(soci::postgresql, "dbname=ggl user=ggl password=ggl");
78
79
80 typedef std::vector<city> V;
81
82 soci::rowset<city> rows = sql.prepare << "select name,astext(location) as wkt from cities";
83 V vec;
84 std::copy(rows.begin(), rows.end(), std::back_inserter(vec));
85
86 for (V::const_iterator it = vec.begin(); it != vec.end(); ++it)
87 {
88 static const double sqrkm = 1000.0 * 1000.0;
89 std::cout << it->name
90 << " " << boost::geometry::dsv(it->location)
91 //<< " " << boost::geometry::area(it->shape) / sqrkm << " km2"
92 << std::endl;
93 }
94 }
95 catch (std::exception const &e)
96 {
97 std::cerr << "Error: " << e.what() << '\n';
98 }
99 return 0;
100 }
101