Search code examples
javascriptjsfprimefacesgeolocation

Pass geolocation JavaScript values to a Bean


I have to pass geolocation values got by using html5 geolocation to my managed bean ItemMb, here is my code to clarify things and i don't really know how to achieve this.

My managed bean

public class ItemMb {

    private Item item = new Item();

    // get/set
}

My dto Item

public class Item {

//  private Double idCollect;
    // login et password
    private Double lat;
    private Double lon;
    private Double accuracy;
    private String photo;
    private String remark;

    public Item(){
    }
// getters and setters

Here is my .js file where i got geolocations values and innertext them in some primefaces tags

window.watchID = navigator.geolocation.watchPosition(function(position){              

      document.getElementById("xCurrentPosition").innerHTML = (Math.round(position.coords.latitude*100) / 100);
      document.getElementById("yCurrentPosition").innerHTML = (Math.round(position.coords.longitude*100) / 100);
      document.getElementById("accuracyCurrentPosition").innerHTML = position.coords.accuracy;    

      });

Now i want to pass those JavaScript generated geolocation values to my managed bean ItemMb. If you need more informations feel free to ask.


Solution

  • I've finally found the answer, i will let it there in case if someone has the same problem. You have to follow these steps:

    1) Define a primefaces remoteCommand

    <p:remoteCommand name="myRemoteCommand" process="@this" autoRun="false" actionListener="#{myMb.myListener}"/>
    

    2) Call the command in your JavaScript code

    myRemoteCommand ([{name:'paramName1',   value: 'paramValue1'}, {name:'paramName2',     value: 'paramValue2'}, …]);
    

    3) In the backing bean use this method

    void myListener(){
                    String param1 = (String) FacesContext.getInstance().getExternalContext().getRequestParameterMap().get("paramName1");
                    …
    }