Open Google Maps InfoWindow based on certain criteria - google-maps

I want to open a Google Maps InfoWindow based on whether or not one of my buildings is throwing a building alarm. The buildings I have the markers on all have alarm states (on or off), and if they are in alarm state, I am changing the color of the marker to yellow or red, depending on the severity of the alarm. When the alarms are "red" alarms, the marker is animated with the google.maps.Animation.BOUNCE effect.
The bounce effect is sometimes not enough to garner attention (we leave this screen open on a wall, and the data in the $(this).children(".alarm-count") div below changes dynamically due to another script we have running on the site in the background.
I already know how to change the markers based on the alarm state, can I also open an InfoWindow within the same condition? I have tried this:
google.maps.event.addListener(map,'idle',(function(marker,i){
return function(){
infowindow.setContent(
'<div class="infowindow-inner">'+
'<a href="'+bldgGfx[i]+'" onclick="window.open('+bldgGfx[i]+');return false;" target="_blank" title="'+bldgName[i]+' ('+bldgAddr[i]+')">'+
'<h2>'+bldgName[i]+'</h2>'+
'<h4>'+bldgAddr[i]+'</h4>'+
'<p>'+mainMeter[i]+' kW</p>'+
'<p>'+alarmCount[i]+' Alarms</p>'+
'</div>'
);infowindow.open(map,marker);
}
})(marker,i));
but it doesn't seem to be working.
The long and short of it is I need to evaluate one value per marker in my page, and open (or not open) the InfoWindow for each building based on that value.
Here is my code:
$(".building").each(function(i){
bldgNo[i] = $(this).children(".bldg-no").html().slice(1);
bldgName[i] = $(this).children(".bldg-name").html();
bldgAddr[i] = $(this).children(".bldg-address").html();
bldgGfx[i] = $(this).children(".bldg-graphic").html();
mainMeter[i] = $(this).children(".main-meter").html();
alarmCount[i] = $(this).children(".alarm-count").html();
latitude[i] = $(this).children(".latitude").html();
longitude[i] = $(this).children(".longitude").html();
if (alarmCount[i]!="N/A"){alarmCount[i]=alarmCount[i].slice(0,-3);}
if (alarmCount[i]>"0" && alarmCount[i]!="N/A"){
marker=new google.maps.Marker({position:new google.maps.LatLng(latitude[i],longitude[i]),map:map,shadow:shadow,icon:redIcon,title:bldgName[i]+" \n"+bldgAddr[i],optimized:false});marker.setAnimation(google.maps.Animation.BOUNCE);
////
//// THE COMMAND TO OPEN THE INFOWINDOW WILL GO HERE, RIGHT?
////
}
else if ($(this).hasClass("new")||(mainMeter[i]=="N/A")||(!isNumber(mainMeter[i]))) {
marker=new google.maps.Marker({position:new google.maps.LatLng(latitude[i],longitude[i]),map:map,shadow:shadow,icon:yellowIcon,title:bldgName[i]+" \n"+bldgAddr[i],optimized:false});marker.setAnimation(google.maps.Animation.NULL);}
else {
marker=new google.maps.Marker({position:new google.maps.LatLng(latitude[i],longitude[i]),map:map,shadow:shadow,icon:greenIcon,title:bldgName[i]+" \n"+bldgAddr[i],optimized:false});marker.setAnimation(google.maps.Animation.NULL);}
markersArray.push(marker);
google.maps.event.addListener(marker,'click',(function(marker,i){
return function(){
infowindow.setContent(
'<div class="infowindow-inner">'+
'<a href="'+bldgGfx[i]+'" onclick="window.open('+bldgGfx[i]+');return false;" target="_blank" title="'+bldgName[i]+' ('+bldgAddr[i]+')">'+
'<h2>'+bldgName[i]+'</h2>'+
'<h4>'+bldgAddr[i]+'</h4>'+
'<p>'+mainMeter[i]+' kW</p>'+
'<p>'+alarmCount[i]+' Alarms</p>'+
'</div>'
);infowindow.open(map,marker);
}
})(marker,i));
i++;
});

Since many buildings may be "on alert", you'll want a InfoWindow array (in my demo it's a global because I use an inline call); however, the screen may get cluttered very easily. I wrote a Z-Index routine to bring a clicked InfoWindow to front. You might also want to consider MarkerWithLabel or InfoBubble because in my opinion they look better than the vanilla InfoWindow.
Please see the demo
demo side-by-side with code
I'll only copy some of the parts that are very different.
var infowindows = [];
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// MANY LINES SKIPPED
// ...
$(this).children(".longitude").html();
infowindows[i] = new google.maps.InfoWindow({
content:'<div class="infowindow"
onclick="bringToFront('+i+')">'+bldgName[i]+'</div>'});
if (alarmCount[i]>0 && alarmCount[i]!="N/A"){
// marker=new google.maps.Marker({position:new google.maps.LatLng(latitude[i],longitude[i]),map:map,shadow:shadow,icon:redIcon,title:bldgName[i]+" \n"+bldgAddr[i],optimized:false});marker.setAnimation(google.maps.Animation.BOUNCE);
marker = new google.maps.Marker({position:new google.maps.LatLng(latitude[i],longitude[i]),map:map,title:"red"});
infowindows[i].open(map,marker);
//// THE COMMAND TO OPEN THE INFOWINDOW WILL GO HERE, RIGHT?
}
...
google.maps.event.addListener(marker,'click',(function(marker,i){
return function(){
infowindows[i].open(map,marker);
bringToFront(i);
}
})(marker,i));
});
}
function bringToFront(windowIndex) {
console.log(windowIndex);
for (var i = infowindows.length-1, n = 0; i >= n; i--) {
infowindows[i].setZIndex(0);
}
infowindows[windowIndex].setZIndex(1);
}

