Simple Click Events

by Daehyun Im

HTML

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

CSS

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

JavaScript

var map;
      var markers = [];
      
function initMap() {
  var myLatlng = {lat: -25.363, lng: 131.044};

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: myLatlng
  });

  var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: 'Click to zoom'
  });
/*
  map.addListener('center_changed', function() {
    // 3 seconds after the center of the map has changed, pan back to the
    // marker.
    window.setTimeout(function() {
      map.panTo(marker.getPosition());
    }, 3000);
  });
*/  
  if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(function (position) {
             initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
             map.setCenter(initialLocation);
             var marker = new google.maps.Marker({
               position: {lat: position.coords.latitude, lng: position.coords.longitude}
             });

         });
     }

  map.addListener('click', function( event ){
  
  	var marker = new google.maps.Marker({
	   	 	position: {lat: event.latLng.lat(), lng: event.latLng.lng()},
        map: map
			});
      
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
    }

// To add the marker to the map, call setMap();
		markers.push(marker);
		//marker.setMap(map);
    
    //initialLocation = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
//	map.setCenter(initialLocation);

	  });

}