Refresh primefaces gmap markers in javascript - javascript

I need to refresh, add new markers or remove markers on a primefaces gmap.
By a callBackParam I pass the markers to a javascript in xhtml.
However when the map refreshes, the event overlaySelect is never fired.
ManageBean scope is viewScoped
public void ajaxPoll() {
Marker[] newMarkers = new Marker[mapLoadModel.getMarkers().size()];
for(int i=0;i < newMarkers.length;i++){
newMarkers[i]=mapLoadModel.getMarkers().get(i);
}
RequestContext.getCurrentInstance().addCallbackParam("newMarkers",new Gson().toJson(newMarkers));
logger.info("refresco marcadores");
}
The javascript:
//<![CDATA[
function handleComplete(xhr, status, args){
var gmap = PF('gMapWV').getMap();
for(var i in gmap.markers)
{
gmap.markers[i].setMap(null);
}
gmap.markers.length=0;
var newMarkers = eval('(' + args.newMarkers + ')');
for(var i in newMarkers)
{
var newMarker = newMarkers[i];
var marker = new google.maps.Marker({
id: newMarker.id,
map: gmap,
position: newMarker.latlng,
icon:newMarker.icon,
title:newMarker.title,
clickable:true
});
}
}
// ]]>
And the map:
<p:poll interval="#{manageLoadExecution.refreshInterval}" listener="#{manageLoadExecution.ajaxPoll}" oncomplete="handleComplete(xhr, status, args)" process="#this" />
<p:gmap widgetVar="gMapWV" id="gMapWV" center="#{manageLoadExecution.latitude} , #{manageLoadExecution.longitude}" zoom="#{manageLoadExecution.zoomLevel}" fitBounds="false" type="terrain" model="#{manageLoadExecution.mapLoadModel}" disableDefaultUI="false" styleClass="map" >
<p:ajax event="overlaySelect" listener="#{manageLoadExecution.onMarkerSelect}" />
<p:gmapInfoWindow id="infoWindow" maxWidth="400" >
<p:outputPanel style="text-align: left; display: block; margin: auto; width:370px" >
After refresh the markers are show on screen, but the overlaySelect event is never fired and the infowindow is not open.
I guess that removing all the markers I'm removing some that makes the event not fires.
Please, any help!
Thank you very very much.

I made it!
I missed to add an id the the new marker in javascript scriptlet.
Finally in javascript code I call _render() method to configure markers and listeners.
Here is the javascript scriptlet:
<script>
//<![CDATA[
function handleComplete(xhr, status, args){
var gmap = PF('gMapWV').getMap();
var newMarkers = eval('(' + args.newMarkers + ')');
for(var i in gmap.markers)
{
var oldMarker = gmap.markers[i];
var newMarker = newMarkers[i];
if(newMarker != null){
oldMarker.setPosition(newMarker.latlng);
oldMarker.title=newMarker.title;
oldMarker.setMap(gmap);
oldMarker.id=newMarker.id;
}else{
oldMarker.setMap(null);
}
}
var oldMarkersLength = gmap.markers.length;
var newMarkersLength = newMarkers.length;
for(var i = oldMarkersLength;i < newMarkersLength;i++)
{
var newMarker = newMarkers[i];
var marker = new google.maps.Marker({
position: newMarker.latlng,
title:newMarker.title,
clickable:true,
id:newMarker.id
});
gmap.markers[i]= marker;
}
PF('gMapWV').addOverlays(gmap.markers);
PF('gMapWV')._render();
}
// ]]>
</script>
If the list decrease the size I set the remain markers to null to reuse then if I need it.
I hope this can help anyone stuck with gmap and primefaces.
Thanks everyone for suggestions