Related

Bring GoogleMaps InfoWindow to front

I have a GoogleMaps APIv3 application in which multiple InfoWindows can be open at any one time. I would like to be able to bring an obscured InfoWindow to the front of all other InfoWindows if any part of it is clicked - similar to the behaviour of windows in MS Windows OS.
I had thought to add an onclick event handler which increases the z-index of the InfoWindow, but the event handler does not appear to be firing.
ZIndex is a global variable that keeps increasing as InfoWindows are clicked - or thats the theory anyway.
Can anyone help ?
Here is my code:-
var ZIndex=1;
var iw = new google.maps.InfoWindow({ content:contentString });
google.maps.event.addListener(iw, 'click', handleInfoWindowClick(iw) );
function handleInfoWindowClick(infoWindow) {
return function() {
infoWindow.setZIndex(ZIndex++);
}
}
there is no click-event for an infoWindow, it's a little bit more difficult.
you'll need to use an element(not a string) as content for the infowindow, because you need a DOMListener instead a listener for the infowindow-object
when domready-fires, you must apply the click-DOMListener to the anchestor of this content-node that defines the infowindow
The following code will do this for you, add this to your page:
google.maps.InfoWindowZ=function(opts){
var GM = google.maps,
GE = GM.event,
iw = new GM.InfoWindow(),
ce;
if(!GM.InfoWindowZZ){
GM.InfoWindowZZ=Number(GM.Marker.MAX_ZINDEX);
}
GE.addListener(iw,'content_changed',function(){
if(typeof this.getContent()=='string'){
var n=document.createElement('div');
n.innerHTML=this.getContent();
this.setContent(n);
return;
}
GE.addListener(this,'domready',
function(){
var _this=this;
_this.setZIndex(++GM.InfoWindowZZ);
if(ce){
GM.event.removeListener(ce);
}
ce=GE.addDomListener(this.getContent().parentNode
.parentNode.parentNode,'click',
function(){
_this.setZIndex(++GM.InfoWindowZZ);
});
})
});
if(opts)iw.setOptions(opts);
return iw;
}
Instead of google.maps.InfoWindow() you must call now google.maps.InfoWindowZ()
It also returns a genuine InfoWindow, but with the mentioned listener applied to it. It also creates the node from the content when needed.
Demo: http://jsfiddle.net/doktormolle/tRwnE/
Updated version for visualRefresh(using mouseover instead of click) http://jsfiddle.net/doktormolle/uuLBb/

