This repository has been archived on 2023-11-03. You can view files and clone it, but cannot push or open issues or pull requests.
GINPA/Modele/GMapsAPI.c

190 lines
5.2 KiB
C
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "GMapsAPI.h"
bool getBackgroundMap(const Carte *const carte)
{
static const char *const mapTypes[] = {"NoType", "roadmap", "satellite", "terrain", "hybrid", "NoType"};
// Ici on fabrique notre """petite""" URL magique
char request[REQUESTSIZE] = "";
snprintf(request, REQUESTSIZE,
"https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&size=%ux%u&scale=%u&zoom=%u&maptype=%s&key=%s",
carte->pointCentral.lat, carte->pointCentral.lon,
MAPSIZE, MAPSIZE,
MAPSCALE,
carte->zoom,
mapTypes[carte->type],
"AIzaSyBcU1vPg1hRYaMd3eGDIkoUULISuw6wbw8");
/* cURL Request */
// On crée notre objet cURL pour la suite
CURL *curl = curl_easy_init();
if(curl == NULL)
{
fprintf(stderr, "L\'objet cURL n\'a pas pu être initialisé.\n");
return false;
}
// On crée / ouvre un fichier en écriture
FILE *map = fopen(MAPFILE, "wb");
if(map == NULL)
{
curl_easy_cleanup(curl);
fprintf(stderr, "L'ouverture du fichier n\'a pas été possible: %s\n", strerror(errno));
return false;
}
// On crée nos opérations à effectuer lors de l'exécution de la requête
curl_easy_setopt(curl, CURLOPT_URL, request);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, map);
// On exécute !
CURLcode result = curl_easy_perform(curl);
// On détruit notre objet cURL
curl_easy_cleanup(curl);
// On ferme le fichier
if(fclose(map) == EOF)
{
fprintf(stderr, "La fermeture du fichier n\'a pas été possible: %s\n", strerror(errno));
return false;
}
// On indique à la fonction appelante si cURL a correctement effectué les opérations ou non !
if(result != CURLE_OK)
{
fprintf(stderr, "Un problème est survenu durant l\'opération cURL. Code de retour: %d.\n", result);
return false;
}
else
{
return true;
}
}
char* getReverseGeocoding(const Coordonnees *const point)
{
char request[REQUESTSIZE] = "";
snprintf(request, REQUESTSIZE,
"https://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&language=%s&key=%s",
point->lat, point->lon,
"fr",
"AIzaSyBcU1vPg1hRYaMd3eGDIkoUULISuw6wbw8");
CURL *curl = curl_easy_init();
if(curl == NULL)
{
fprintf(stderr, "L\'objet cURL n\'a pas pu être initialisé.\n");
return NULL;
}
FILE *address = fopen(ADDRESSFILE, "wb+");
if(address == NULL)
{
curl_easy_cleanup(curl);
fprintf(stderr, "L'ouverture du fichier n\'a pas été possible: %s\n", strerror(errno));
return NULL;
}
curl_easy_setopt(curl, CURLOPT_URL, request);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, address);
CURLcode result = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(result != CURLE_OK)
{
fprintf(stderr, "Un problème est survenu durant l\'opération cURL. Code de retour: %d.\n", result);
if(fclose(address) == EOF)
{
fprintf(stderr, "La fermeture du fichier n\'a pas été possible (non-fatale): %s\n", strerror(errno));
}
return NULL;
}
// On force l'écriture des données et rembobine le curseur en début de fichier.
fflush(address);
rewind(address);
// On charge dans une variable le contenu du JSON
json_error_t error;
json_t *root = json_loadf(address, 0, &error);
// Une fois le chargement terminé, on peut fermer notre fichier ouvert...
if(fclose(address) == EOF)
{
fprintf(stderr, "La fermeture du fichier n\'a pas été possible (non-fatale): %s\n", strerror(errno));
}
// Au cas où...
if(root == NULL || !json_is_object(root))
{
fprintf(stderr, "Un problème est survenu lors du parsing des adresses. Informations supplémentaires:\n\n\"%s\": %s {[%d, %d] - %d}\n", error.source, error.text, error.line, error.column, error.position);
json_decref(root);
return NULL;
}
// `obj` prendra les valeurs successives des champs du JSON.
json_t *obj = NULL;
json_t *array = NULL;
/* Test du retour de l'API de Google */
obj = json_object_get(root, "status");
if(!json_is_string(obj) || strcmp(json_string_value(obj), "OK"))
{
fprintf(stderr, "L\'API Geocoding a renvoyé une erreur: \"%s\".\n", json_string_value(obj));
json_decref(root);
return NULL;
}
/* _________________________________ */
/* L'API nous a donné son feu vert, on récupère les résultats ! */
array = json_object_get(root, "results");
// L'objet récupéré DOIT ÊTRE un "tableau"
if(!json_is_array(array))
{
fprintf(stderr, "Un problème est survenu lors du parsing des addresses: les résultats ne sont pas là :\'(.\n");
json_decref(root);
return NULL;
}
// On a récupéré un tableau d'éléments, parcourons-le !
size_t index;
json_t *value;
json_array_foreach(array, index, value)
{
// L'information qui nous intéresse est dans un Objet encore
if(json_is_object(value))
{
obj = json_object_get(value, "formatted_address");
// Notre information n'est pas loin ! Mais est-ce une string ?
if(json_is_string(obj))
{
// On détermine la taille -> Allocation dynamique et copie. (`+ 1` pour garder une case pour '\0')
ssize_t lenght = strlen(json_string_value(obj)) + 1;
char *temp = calloc(lenght, sizeof(*temp));
strncpy(temp, json_string_value(obj), lenght);
json_decref(root);
return temp;
}
}
}
/* ____________________________________________________________ */
// Aucun champ correspondant n'a été trouvé, on détuit l'objet avant de quitter
json_decref(root);
return NULL;
}