It is possible to add markers onto the map via a data model and then select or drag it by interacting with the map.
The marker should be an instance of org.primefaces.model.map.Marker
. Markers can be easily constructed by providing an instance of org.primefaces.model.map.LatLng
to define their position. The latitude
and longitude
values could be provided to the LatLng
class as constructor parameters. Markers will be added to the data model via the addOverlay
method. This is shown in the following code:
MapModel markerModel = new DefaultMapModel(); markerModel.addOverlay(new Marker(new LatLng(41.073399, 29.051971), "Bosphorus")); markerModel.addOverlay(new Marker(new LatLng(41.118418, 29.134026), "Bosphorus"));
The attributes of org.primefaces.model.map.Marker
are listed in the following table:
Property |
Default |
Type |
Description |
---|---|---|---|
|
|
|
This is the text to display on rollover |
|
|
|
This is the location of the marker |
|
|
|
This is the foreground image of the marker |
|
|
|
This is the shadow image of the marker |
|
|
|
This is the cursor to display on rollover |
|
|
|
This defines whether the marker can be dragged |
|
|
|
This defines whether the marker can be clicked |
|
|
|
This is the shadow image not displayed when set to |
|
|
|
This defines the visibility of the marker |
The gmap
component offers the overlaySelect
and markerDrag
AJAX behavior events to handle the selection and dragging of the markers placed on the map.
The definition of <p:ajax>
, along with the listener method, is given here:
<p:gmap ...> <p:ajax event="overlaySelect" listener="#{mapBean.onMarkerSelect}" update="growl" /> </p:gmap> public void onMarkerSelect(OverlaySelectEvent event) { Marker selectedMarker = (Marker) event.getOverlay(); MessageUtil.addInfoMessageWithoutKey(selectedMarker.getTitle(), selectedMarker.getLatlng().toString()); }
To have draggable markers, each marker's draggable
attribute should be set to true
first. Then, the definition of <p:ajax>
, along with the listener method, can be performed, as shown here:
<p:gmap ...> <p:ajax event="markerDrag" listener="#{mapBean.onMarkerDrag}" update="growl" /> </p:gmap> public void onMarkerDrag(MarkerDragEvent event) { MessageUtil.addInfoMessage("marker.dragged", event.getMarker().getLatlng().toString()); }
This recipe is available in the demo web application on GitHub (https://github.com/ova2/primefaces-cookbook/tree/second-edition). Clone the project if you have not done it yet, explore the project structure, and build and deploy the WAR file on application servers compatible with Servlet 3.x, such as JBoss WildFly and Apache TomEE.
The showcase for the recipe is available at http://localhost:8080/pf-cookbook/views/chapter9/mapMarkers.jsf
.