How can watch my position when I close my App with Phonegap and jquerymobile

I am using phonegap, jquerymobile the googlemap API to get my current position and to watch my position.
For this, when I lunch my map page, my position is shown with a marker and the marker move when I move.
Even if it works excpeted when I close my App (onPause).
Here is my code (you can tell me how I can perfect it :o) )
$('#home').live("pagebeforeshow", function() {
if($('#googleAPI').length != 0){
navigator.geolocation.getCurrentPosition(function(position){
//showMap('mapHome',position.coords.latitude, position.coords.longitude);// Canvas, lat, long
var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
// Google Map options
var myOptions = {
zoom: 17,
//zoomControl : 1,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP////ROADMAP, SATELLITE, HYBRID and TERRAIN
};
// Create the Google Map, set options
Tracking.mapy = new google.maps.Map(document.getElementById('mapHome'), myOptions);
//addMarker(position.coords.latitude,position.coords.longitude);
},
showError,
{
enableHighAccuracy : true,
maximumAge : 2000
//maximumAge:Infinity
});
}
})
$('#home').live("pageshow", function() {
// Place and move the marker regarding to my position and deplacement
if($('#googleAPI').length != 0){
//var track_id = "me";
Tracking.watch_id = navigator.geolocation.watchPosition(
// Success
function(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latLng = new Array();
latLng[0] = lat;
latLng[1] = long;
//Tracking.myCoordinates.push(lat,long);
Tracking.myCoordinates.push(latLng);
addMarker(lat, long);
},
// Error
showError,
{
frequency: 1000
});
console.log('HW : WatchPosition called. Id:' + Tracking.watch_id);
}else{
Alert.show('The map API has not been loaded. Check for connection and try again. (pagebeforeshow)');
}
})
$('#home').live("pagebeforehide", function() {
if($('#googleAPI').length != 0){
//track_id = "me";
// Stop tracking the user
if (Tracking.watch_id != null) {
navigator.geolocation.clearWatch(Tracking.watch_id);
console.log('HW : WatchPosition cancelled Id:' + Tracking.watch_id);
Tracking.watch_id = null;
}
//navigator.geolocation.clearWatch(Tracking.watch_id);
//Tracking.watch_id = null;
Tracking.myCoordinates = new Array();
}else{
Alert.show('The map API has not been loaded. Check for connection and try again. (pagebeforeshide)');
}
});
The problem is when I close my App, because I still need to be alert when I go outside of my geofence. Then, as lomg as I do not stop to watch my position, I need it to be watching even if I close my position or if I lunch another app.
Then I do not know how to do when I called that Phonegap even:
document.addEventListener('pause', onPause, false);
function onPause(){}
Should I simply relunch my watch code with a different watch_id?
Any suggestion?
Many thank and happy new year
I think what you're trying to get at is running a background process using phonegap. The discussion in this link seems to say that it's only possible if you write a plugin to perform that functionality. PhoneGap doesn't have an API to do it out of the box.
Executing javascript in background using phonegap

How to make the infowindow appear depending upon the space it already have and not move the map

I am displaying few locations in google maps. I refresh these locations if a user zoom in/out or drags the map. Now the issue is if i click on the marker of a location then the info window opens up and drags the map if it doesn't have any space to show. This dragging causes my locations to be refreshed and hence my marker vanishes.
I tried disableAutoPan: true but then the info window is not seen only. Is there any way that the info window auto adjust itself. is there any way to sort this out?
Use a global variable to indicate when the refresh should be ignored, for example:
// Global var
var ignoreRefresh = false;
google.maps.addListener(marker,'click', function(){
ignoreRefresh = true;
infoWindow.setContent('Hello');
infoWindow.open(map,marker);
})
function refresh(){
if (ignoreRefresh) {
ignoreRefresh = false;
return;
}
//...
//do your normal refresh of data
//...
}

How to get markers after calling drive directions in Google Maps API?