Try to do this, it work to me (for those don't want refresh the map):
var gmap = PF('gmap').getMap();
var marker = new google.maps.Marker({
id: json.id,
map: gmap,
position: json.latlng,
icon: json.icon,
title: json.title,
draggable: true,
clickable:true
});
gmap.markers[gmap.markers.length] = marker;
PF('gmap').addOverlay(marker);
PF('gmap').configureMarkers();
PF('gmap').addOverlays(gmap.markers);

Related

Unable to add url to google maps click event

I'm stuck on this problem, no matter what I have tried, I cannot add a url to the google maps marker.
Can anyone with more experience than me please help with this problem.
Currently, if I click the marker, I'm taking back to the home page, what I want is to go to this url '/Hotel/Full-Details?=#item.DisplayHotelName&propId=#item.HotelId'which is in the foreach loop.
I have looked at
google map api: open url by clicking at marker
Google Map marker url
and other but i'm stuck
My code is:
<script type="text/javascript">
$(function() {
var map;
var markersArray = [];
var image = 'img/';
var bounds = new window.google.maps.LatLngBounds();
var loc;
//var pageUrl;
var mapOptions = { mapTypeId: window.google.maps.MapTypeId.ROADMAP };
map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
#foreach (var item in Model.DisplayHotelPaging)
{
<text> loc = new google.maps.LatLng(#item.Latitude, #item.Longitude);
bounds.extend(loc);
addMarker(loc, '#item.DisplayHotelName #item.Address1 #item.PostalCode', "active",'/Hotel/Full-Details?=#item.DisplayHotelName&propId=#item.HotelId')
</text>
}
map.fitBounds(bounds);
map.panToBounds(bounds);
//for (var i = 0; i < window.addMarker.length; i++) {
function addMarker(location, name, active) {
//var page = loc[i];
var marker = new google.maps.Marker({
position: location,
map: map,
title: name,
status: active,
icon: '/Images/property1.png',
url: '/'//page[3]
});
// }
window.google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
}
});
</script>
Thanks for any help
I believe you need to add the URL to your addMarker function like so:
function addMarker(location, name, active, markerUrl) {
//var page = loc[i];
var marker = new google.maps.Marker({
position: location,
map: map,
title: name,
status: active,
icon: '/Images/property1.png',
url: markerUrl
});
// }
window.google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
}
Currently you hard-coded '/' as your URL which would take you to your home page.

Google InfoWindow not loading inside for loop

I have add the following code to a Google Map on a site of mine. The map contains many points pulling from coordinates set in the WordPress backend.
I also want to include some static points which will always stay on the map and am hardcoding their coordinates.
The following is the code I am using and what happens is that the code displays the first marker but not the infobox. Because of this, the code stops and does not continue through the for loop. The issue is at the return function() bit, but I am not sure how to get it working.
var infowindow = new google.maps.InfoWindow({maxWidth: 185});
var setMarker;
var setMarkers = new Array();
var setLocations = [
['<h4>Location1</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/airport_icon.png'],
['<h4>Location2</h4>', 53.3461,-6.2969, '/wp-content/themes/path/to/train_icon.png'],
['<h4>Location3</h4>', 53.3532,-6.2468, '/wp-content/themes/path/to/train_icon.png'],
['<h4>Location4</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/dvc_icon.png'],
['<h4>Location5</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/dvc_icon.png'],
];
for (var i = 0; i < setLocations.length; i++) {
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(setLocations[i][1], setLocations[i][2]),
icon : setLocations[i][3],
});
setMarkers.push(setMarker);
google.maps.event.addListener(setMarker, 'click', (function(setMarker, i) {
return function() {
infowindow.setContent(setLocations[i][0]);
infowindow.open(map, setMarker);
}
})(setMarker, i));
}
Define your setMarker variable inside the for loop and push it to your markers array:
for (var i = 0; i < setLocations.length; i++) {
var setMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(setLocations[i][1], setLocations[i][2])
});
google.maps.event.addListener(setMarker, 'click', (function (setMarker, i) {
return function () {
infowindow.setContent(setLocations[i][0]);
infowindow.open(map, setMarker);
}
})(setMarker, i));
setMarkers.push(setMarker);
}
JSFiddle demo

Declaring google map markers in a loop

