Google Maps API V3 Events

Source: Internet
Author: User

Overview

JavaScript in the browser is event-driven, which means that JavaScript responds to interactions by generating events and expects the program to listen for events of interest. The event models used in the Google Maps API V3 and the Google Maps API V2 are very similar in nature, although they differ greatly in their intrinsic mechanisms. There are two types of events:

    • User events (such as "click" mouse events) are propagated from the DOM to the Google Maps API. These events are independent and differ from the standard DOM events.
    • The MVC state change notification reflects changes in the Maps API object and is named according to the property_changed convention.

Each Maps API object can export a large number of named events. If the program wants to implement certain events, the Javascript event listeners are registered for these events and the google.maps.event event handlers are registered in the namespace addListener() to execute the code after receiving these events. Developers of Google Maps API V2 should be familiar with this usage.

For a complete list of events, see the Maps API reference. For each object that contains an event, we list the events for these objects in a separate section.

User Interface Events

Some objects in the Maps API are designed to respond to user events, such as mouse events or keyboard events. google.maps.Markerobjects can listen for some user events, such as:

    • ‘click‘
    • ‘dblclick‘
    • ‘mouseup‘
    • ‘mousedown‘
    • ‘mouseover‘
    • ‘mouseout‘

These events may look like standard DOM events, but they are actually part of the Maps API. Because the DOM event models implemented by different browsers are not the same, the Maps API provides a mechanism for listening to and responding to these DOM events without having to deal with a variety of cross-browser features. These events also typically pass parameters in events that indicate certain user interface States, such as mouse positions.

MVC State Change

MVC objects typically contain states. Whenever you change the properties of an object, the API triggers an event that has changed the property. For example, when the zoom level of a local diagram changes, the API will trigger events on the map zoom_changed . You can also event register event handlers in the namespace method addListener() to intercept these state changes.

User events and MVC state changes look similar, but typically you should treat them differently in your code. For example, MVC events do not pass parameters in their events. You may need to call the appropriate method on the object getProperty to check the properties that were changed in the MVC state change.

Map events

You can use addListener() event handlers to register to receive event notifications. The method takes an object, an event to listen to, and a function to invoke when the specified event occurs.

The following code can combine user events and state change events. We can attach an event handler to a tag that performs a zoom operation on the map when clicked. We'll also add event handlers to the map to change the "center" property and translate the center_changed map back to the marker 3 seconds after receiving the event:

