Introduction:
This tutorial shows how to use event listeners with simple click events.
- When a marker is clicked, this function listens for the click event and zooms the map.
- After 3 seconds, it listens for the center changed event and pans the map back to the marker.
User events (such as mouse clicks) are sent from the DOM to the Maps JavaScript API. These events are unique from the usual DOM events.
Code:
function initMap(): void { const myLatlng = { lat: -25.363, lng: 131.044 }; const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 4, center: myLatlng, } ); const marker = new google.maps.Marker({ position: myLatlng, map, title: "Click to zoom", }); map.addListener("center_changed", () => { // 3 seconds after the center of the map has changed, pan back to the // marker. window.setTimeout(() => { map.panTo(marker.getPosition() as google.maps.LatLng); }, 3000); }); marker.addListener("click", () => { map.setZoom(8); map.setCenter(marker.getPosition() as google.maps.LatLng); }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap; export {};
Explanation:
- The function initMap() is created and it consists of the map properties.
- The ‘centre’ attribute defines where the map should be centered with the help of the latitude and longitude coordinates.
const myLatlng = { lat: -25.363, lng: 131.044 }; center: myLatlng,
zoom: 4,
const map = new google.maps.Map( document.getElementById("map") as HTMLElement,
const marker = new google.maps.Marker({ position: myLatlng, map, title: "Click to zoom", });
map.addListener("center_changed", () => { // 3 seconds after the center of the map has changed, pan back to the // marker. window.setTimeout(() => { map.panTo(marker.getPosition() as google.maps.LatLng); }, 3000); }); marker.addListener("click", () => { map.setZoom(8); map.setCenter(marker.getPosition() as google.maps.LatLng); }); }
window.initMap = initMap;
Conclusion:
Thus, in this tutorial we learned how to use the event listeners.