I just started working using Google Maps API yesterday, and trying to set up drive directions to my map. My problem is: when I call the function load,
// [...]
gdir = new GDirections(map, directionsPanel);
// [...]
gdir.load("from: " + fromAddress + " to: " + toAddress);
it returns a map whose markers are not draggable. So, I need to make them draggable in order to recalculate the directions, but I can't get the markers objects.
Someone knows how can I do it?
You need to add a handler on the GDirections object for the addoverlay event:
GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay);
When your onGDirectionsAddOverlay handler is called you can iterate through the new markers and replace them with draggable copies:
for (var i = 0; i <= gdir.getNumRoutes(); i++)
{
var originalMarker = gdir.getMarker(i);
latLngs[i] = originalMarker.getLatLng();
icons[i] = originalMarker.getIcon();
newMarkers[i] = new GMarker(latLngs[i], { icon: icons[i], draggable: true, title: 'Kan flyttes' });
map.addOverlay(newMarkers[i]);
// add stuff to your newMarkers[i] drag end event...
// ...
//Bind 'click' event to original markers 'click' event
copyClick(newMarkers[i], originalMarker);
// Now we can remove the original marker safely
map.removeOverlay(originalMarker);
}
You can find a working example of this here (source).

Customize Google Maps info window?

I'm working on a website of a client, a local church. I've embedded a Google Map using the Link feature on the Maps page. The info window on the map includes "Reviews," and the church is concerned about this. Is there a way to remove that from the info window? I don't want to remove any reviews themselves, just that link on the info window?
Is this possible? Are there any other customization options (besides the size) one can manipulate via the query string?
Nearly 2 years ago, I created a custom map with complete control over the contents of the bubble, using the API and some code manipulation. Click on the above link for a demo. I've cleaned up the code for this answer, although to implement you'll need to replace all YOUR__BLANK__HERE text with the appropriate values.
Step 1: Call the gMaps API
<script src="http://maps.google.com/maps?file=api&v=2&key=YOUR_API_KEY_HERE"
type="text/javascript">
</script>
Step 2: In the body of your document, create an element with id "map". Size and position it with CSS. It requires a height and width.
<div id="map" class="content"></div>
Step 3: After the div has been defined in the DOM, it is safe to insert the following script tag:
<script type="text/javascript">
//<![CDATA[
// Check to see if this browser can run the Google API
if (GBrowserIsCompatible()) {
var gmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];
var i=0;
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
// The info window version with the "to here" form open
to_htmls[i] = html +
'<br />Start address:<form action="http://maps.google.com/maps" method="get">' +
'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
'<INPUT value="Get Directions" TYPE="SUBMIT">' +
'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() +
// "(" + name + ")" +
'"/>';
// The inactive version of the direction info
html = html + '<br><a href="javascript:tohere('+i+')">Get Directions<'+'/a>';
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
gmarkers[i] = marker;
htmls[i] = html;
i++;
return marker;
}
// functions that open the directions forms
function tohere(i) {
gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
// Display the map, with some controls and set the initial location
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
YOUR_ZOOM_LEVEL_HERE // a value of 13 worked for me
);
// Set up one marker with an info window
var marker = createMarker(
new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
'YOUR_MARKER_NAME_HERE',
'<i>YOUR_HTML_HERE<'+'/i>');
/* repeat the process to add more markers
map.addOverlay(marker);
var marker = createMarker(
new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
'YOUR_MARKER_NAME_HERE',
'<i>YOUR_HTML_HERE<'+'/i>');
map.addOverlay(marker);*/
}
// display a warning if the browser was not compatible
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
// This Javascript is based on code provided by the
// Blackpool Community Church Javascript Team
// http://www.commchurch.freeserve.co.uk/
// http://www.econym.demon.co.uk/googlemaps/
//]]>
</script>
Using this code, the bubble contains the html you specify in YOUR_HTML_HERE plus a link to Get Directions, which (when clicked) turns into a textbox asking for a starting address. The result of the query, unfortunately, opens in a new browser window (since, at time of original publishing the API did not include directions capabilities)
I think I found the answer to my own question. The info window itself can't be modified, but by linking to the map for the address itself rather than the church as a business entity does the trick. The driving directions link is still there and that's mostly all they wanted.