Automatically Opening an Info Window On Google Map (JSF2 Bean)
February 18th, 2012
Currently I am working on a project with Primefaces and started out utilising the gmap component, but could not find a way to automatically open a marker info window. Basically I wanted it to be a company contact page, get a google map and open a box with the company info. Like this :-
To do this, firstly I created the JSF page in which it grabs values from a ManagedBean and inserts them to javascript variables (var). Once done it then loads the gmap.js javascript file detailed below. Finally as part of the h:body tag I have triggered an onload event.
mypage.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<f:view xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ez="http://java.sun.com/jsf/composite/ezcomp">
<h:head>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
//Define the company details here before calling the gMap//
var companyName = '#{ApplicationBean.companyName}';
var companyAddress = '#{ApplicationBean.companyAddressHTML}';
var companyLat = #{ApplicationBean.companyLat};
var companyLong = #{ApplicationBean.companyLong};
var companyFax = '#{ApplicationBean.companyFax}';
var companyTel = '#{ApplicationBean.companyFax}';
var companyEmail = '#{ApplicationBean.companyEmail}';
</script>
<script src="#{facesContext.externalContext.context.contextPath}/resources/javascript/gmap.js" type="text/javascript"></script>
</h:head>
<h:body onload="gMapInitialize()">
<div id="map" style="width:100%; height:100%"></div>
</h:body>
</f:view>
</html>
Finally we have the gmap.js that deals with the googleMaps API v3. “The infowindow.open(map,marker);” triggers the opening of the window without a user click.
gmap.js
function gMapInitialize() {
var gMapLatlng = new google.maps.LatLng(companyLat, companyLong);
var gMapOptions = {
center: new google.maps.LatLng(54.145921, -0.799813),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), gMapOptions);
var marker = new google.maps.Marker({
position: gMapLatlng,
map: map,
title: companyName
});
var contentString = '<div id="content">'+
'<h2>' + companyName + '</h2>'+
'<div id="bodyContent">'+ companyAddress + '<BR/>' +
'<b>TEL : ' + companyTel + ' FAX : ' + companyFax + '<BR/>' +
'EMAIL : <a href="mailto:' + companyEmail +'">' + companyEmail + '</a></b>' +
'</div></div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
infowindow.open(map,marker);
}
Categories: Java