function Initialize () {    var mapoptions = {      zoom:4,      center:new google.maps.LatLng (-25.363882, 131.044922),      MapTypeId:google.maps.MapTypeId.ROADMAP    };      var map = new Google.maps.Map (document.getElementById (' Map_canvas '),        mapoptions);      var marker = new Google.maps.Marker ({      position:map.getCenter (),      Map:map,      title: ' Click to zoom '    }) ;      Google.maps.event.addListener (map, ' center_changed ', function () {      //3 seconds after the center of the map have change D, pan back to the      //marker.      Window.settimeout (function () {        Map.panto (marker.getposition ());      };    });      Google.maps.event.addListener (marker, ' click ', Function () {      map.setzoom (8);      Map.setcenter (Marker.getposition ());    });    Google.maps.event.addDomListener (window, ' Load ', initialize);  

Tip : If you are trying to detect changes in viewports, be sure to use specific bounds_changed events rather than their components zoom_changed and center_changed events. Since the Maps API will trigger the next two events individually, the getBounds() utility results will not be reported until the viewport has been forcibly changed by the system. If you want to get after this type getBounds() of event, be sure to listen to the bounds_changed event instead.

Accessing parameters in user interface events

Typically, user interface events in Google Maps API V3 Pass event arguments that you can access through the event listener, which indicates the user interface state at the time the event occurred. For example, a user interface ‘click‘ event typically passes a containing latLng property that indicates the MouseEvent location of the click on the map. Note that this is the behavior unique to user interface events, and that MVC state changes do not pass parameters in their events.

You can access event parameters in the event listener in the same way that you access object properties. The following example shows how to add an event listener to a map and how to create a marker when the user taps the map.

var map;  function Initialize () {    var mylatlng = new Google.maps.LatLng ( -25.363882,131.044922);    var mapoptions = {      Zoom:4,      center:mylatlng,      MapTypeId:google.maps.MapTypeId.ROADMAP    }    map = new Google.maps.Map (document.getElementById ("Map_canvas"), mapoptions);      Google.maps.event.addListener (Map, ' click ', Function (event) {      placemarker (EVENT.LATLNG);    });    function Placemarker (location) {    var marker = new Google.maps.Marker ({        position:location,        map:map    });      Map.setcenter (location);  }  

Using closures in event listeners

When you execute an event listener, it is generally advisable to attach private and persistent data to the object. JavaScript does not support "private" instance data, but it supports closures that allow internal functions to access external variables. In event listeners, closures are ideal for accessing variables that are not normally attached to an object that occurs.

The following example uses a function closure in an event listener to assign an encrypted message to a set of tokens. Clicking on each tag will see a portion of the encrypted message that is not contained within the tag itself.

var map;    function Initialize () {var mylatlng = new Google.maps.LatLng ( -25.363882,131.044922); var mapoptions = {zoom:4, center:mylatlng, MapTypeId:google.maps.MapTypeId.ROADMAP} map = new      Google.maps.Map (document.getElementById ("Map_canvas"), mapoptions);    ADD 5 markers to the map at random locations.    var southWest = new Google.maps.LatLng ( -31.203405,125.244141);    var northeast = new Google.maps.LatLng ( -25.363882,131.044922);    var bounds = new Google.maps.LatLngBounds (southwest,northeast);    Map.fitbounds (bounds);    var Lngspan = northeast.lng ()-southwest.lng ();    var Latspan = Northeast.lat ()-Southwest.lat (); for (var i = 0; I<5; i++) {var location= newGoogle.maps.LatLng (Southwest.lat () + Latspan * math.random (), southwest.lng () + Lngspan * math.random ()); var marker= newGoogle.maps.Marker ({position:location, map:map}); var J= i+ 1;      Marker.settitle (J.tostring ());    Attachsecretmessage (marker, i); }}//The five markers show a secret message when clicked//if that message is not within the marker ' s instance da  Ta. function Attachsecretmessage (marker, number) {var message= ["This", "is", "the", "Secret", "message"]; var Infowindow= newGoogle.maps.InfoWindow ({content:message[number], size:new google.maps.Size (50,50)});    Google.maps.event.addListener (marker, ' click ', Function () {infowindow.open (map,marker);  }); 

Get and set properties in an event handler

There are no MVC state change events in the Maps API event system that pass parameters when an event is triggered. (User events do pass parameters, which can be checked.) If you need to check the properties of the MVC state change, you should explicitly call the appropriate method on the object getProperty() . During this check, the current state of the MVC object is always retrieved, although it may not be the state that the MVC object was in when it first triggered the corresponding event.

Note : Explicitly setting a property in an event handler that responds to a state change in a particular property may produce unpredictable and/or unnecessary behavior. For example, setting such a property will trigger a new event, and if you always set a property in this event handler, you may end up with an infinite loop.

In the following example, we set up an event handler that responds to scaling events by building the information window that displays the zoom level.

function Initialize () {    var mylatlng = new Google.maps.LatLng ( -25.363882, 131.044922);    var mapoptions = {      Zoom:4,      center:mylatlng,      MapTypeId:google.maps.MapTypeId.ROADMAP    };      var map = new Google.maps.Map (document.getElementById (' Map_canvas '),        mapoptions);      var Infowindow = new Google.maps.InfoWindow ({      content: ' Change of the zoom level ',      position:mylatlng    }); C13/>infowindow.open (map);      Google.maps.event.addListener (map, ' zoom_changed ', function () {      var zoomlevel = Map.getzoom ();      Map.setcenter (MYLATLNG);      Infowindow.setcontent (' Zoom: ' + zoomlevel);    });    Google.maps.event.addDomListener (window, ' Load ', initialize);  

Listen for DOM events

The Google Maps JavaScript API Event Model creates and manages custom events on its own. However, the DOM (Document Object model) inside the browser also creates and dispatches events themselves based on the specific browser event model that is used. If you want to capture and respond to these events, you can use the static methods provided by the Maps API addDomListener() to listen and bind to these DOM events.

This method is easy to use and has a signature as follows:

Adddomlistener (Instance:object, eventname:string, handler:function)

instanceThis may be any DOM element supported by the browser, including:

    • A layered component of the DOM, such as window ordocument.body.myform
    • Named elements, such asdocument.getElementById("foo")

Note that addDomListener() only the indicated event is passed to the browser so that the system handles the event based on the browser's DOM event model, but almost all popular browsers support at least DOM level 2. (For more information about DOM-level events, see the Mozilla DOM level reference.) )

See here, you may already be familiar with window.onload this DOM event, and we have <body> handled the event in the markup. We use this event to trigger the initial JavaScript code after the HTML page is fully loaded, as follows:

<Script>    functionInitialize () {//Map Initialization    }  </Script>  <Bodyonload= "Initialize ()">    <DivID= "Map_canvas"></Div>  </Body>  

Although this event is attached to an element here, <body> the event is actually an window event indicating that the window DOM hierarchy under the element has been fully constructed and rendered.

onloadplacing an event <body> inside a tag is easy to understand, but it confuses the content with the behavior. In general, the best practice is to separate the content code (HTML) from the Behavior Code (JAVASCRIPT) and provide the display code (CSS) separately. To do this, you can replace the inline event handler in your own Maps API JavaScript code with onload a DOM listener, as follows:

<Script>    functionInitialize () {//Map Initialization} google.maps.event.addDomListener (window,'Load', initialize); </Script>  <Body>    <DivID= "Map_canvas"></Div>  </Body>  

Although the above code is the Maps JavaScript API code, the addDomListener() method binds to the browser window object and allows the API to communicate with objects outside its regular domain.

Last updated February 1, 2013.

Google Maps API V3 Events

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.