package main
import (
"context"
"googlemaps.github.io/maps"
"log"
)
const (
apiKey = "YOUR_GOOGLE_MAPS_API_KEY"
)
func main() {
ctx := context.Background()
// Initialize the Google Maps client
client, err := maps.NewClient(maps.WithAPIKey(apiKey))
if err != nil {
log.Fatalf("Error creating Google Maps client: %v", err)
}
// Define the waypoints for the route
waypoints := []string{"New York, NY", "Los Angeles, CA"}
// Retrieve the route information
routeResp, _, err := client.Directions(ctx, &maps.DirectionsRequest{
Origin: waypoints[0],
Destination: waypoints[len(waypoints)-1],
Waypoints: waypoints[1 : len(waypoints)-1],
})
if err != nil {
log.Fatalf("Error getting directions: %v", err)
}
// Calculate the center point of the route
centerLat, centerLng := calculateCenter(routeResp)
// Print the center coordinates
log.Printf("Center Coordinates: %f, %f", centerLat, centerLng)
}
func calculateCenter(route *maps.DirectionsResponse) (float64, float64) {
var totalLat, totalLng float64
// Sum up the latitude and longitude of all points in the route
for _, leg := range route.Routes[0].Legs {
totalLat += leg.StartLocation.Lat
totalLng += leg.StartLocation.Lng
for _, step := range leg.Steps {
totalLat += step.StartLocation.Lat
totalLng += step.StartLocation.Lng
totalLat += step.EndLocation.Lat
totalLng += step.EndLocation.Lng
}
}
// Calculate the average latitude and longitude
numPoints := float64(len(route.Routes[0].Legs)2 + len(route.Routes[0].Legs[0].Steps)4)
centerLat := totalLat / numPoints
centerLng := totalLng / numPoints
return centerLat, centerLng
}