package main
import (
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/kr/pretty"
"googlemaps.github.io/maps"
)
func main() {
router := gin.Default()
router.GET("/map", func(c *gin.Context) {
apiKey := "YOUR_GOOGLE_MAPS_API_KEY"
client, err := maps.NewClient(maps.WithAPIKey(apiKey))
if err != nil {
log.Fatal("Error creating Google Maps client: ", err)
}
locations := []maps.LatLng{
{Lat: 37.7749, Lng: -122.4194},
{Lat: 34.0522, Lng: -118.2437},
{Lat: 40.7128, Lng: -74.0060},
}
markers := make([]maps.Marker, len(locations))
for i, loc := range locations {
markers[i] = maps.Marker{
Position: loc,
Label: fmt.Sprintf("%c", 'A'+i), // Adding letters to markers
}
}
mapURL := getMapURL(client, markers)
c.JSON(http.StatusOK, gin.H{"map_url": mapURL})
})
router.Run(":8080")
}
func getMapURL(client *maps.Client, markers []maps.Marker) string {
r := &maps.DirectionsRequest{
Origin: "San Francisco, CA",
Destination: "Los Angeles, CA",
Mode: maps.TravelModeDriving,
Waypoints: markersToWaypoints(markers),
}
resp, _, err := client.Directions(nil, r)
if err != nil {
log.Fatal("Error getting directions: ", err)
}
pretty.Println(resp) // Displaying directions response for debugging (optional)
mapURL := getStaticMapURL(resp.Routes[0].OverviewPolyline.Points, markers)
return mapURL
}
func markersToWaypoints(markers []maps.Marker) []string {
var waypoints []string
for _, marker := range markers {
waypoints = append(waypoints, marker.Position.String())
}
return waypoints
}
func getStaticMapURL(polyline string, markers []maps.Marker) string {
var markerLabels string
for _, marker := range markers {
markerLabels += fmt.Sprintf("%c", 'A'+len(markerLabels))
}
return fmt.Sprintf("https://maps.googleapis.com/maps/api/staticmap?size=600x400&path=enc:%s&markers=label:%s", polyline, markerLabels)
}