Search code examples
google-mapsgoogle-maps-api-3primefacesprimefaces-gmap

ContextMenu in GMap primefaces component


Does anybody know how to create a primefaces contextmenu that will be launched on right click on GMap?

Normally the code should look like this:

<p:gmap id="gmapElement" widgetVar="gmtls" center="41.381542, 2.122893" zoom="15" type="hybrid" styleClass="mapClass"/>
<p:contextMenu for="gmapElement" >  
    <p:menuitem value="Method A" onclick="method1()" />  
    <p:menuitem value="Method B" onclick="method2()" />  
</p:contextMenu>  

However, google api overrides right click event. I think that the best way to handle it is additional listener in google map. But I cannot find any information how to show the context menu programatically:

var mapComponent = gmtls.getMap();
google.maps.event.addListener(mapComponent, 'rightclick', function(mouseEvent) {
    //show context menu at coordinates: mouseEvent.latLng
});

Can someone tell me what should I put in the listener body?


Solution

  • So here is the answer I was looking for. During initialisation of GMap component additional listener in google maps API must be registered:

    var mapComponent = gmtls.getMap();
    google.maps.event.addListener(mapComponent, 'rightclick', function(mouseEvent) {
        $(PrimeFaces.escapeClientId('mainForm:contextMenu')).css({
            top: yPos+'px',
            left: xPos+'px'                        
        }).show();
    });
    

    The easiest way to get coordinates (yPos, xPos) is to use jQuery which listen on mouseMove event:

    var xPos = 0;
    var yPos = 0;
    jQuery(document).ready(function(){
        $(document).mousemove(function(e){
            xPos = e.pageX;
            yPos = e.pageY;
        }); 
    })