67 lines
1.8 KiB
Go
67 lines
1.8 KiB
Go
// ============================================
|
|
// services/tomtom.go - SERVICE TOMTOM ROUTING
|
|
// ============================================
|
|
|
|
package services
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"gestion/models"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"net/url"
|
|
"time"
|
|
)
|
|
|
|
func GetETAWithTraffic(from, to Coordinates) (etaMinutes int, distanceKm float64, err error) {
|
|
client := &http.Client{Timeout: 10 * time.Second}
|
|
|
|
buildReq := func(key string) (*http.Request, error) {
|
|
u := &url.URL{
|
|
Scheme: "https",
|
|
Host: "api.tomtom.com",
|
|
Path: fmt.Sprintf("/routing/1/calculateRoute/%f,%f:%f,%f/json", from.Latitude, from.Longitude, to.Latitude, to.Longitude),
|
|
}
|
|
q := url.Values{}
|
|
q.Set("key", key)
|
|
q.Set("traffic", "true")
|
|
q.Set("travelMode", "car")
|
|
u.RawQuery = q.Encode()
|
|
return http.NewRequest(http.MethodGet, u.String(), nil)
|
|
}
|
|
|
|
resp, err := tomTomKeys.Do(client, buildReq)
|
|
if err != nil {
|
|
return 0, 0, fmt.Errorf("erreur TomTom: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
return 0, 0, fmt.Errorf("erreur API TomTom %d: %s", resp.StatusCode, string(body))
|
|
}
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return 0, 0, fmt.Errorf("erreur lecture: %w", err)
|
|
}
|
|
|
|
var routeResponse models.RouteResponse
|
|
if err := json.Unmarshal(body, &routeResponse); err != nil {
|
|
return 0, 0, fmt.Errorf("erreur parsing: %w", err)
|
|
}
|
|
|
|
if len(routeResponse.Routes) == 0 {
|
|
return 0, 0, fmt.Errorf("aucun itinéraire trouvé")
|
|
}
|
|
|
|
summary := routeResponse.Routes[0].Summary
|
|
etaMinutes = (summary.TravelTimeInSeconds + 59) / 60
|
|
distanceKm = float64(summary.LengthInMeters) / 1000.0
|
|
|
|
log.Printf("🛣️ TomTom Routing: %.2f km → %d min (trafic inclus)", distanceKm, etaMinutes)
|
|
return etaMinutes, distanceKm, nil
|
|
}
|