-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReverseGeocode.cpp
More file actions
87 lines (81 loc) · 2.14 KB
/
ReverseGeocode.cpp
File metadata and controls
87 lines (81 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "ReverseGeocode.hpp"
#include <iostream>
#include <exception>
ReverseGeocode::ReverseGeocode()
{
pFunc = NULL;
PyObject *pName, *pModule;
Py_Initialize();
pName = PyUnicode_FromString("reverse_geocoder");
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, "search");
}
else
{
throw std::runtime_error("module not found");
}
}
std::vector<std::map<std::string, std::string>> ReverseGeocode::search(double _lat, double _lon)
{
std::vector<std::map<std::string, std::string>> results;
if(pFunc && PyCallable_Check(pFunc))
{
PyObject *pArgs, *pLat, *pLon, *pList, *pArgs1;
pArgs = PyTuple_New(2);
pLat = PyFloat_FromDouble(_lat);
if(!pLat)
{
std::cerr << "conversion failed" << std::endl;
return results;
}
PyTuple_SetItem(pArgs, 0, pLat);
// Py_DECREF(pLat);
pLon = PyFloat_FromDouble(_lon);
if(!pLon)
{
std::cerr << "conversion failed" << std::endl;
return results;
}
PyTuple_SetItem(pArgs, 1, pLon);
// Py_DECREF(pLon);
pArgs1 = PyTuple_New(1);
PyTuple_SetItem(pArgs1, 0, pArgs);
pList = PyObject_CallObject(pFunc, pArgs1);
if(!pList)
{
std::cout << "invalid args" << std::endl;
PyErr_Print();
return results;
}
Py_DECREF(pArgs);
Py_DECREF(pLat);
Py_DECREF(pLon);
Py_DECREF(pArgs1);
Py_ssize_t size;
size = PyList_Size(pList);
for(int i = 0 ; i< size; i++)
{
std::map<std::string, std::string> result;
PyObject *pDict;
pDict = PyList_GetItem(pList, i);
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(pDict, &pos, &key, &value)) {
const char* s = PyUnicode_AsUTF8(key);
const char* s1 = PyUnicode_AsUTF8(value);
result[s] = s1;
}
results.push_back(result);
Py_DECREF(pDict);
}
//Py_DECREF(pList); // why? segfaults on second call, uncommenting pDict unref above also werks
}
else
{
std::cerr << "function not found" << std::endl;
}
return results;
}