简体   繁体   中英

Binding Google Map Markers to non-map Sidebar Entries

Am trying to add 2-way bindings between event listeners on Google Map V3 markers and off-the-map sidebar entries. I seek examples that accomplish this but am having trouble locating best practices. ESA 2009 was able to establish this type of association between sidebar entry and marker right after Google Maps API V3 was released. Is there a contemporary method for accomplishing this, possibly with jQuery.Callbacks()? This ESA 2009 Example has been up for 3 years but there have been few (if any) successful emulating implementions that have been able to cleanly duplicate the ESA 2009 elegant bidirectional binding functionality between the marker and the corresponding non-Map sidebar entry. This PlugIn is a great start, but that JQuery lacks ability to highlight or identify the selected sidebar item when the marker is clicked directly.

The ESA 2009 approach uses internal functions, closures and prototypes in SidebarItem() and makeMarker() JS functions to establish two-way binding between sidebar entry and marker. When the marker is clicked the sidebar entry is highlighted (and vice versa) without apparent memory leak or excessive recursion. The ESA 2009 technique is conceptually difficult for me to grasp or extend. The behavior is useful but not widely adopted. When users click on a sidebar item, there is typical Google Maps behavior: the map pans and infowindow opens. This is standard, but in the ESA 2009 version there is also an extra piece which is the non-map sidebar item listening and responding (through CSS with focus) to the corresponding marker click. This 2-way listener effect has been difficult to port through JQuery or just to incorporate natively in any recent store locator solutions. The desired functionality is:

When user clicks a marker or it's sidebar entry, existing highlights are cleared and the selected infowindow opens and corresponding sidebar item is identified in parallel...and vice versa.

What is the best practice for achieving this useful effect? Does anyone know of current examples integrating bi-directional triggers? How is the link best achieved between specific markers rendered from Google's servers and corresponding event listeners on the same page but outside of the map (eg, sidebar items). Should we be using any of JQuery's most recent (1.7) callback handling features? Are there better non-JQuery techniques?

Below is the "state-of-the-art" familiar snippet creating the Marker and InfoWindow on a Map() named 'map' and creating a sidebar row in a DIV named 'sidebar' with markerArray and markerBounds collecting the markers. The SidebarItem() constructor is called by the makeMarker() function from ESA 2009's excellent example:

 var infoWindow = new google.maps.InfoWindow();
 var markerBounds = new google.maps.LatLngBounds();
 var markerArray = [];

    function makeMarker(options){
    var pushPin = new google.maps.Marker({map:map});
    pushPin.setOptions(options);
    google.maps.event.addListener(pushPin, "click", function(){
      infoWindow.setOptions(options);
      infoWindow.open(map, pushPin);
      if(this.sidebarButton)this.sidebarButton.button.focus();
    });
    var idleIcon = pushPin.getIcon();
    if(options.sidebarItem){
      pushPin.sidebarButton = new SidebarItem(pushPin, options);
  pushPin.sidebarButton.addIn("sidebar");
}
markerBounds.extend(options.position);
markerArray.push(pushPin);
     return pushPin;
  }

google.maps.event.addListener(map, "click", function(){
  infoWindow.close();
});

function SidebarItem(marker, opts){
var tag = opts.sidebarItemType || "button";
var row = document.createElement(tag);
row.innerHTML = opts.sidebarItem;
row.className = opts.sidebarItemClassName || "sidebar_item";  
row.style.display = "block";
row.style.width = opts.sidebarItemWidth || "120px";
row.onclick = function(){
google.maps.event.trigger(marker, 'click');
}
row.onmouseover = function(){
google.maps.event.trigger(marker, 'mouseover');
}
row.onmouseout = function(){
google.maps.event.trigger(marker, 'mouseout');
}
this.button = row;
}
// adds a sidebar item to a 

SidebarItem.prototype.addIn = function(block){
if(block && block.nodeType == 1)this.div = block;
else
this.div = document.getElementById(block)
|| document.getElementById("sidebar")
|| document.getElementsByTagName("body")[0];
this.div.appendChild(this.button);
}
// deletes a sidebar item
SidebarItem.prototype.remove = function(){
if(!this.div) return false;
this.div.removeChild(this.button);
return true;
}

SidebarItem() and makeMarker() are public domain functions but they have been stubbornly difficult for newbies like me to understand, adopt and integrate. Any advice or current examples would be appreciated. Specifically, is the ESA 2009 approach obsolete? I am not finding recent usage of this strategy. What is the best modern way to associate non-map DOM elements with specific Google Map markers?

Thanks in advance...

I don't think there's any magic in what you are trying to achieve but you do need to be aware of variable scope. The easiest approach is to declare your map markers and sidebar entries, and define their event handlers, in the same scope (eg. in an onload handler) so they can address each other. I haven't been through your code in detail so you may already be OK in this regard.

You might also like to try working with .triggerHandler() rather than .trigger() otherwise there's a possibility that A will trigger B and B will immediately trigger A etc. etc. If so, then the call stack may fill up or the browser may just seize.


EDIT:

Here is something similar, taken from an application in which Google map markers and corresponding external links are all given mouseover and mouseout handlers for mutual highliting. The whole application is several thousands of lines long and organised into namespaces, each with a capitalised name (eg. GOOGLEMAP , DATA ).

You will see that the data structure DATA.locationData is key to the interaction between the markers and external links. It allows handlers to be attached in different namespaces (ie. different scopes) to links and markers.

Namespace "GOOGLEMAP" (simplified) :

var GOOGLEMAP = (function(){//NAMESPACE pattern
    //...
    var mouseoverLocMarker_closure = function(loc) {
        return function() {
            $(loc.link).addClass('hilight');
        };
    };
    var mouseoutLocMarker_closure = function(loc) {
        return function() {
            $(loc.link).removeClass('hilight');
        };
    };
    //...
    var init = function(...) {
        //...
        for(var name in DATA.locationData) {
            //...
            var loc = DATA.locationData[name];//lookup in a large hardcoded data structure in the DATA namespace
            loc.marker = new google.maps.Marker({ map:map, icon:'images/symbols/green.gif', zIndex:0 });//makes the marker available in other scopes
            //Here we attach functions returned by "_closure" functions, in order to correctly remember loc.
            google.maps.event.addListener( loc.marker, 'mouseover', mouseoverLocMarker_closure(loc) );
            google.maps.event.addListener( loc.marker, 'mouseout', mouseoutLocMarker_closure(loc) );
            //...
        }
    };
    //...
})();

A jQuery "document ready" closure (simplified) :

$(function(){
    $('#towns a.location').each(function(){
        //...
        var loc = DATA.locationData[name];//lookup in a large hardcoded data structure in the DATA namespace
        if(loc){
            //...
            $this.mouseover(function(){
                if(loc.marker) {
                    loc.icon = loc.marker.getIcon();
                    loc.marker.setIcon('images/symbols/red.gif');
                }
            });
            $this.mouseout(function(){
                if(loc.marker) {
                    loc.marker.setIcon(loc.icon);
                }
            });
            loc.link = this;//makes the link available to other scopes
        }
        else {
            //...
        }
    });
    //...
});

I can't honestly say that this code is exemplary - it could probably be more efficient of memory - but it is well organised and thoroughly reliable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM