Google Maps Events

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP




<!--
main_leaderboard, all: [728,90][970,90][320,50][468,60]
-->




Google Maps Events



❮ Previous
Next ❯


Click the marker to zoom - attach event handlers to Google maps.




function myMap()

var myCenter=new google.maps.LatLng(51.508742,-0.120850);
var mapOptions =
center: myCenter,
zoom:5,
mapTypeId: google.maps.MapTypeId.ROADMAP
;

var map = new google.maps.Map(document.getElementById("googleMap"),mapOptions);

var marker = new google.maps.Marker(
position: myCenter,
title:'Click to zoom'
);

marker.setMap(map);

// Zoom to 9 when clicking on marker
google.maps.event.addListener(marker,'click',function()
map.setZoom(9);
map.setCenter(marker.getPosition());
);


Click The Marker to Zoom


We still use the map from the previous page: a map centered on London, England.


Now we want to zoom when a user is clicking on the marker (We attach
an event handler to a marker that zooms the map when clicked).


Here is the added code:



Example



// Zoom to 9 when clicking on marker

google.maps.event.addListener(marker,'click',function()

 
map.setZoom(9);

 
map.setCenter(marker.getPosition());

 
);

Try it Yourself »

We register for event notifications using the addListener() event handler.
That method takes an object, an event to listen for, and a function to call when
the specified event occurs.






<!--
mid_content, all: [300,250][336,280][728,90][970,250][970,90][320,50][468,60]
-->




Pan Back to Marker


Here, we save the zoom changes and pan the map back after 3 seconds:



Example



google.maps.event.addListener(marker,'click',function()

  var pos = map.getZoom();
  map.setZoom(9);
 
map.setCenter(marker.getPosition());
  window.setTimeout(function() map.setZoom(pos);,3000);
);

Try it Yourself »


Open an InfoWindow When Clicking on The Marker


Click on the marker to show an infowindow with some text:



Example



var infowindow = new google.maps.InfoWindow(

  content:"Hello World!"

  );


google.maps.event.addListener(marker, 'click', function()

  infowindow.open(map,marker);

  );

Try it Yourself »


Set Markers and Open InfoWindow for Each Marker


Run a function when the user clicks on the map.


The placeMarker() function places a marker where the user has clicked, and shows an infowindow with the latitudes
and longitudes of the marker:



Example



google.maps.event.addListener(map, 'click', function(event)

  placeMarker(map, event.latLng);

  );


function placeMarker(map, location)

  var marker = new google.maps.Marker(

    position: location,

    map: map

  );

  var infowindow = new google.maps.InfoWindow(

    content: 'Latitude: ' + location.lat() +

    '<br>Longitude: ' + location.lng()

  );

  infowindow.open(map,marker);

Try it Yourself »



❮ Previous
Next ❯

Popular posts from this blog

WWE Night of Champions

Poznań

Kaliningrad