added parsing of result name

This commit is contained in:
Steffen Vogel 2012-12-23 02:18:38 +01:00
parent 3f4607b3ca
commit 245ace61b1
4 changed files with 43 additions and 27 deletions

View file

@ -46,7 +46,7 @@ static size_t json_parse_callback(void *contents, size_t size, size_t nmemb, voi
return realsize;
}
int geonames_lookup(const char *place, struct coords *result) {
int geonames_lookup(const char *place, struct coords *result, char *name, int n) {
CURL *ch;
CURLcode res;
@ -86,21 +86,29 @@ int geonames_lookup(const char *place, struct coords *result) {
}
if (jobj) {
return geonames_parse(jobj, result);;
int ret = geonames_parse(jobj, result, name, n);
json_object_put(jobj);
return ret;
}
else {
return EXIT_FAILURE;
}
}
int geonames_parse(struct json_object *jobj, struct coords *result) {
struct json_object *jobj_place = json_object_array_get_idx(json_object_object_get(jobj, "geonames"), 0);
int geonames_parse(struct json_object *jobj, struct coords *result, char *name, int n) {
int results = json_object_get_int(json_object_object_get(jobj, "totalResultsCount"));
if (results == 0) {
return EXIT_FAILURE;
}
struct json_object *jobj_place = json_object_array_get_idx(json_object_object_get(jobj, "geonames"), 0);
result->lat = json_object_get_double(json_object_object_get(jobj_place, "lat"));
result->lon = json_object_get_double(json_object_object_get(jobj_place, "lng"));
/* cleanup */
json_object_put(jobj);
if (name && n > 0) {
strncpy(name, json_object_get_string(json_object_object_get(jobj_place, "name")), n);
}
return EXIT_SUCCESS;
}

View file

@ -10,7 +10,7 @@ struct coords {
double lon;
};
int geonames_lookup(const char *place, struct coords *coords);
int geonames_parse(struct json_object *jobj, struct coords *result);
int geonames_lookup(const char *place, struct coords *coords, char *name, int n);
int geonames_parse(struct json_object *jobj, struct coords *result, char *name, int n);
#endif /* _GEONAMES_H_ */

27
src/geonames_main.c Normal file
View file

@ -0,0 +1,27 @@
#include <stdio.h>
#include <stdlib.h>
#include "geonames.h"
int main(int argc, char *argv[]) {
struct coords res;
char *result_name = malloc(32);
char *name = "Aachen";
if (result_name == NULL) {
return EXIT_FAILURE;
}
if (argc == 2) {
name = argv[1];
}
int ret = geonames_lookup(name, &res, result_name, 32);
if (ret == EXIT_SUCCESS) {
printf("%s is at (%.4f, %.4f)\r\n", result_name, res.lat, res.lon);
}
free(result_name);
return ret;
}

View file

@ -1,19 +0,0 @@
#include <stdio.h>
#include "geonames.h"
int main(int argc, char *argv[]) {
struct coords res;
char *name = "Aachen";
if (argc == 2) {
name = argv[1];
}
if (geonames_lookup(name, &res) == 0) {
printf("%s is at (%.4f, %.4f)\r\n", name, res.lat, res.lon);
return 0;
}
return 0;
}