I have a weird issue with event listeners on google map markers. Basically I want to declare a bunch of markers in a loop, and have each marker have an associated infowindow. The relevant code is:
var markers=[];
var contents = [];
var infowindows = [];
for (i = 0; i < 10; i++) {
markers[i] = new google.maps.Marker({
position: new google.maps.LatLng(40+Math.random()*5, 4+Math.random()*5),
map: map,
title: 'samplemarker'
});
contents[i] = '<div class="popup_container">' +
'</div>';
infowindows[i] = new google.maps.InfoWindow({
content: contents[i],
maxWidth: 300
});
google.maps.event.addListener(markers[i], 'click', function() {
infowindows[i].open(map,markers[i]);
map.panTo(markers[i].getPosition());
});
}
The markers are created correctly, and the infowindows too, since if I do manually infowindows[i].open(map,markers[i]); they are opened correctly. However the listener does not work.
Even weirder: I have another marker, "marker_1" declared outside of the for loop, exactly the same way. If I write:
google.maps.event.addListener(marker_1, 'click', function() {
infowindows[0].open(map,markers[0]);
map.panTo(markers[0].getPosition());
});
The infowindow 0 is opened and the map is panned to marker 0 when marker_1 is clicked. However when writing, at the exact same position, the same lines except for marker_1 replaced with markers[0], a click on the marker 0 has no effect at all.
Thanks for any help and sorry if it's something stupid!
Inside your onclick handler, you don't already have that i value, in your case it would always take last value of i after the end of the loop, i.e 10, and markers[10] doesn't exist as you only have 10 markers.
To make it work you can e.g. add additional property to your markers in array, that would store marker index and use it inside your onlick handler
var markers=[];
var contents = [];
var infowindows = [];
for (i = 0; i < 10; i++) {
markers[i] = new google.maps.Marker({
position: new google.maps.LatLng(40+Math.random()*5, 4+Math.random()*5),
map: map,
title: 'samplemarker'
});
markers[i].index = i; //add index property
contents[i] = '<div class="popup_container"></div>';
infowindows[i] = new google.maps.InfoWindow({
content: contents[i],
maxWidth: 300
});
google.maps.event.addListener(markers[i], 'click', function() {
console.log(this.index); // this will give correct index
console.log(i); //this will always give 10 for you
infowindows[this.index].open(map,markers[this.index]);
map.panTo(markers[this.index].getPosition());
});
}
see corrected example

Remove marker from Google Maps API V3

I have a map where I want to add a marker (with info window) via a checkbox. It also works quite well, but I just can not get it deleted again when I uncheck the checkbox. Can anyone help?
See also here: http://jsfiddle.net/x8D7y/
function clearOverlays() {
google.maps.event.clearListeners(marker300, 'click');
}
function showOverlays() {
var marker300 = new google.maps.Marker({
position: new google.maps.LatLng(45.0, 1.0),
map: map /*,
icon: 'img/bike5.png' */
});
var infowindow300 = new google.maps.InfoWindow({
content: '<div style="width: 200px;">Test 300 - Link</div>'
});
google.maps.event.addListener(marker300, 'click', function() {
infowindow300.open(map, marker300);
});
}
You have to use an external Array which holds the extra markers you use with the map. In your case I have added the following array:
var extraMarkers = [];
Then when I click the checkbox, I am getting the ID of that checkbox, and send it in both showOverlays() and clearOverlays() as function argument.
Then, in showOverlays(), I am using the checkbox ID as extraMarkers key and the marker as value.
Finally, in clearOverlays() I use again the checkbox ID to get the element with this ID from the extraMarkers array and I see the map to null, in order to remove the marker.
See here the working example : http://jsfiddle.net/x8D7y/1/
Here is the full code required by you:
var map;
var extraMarkers = [];
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(45.0, 1.0)
};
map = new google.maps.Map($('#map')[0], myOptions);
var marker1 = new google.maps.Marker(
{
position: new google.maps.LatLng(45.5, 1.5),
map: map /*,
icon: 'img/bike5.png' */
}
);
var infowindow1 = new google.maps.InfoWindow(
{
content: '<div style="width: 200px;">Test 1 - Link</div>'
}
);
google.maps.event.addListener(
marker1,
'click',
function()
{
infowindow1.open(map, marker1);
}
);
function clearOverlays(myID)
{
google.maps.event.clearListeners(extraMarkers[myID], 'click');
extraMarkers[myID].setMap(null);
}
function showOverlays(myID)
{
var marker300 = new google.maps.Marker(
{
position: new google.maps.LatLng(45.0, 1.0),
map: map /*,
icon: 'img/bike5.png' */
}
);
extraMarkers[myID] = marker300;
var infowindow300 = new google.maps.InfoWindow(
{
content: '<div style="width: 200px;">Test 300 - Link</div>'
}
);
google.maps.event.addListener(
marker300,
'click',
function()
{
infowindow300.open(map, marker300);
}
);
}
$('#mapall').change(
function()
{
var myID = $(this).attr('id');
if($('#mapall').attr('checked'))
{
showOverlays(myID);
}
else
{
clearOverlays(myID);
}
}
);
if you have single marker on map then use marker.setMap(null);
if Multiple marker make an array for marker
markersArray.push(marker);
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
Try this:
marker300.setMap(null);
Your marker was not visible outside of showOverlays() function. Error was reported in console:
Uncaught ReferenceError: marker300 is not defined
Minimum change is to define marker300 as global:
var map;
var marker300;
and delete marker in
function clearOverlays() {
google.maps.event.clearListeners(marker300, 'click');
marker300.setMap(null);
}
and remove var in front of variable marker300 in function showOverlays()
See example in fiddle
If you want to have several markers than you will have to follow solution from user Merianos Nikos

