I'm trying to get lat/lng from a google my maps iframe in my website but it doesn't work

55 Views Asked by At

I'm doing a little project in Rome. I need people to choose their position in Rome and server get lat/lng from their click. I created a "Google My Maps" map with bordered zones and I don't know how to get user's click on the map.

This is my .Js

var selectedCoordinates = null;
function selectResult(index) {
    var selectedResult = document.querySelector(".result-item:nth-child(" + index + ")");
    var resultsContainer = document.getElementById("dynamicResultsContainer");
    resultsContainer.innerHTML = '';
    resultsContainer.appendChild(selectedResult);

    // Crea il div per la mappa con l'iframe
    var mapDiv = document.createElement("div");
    mapDiv.id = "mapContainer";
    mapDiv.innerHTML = '<iframe src="https://www.google.com/maps/d/u/1/embed?mid=19xx_3tmothVIw3d51PqyNHNwUwsckw0&ehbc=2E312F" width="640" height="480" onclick="mapClickHandler(event)"></iframe>';

    // Aggiungi il div della mappa dopo il risultato selezionato
    resultsContainer.appendChild(mapDiv);
}

function mapClickHandler(event) {
    // Chiama questa funzione quando viene cliccato sulla mappa
    var latLng = event.latLng

    // Invia le coordinate al server tramite una richiesta AJAX
    sendCoordinatesToServer({lat: latLng.lat(), lng: latLng.lng()});
}

function sendCoordinatesToServer(latLng) {
    // Invia le coordinate al server tramite una richiesta AJAX
    console.log('Sending coordinates to server:', coordinates);

    fetch('/update_coordinates', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            lat: latLng.lat(),
            lng: latLng.lng()
        }),
    })
    .then(response => response.json())
    .then(data => {
        console.log('Server response:', data);
    })
    .catch((error) => {
        console.error('Error:', error);
    });
}

I expect to get lat and lng from user click and post them to server for another function. I'm not using a Google API because this is just the final project of the course, so I'm just expecting free solutions.

Thank you.

0

There are 0 best solutions below