Why can't I add a marker to Google Maps on my page? I am working with Google Maps API. I don't know what the problem is. Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API&callback=initMap" ></script>
</head>
<body>
<div style="height: 300px; width: 600px;"></div>
<script>
let loc = document.querySelector(".location");
window.onload=loadMap
function loadMap(){
const myLatLng = { lat: 50.488057309872424, lng: 30.47287431851951 };
let options={
center:myLatLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
let map=new google.maps.Map(loc,options)
let marker= new google.maps.Marker({
positon: myLatLng,
map:map,
title: "Это ВЫ!"
});
}
</script>
</body>
</html>
I read Google documentation but I can't find my mistake.
CodePudding user response:
A corrected example that will display the marker once the correct apikey is used. The issue was the incorrect spelling of position
... also removed the window.onload=loadMap
as that was redundant if using the callback
parameter in the script url. Adding async
and defer
to the script url should help ensure that the dom is loaded before attempting to run the javascript code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.location {
width: 600px;
height: 300px;
}
</style>
</head>
<body>
<div ></div>
<script>
function loadMap() {
const myLatLng = {
lat: 50.488057309872424,
lng: 30.47287431851951
};
let options = {
center: myLatLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
let map = new google.maps.Map(document.querySelector(".location"), options);
let marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: ""
})
}
</script>
<script async defer src='//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=loadMap'></script>
</body>
</html>