Google Maps Zoom and Description dialog not working right

Well I'm having a couple problems getting google maps to work using the v3 API.
Look here: [Removed by Poster]
Both maps are, in fact, working but the zoom level seems like it is random. The zoom is set to 12 when the map is initialized. Also, if you click on the marker, the description box is missing corners and is unable to be closed. Here is the javascript functions I am using to activate these maps:
var mapHash = [];
var bound = new google.maps.LatLngBounds();
finishedCoding = false;
function initMap(map_container_div,lat,lng) {
var latlng = new google.maps.LatLng(lat,lng);
var myOptions = {
zoom:12,
center:latlng,
mapTypeId:google.maps.MapTypeId.ROADMAP,
streetViewControl: false
};
var map = new google.maps.Map(document.getElementById(map_container_div), myOptions);
if (!getMap(map_container_div)) {
var mapInfo = {
mapkey:'',
map:'',
geocoder : new google.maps.Geocoder()
};
mapInfo.map = map;
mapInfo.geocoder = new google.maps.Geocoder();
mapInfo.mapKey = map_container_div;
mapHash.push(mapInfo);
}
}
function placeMarker(myAddress, mapId, description, title) {
mapIndex = getMap(mapId)
//alert(myAddress + mapId + map)
mapHash[mapIndex].geocoder.geocode({
'address':myAddress
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
mapIndex = getMap(mapId)
var marker = new google.maps.Marker({
map:mapHash[mapIndex].map,
position:results[0].geometry.location,
title: title
});
bound.extend(results[0].geometry.location);
mapHash[mapIndex].map.fitBounds(bound);
finishedCoding = true;
placeDesc(marker,description,mapId);
}
});
}
function placeDesc(marker,myDesc,mapId) {
mapIndex = getMap(mapId);
var infowindow = new google.maps.InfoWindow({
content: myDesc
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(mapHash[mapIndex],marker);
});
}
function getMap(mapKey) {
for (var i = 0 ; i < mapHash.length ; i++) {
if (mapHash[i].mapKey == mapKey) {
return i;
}
}
return false;
}
function startmap(mapidd,address,description,title,lat,lng) {
initMap(mapidd,lat,lng)
placeMarker(address,mapidd,description,title)
}
by just removeing
body img {
max-width: 520px !important;
height: auto !important;}
from style sheet
http://www.wppassport.com/wp-content/plugins/easyfanpagedesign/default.theme/style.css
your problem is resolved now
Your dialog boxes aren't closing because of a javascript error.
Something is wrong with infowindow.open(mapHash[mapIndex],marker); inside your click listener. It's displaying the window, which makes you think that the error is happening after, but I'm pretty sure it's in the call itself. When I debugged you weren't making an obvious mistake, but I still think that that line of code is the culprit.
I solved this issue myself and am kicking myself for not thinking of this. :)
Just had to add mapHash[mapIndex].map.setZoom(12);
And I removed the following 2 codes:
bound.extend(results[0].geometry.location);
mapHash[mapIndex].map.fitBounds(bound);

Categories