Computer Magic Logo
Marker events

Thursday, December 1, 2016

Published by Aristotelis Pitaridis

Below we can see how to catch various marker events.

<!DOCTYPE html>
<html>
<head>
    <style>
        #map {
            height: 400px;
            width: 600px;
        }
    </style>
</head>
<body>
    <h3>My Google Maps Demo</h3>
    <div id="map"></div>
    <script>
        function initMap() {
            var location = { lat: 35.339186, lng: 25.1315903 };
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 12,
                center: location
            });
            var marker = new google.maps.Marker({
                position: location,
                map: map,
                draggable: true
            });

            google.maps.event.addListener(marker, 'click', function (event) {
                console.log('Clicked.');
            });

            google.maps.event.addListener(marker, 'dblclick', function (event) {
                console.log('Double Clicked.');
            });

            google.maps.event.addListener(marker, 'mouseup', function (event) {
                console.log('Mouse Up.');
            });

            google.maps.event.addListener(marker, 'mousedown', function (event) {
                console.log('Mouse Down.');
            });

            google.maps.event.addListener(marker, 'mouseover', function (event) {
                console.log('Mouse Over.');
            });

            google.maps.event.addListener(marker, 'mouseout', function (event) {
                console.log('Mouse Out.');
            });

            google.maps.event.addListener(marker, 'rightclick', function (event) {
                console.log('Right click.');
            });

            google.maps.event.addListener(marker, 'dragstart', function (event) {
                console.log('Dragg started.');
            });

            google.maps.event.addListener(marker, 'drag', function (event) {
                console.log('Dragging. Lat:' + event.latLng.lat() + ', Lng:' + event.latLng.lng());
            });

            google.maps.event.addListener(marker, 'dragend', function (event) {
                console.log('Drag ended. Lat:' + event.latLng.lat() + ', Lng:' + event.latLng.lng());
            });
        }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
</body>
</html>