<?php

function mp_get_coordinates($id) {
	global $mp_api_key;
	$event = (object)[];
	$location = (object)[];
	$location->coordinates = null;
	$location->street = "";
	$location->city = "";
	$location->country = "";
	$location->address = "";
	$location->approximate = false;

	// get address
	$address = "";
	$fields = array(
		"adresse",
		"ville",
		"pays",
	);
	foreach($fields as $field) {
		$address_section = get_field($field, $id);
		$address .= $address_section . ",";
	}

	// get coordinates from google maps api
	$geolocation = 'https://maps.googleapis.com/maps/api/geocode/json'
				 . '?language=fr'
				 . '&address=' . urlencode($address)
				 . '&key=' . $mp_api_key;
	$jsoncontent = file_get_contents($geolocation);

	// extract coordinates from json
	// https://developers.google.com/maps/documentation/geocoding/requests-geocoding#Types
	$content = json_decode($jsoncontent);
	$location->coordinates = $content->results[0]->geometry->location;
	$location->address = $content->results[0]->formatted_address;
	foreach ($content->results[0]->address_components as $component) {
		if (in_array("street_number", $component->types))
			$location->street = $component->long_name;
		else if (in_array("route", $component->types)) {
			if (strlen($location->street) != 0)
				$location->street .= " ";
			$location->street .= $component->long_name;
		}
		else if (in_array("locality", $component->types))
			$location->city = $component->long_name;
		else if (in_array("postal_town", $component->types)) {
			if (strlen($location->city) != 0)
				$location->city .= "/";
			$location->city .= $component->long_name;
		}
		else if (in_array("country", $component->types))
			$location->country = $component->long_name;
	}
	if ($content->results[0]->geometry->location_type == "APPROXIMATE")
		$location->approximate = true;

	foreach ($location as $value) {
		if (gettype($value) != "string")
			continue;
		$value = trim($value, " ");
	}

	return $location;
}


?>
