I tried to get the user location when a user visit a website, using javascript. I can get the coordinates of user (lat and long). But when i put these coordinates in the src code (see code below), it doesn't show in map the user location and i get an error (map shows an error). What is the solution? Thanks
Possible solution that i tried, but didn't work:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<div id="map">
<iframe id="google_map" width="600" height="450" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" style="border:0;" allowfullscreen="" loading="lazy" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d77762.85290000484!2d-1.933670854470559!3d52.47752147716896!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4870942d1b417173%3A0xca81fef0aeee7998!2zzpzPgM6tz4HOvM65zr3Ph86xzrwsIM6Xzr3Pic68zq3Ovc6_IM6SzrHPg86vzrvOtc65zr8!5e0!3m2!1sel!2s!4v1638083584669!5m2!1sel!2s"></iframe>
</div>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
return false;
}
function showPosition(position){
document.getElementById('google_map').setAttribute("src", "https://maps.googleapis.com/maps/api/staticmap?center="+position.coords.latitude + "," + position.coords.longitude +"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY")
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
and
document.getElementById('google_map').setAttribute("src", "https://www.google.com/maps/search/?api=1&query=" + position.coords.latitude + "," + **position.coords.longitude);