[GIS] Click event doesn’t work with Google Maps

eventsgoogle-maps-apijavascriptmarkers

I'm trying to create a simple click event when I click on a list item on my page, a marker should be created on the google map in that page. But it does not happen. Is there some google maps API limitation I'm missing here?

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Google Maps Test</title>
</head>

<body>

<div id="map"></div>

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBsOJuJVljNDP1VyUcAXH0s7kizqwU4APk&callback=initMap"></script>

<script src="rome-gm.js"></script> 

<style>
  body {background-color: #fff5e5;}
  #map {height: 650px;} 
  ul {list-style-type: circle; float: left; width: 140px; height: 30px; line-height: 240%; padding-left: 20px; padding-right: 10px; cursor: pointer;}
  li:hover {background-color: #e62e00;}
  li {font-family: "georgia", "san-serif";}
  h1 {text-align: center; font-family: "georgia", "san-serif";}
</style>

<h1>Roman Weekend</h1>

<ul>
  <li onclick="terminiFunction()">Termini</li>
</ul>

</body>

</html>

and here is the script:

function initMap() {
  // Create a map object and specify the DOM element for display.
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 41.902728, lng: 12.496246},
    scrollwheel: false,
    zoom: 13
  });
}

google.maps.event.addDomListener(window, 'load', initMap)

  var marker = new google.maps.Marker({
    position: {lat: 41.900819, lng: 12.501757},
    title:"Termini"
});

function terminiFunction() {
  marker.setMap(map)
}

Best Answer

You need to create marker object before or on click on the list item. Currently, what is happening is that marker object is not initialized properly and also the map object is not accessible in terminiFunction(). Here are the updated functions:

var map;
    function initMap() {
        // Create a map object and specify the DOM element for display.
        map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 41.902728, lng: 12.496246},
            scrollwheel: false,
            zoom: 13
        });
    }
function terminiFunction() {
        var marker = new google.maps.Marker({
            position: {lat: 41.900819, lng: 12.501757},
            title: "Termini"
        });
        marker.setMap(map);
    }

Change your code according to your requirement.