Google Maps Events
Click marker to zoom map - events bound to the Google Map.
Click marker to zoom map
We still use the map of London, UK used in the previous article.
Implement the function of zooming the map when the user clicks the marker (bind the map zoom event when clicking the marker).
The code is as follows:
Example
//
Zoom to 9 when clicking on marker
.
maps
.
event
.
addListener
(
marker
,
'
click
'
,
function
(
)
{
map
.
setZoom
(
9
)
;
map
.
setCenter
(
marker
.
getPosition
(
)
)
;
}
)
;
Try it »
Use the addListener() event handler to register event listeners. This method uses an object, an event to listen for, and a function will be called when the specified event occurs.
Reset marker
We change the 'center' property by adding an event handler to the map. The following code uses the center_changed event to move the marker back to the center point after 3 seconds:
Example
.
maps
.
event
.
addListener
(
map
,
'
center_changed
'
,
function
(
)
{
window
.
setTimeout
(
function
(
)
{
map
.
panTo
(
marker
.
getPosition
(
)
)
;
}
,
3000
)
;
}
)
;
Try it »
Open an info window when clicking the marker.
Click the marker to display some text information in the info window:
Example
var
infowindow
=
new
.
maps
.
InfoWindow
(
{
content
:
"
Hello World!
"
}
)
;
.
maps
.
event
.
addListener
(
marker
,
'
click
'
,
function
(
)
{
infowindow
.
open
(
map
,
marker
)
;
}
)
;
Try it »
Set markers and open the info window for each marker
Execute a window when the user clicks the map
When the user clicks a location on the map, use the placeMarker() function to place a marker at the specified location and pop up an info window:
Example
.
maps
.
event
.
addListener
(
map
,
'
click
'
,
function
(
event
)
{
placeMarker
(
event
.
latLng
)
;
}
)
;
function
placeMarker
(
location
)
{
var
marker
=
new
.
maps
.
Marker
(
{
position
:
location
,
map
:
map
,
}
)
;
var
infowindow
=
new
.
maps
.
InfoWindow
(
{
content
:
'
Latitude:
'
location
.
lat
(
)
'
Longitude:
'
location
.
lng
(
)
}
)
;
infowindow
.
open
(
map
,
marker
)
;
}
Try it »