Permanent Google Map Infowindow - javascript

I have a marker which has a dynamic position (i.e. updated periodically). When marker is clicked, an infowindow is shown but when marker position is updated, the infowindow gets automatically closed. I want that when marker position is updated, infowindow position should also get updated automatically. How to solve this.
P.S. :- infowindow contain a form which is editable by the user.
Problem : when user is editing/filling the form and marker position gets updated (form not submitted yet), then the form will get closed and user will lose his data.
<script type="text/javascript">
var map;
var lat_longs = new Array();
var geocoder = null;
var infoWindow = new google.maps.InfoWindow();
var trafficLayer = null;
var weatherLayer = null;
var markers = new Array();
var poi = new Array();
var fitMap = 0;
loc_array = new Array();
totUpdateOld = new Array();
ident = 0;
function showMap() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng('-0.57128','117.202148'),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
geocoder = new google.maps.Geocoder();
trafficLayer = new google.maps.TrafficLayer();
weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELCIUS
});
showCarPosition(function() {
fitMapToBounds();
});
}
function showCarPosition(){
if (markers.length>0){
ident = 2;
}
var car_icon;
jQuery.getJSON('<s:property value="jsonUrl"/>','', function(data) {
var arrayCar = data.listCar;
for (var i = 0; i < arrayCar.length; i++) {
var car = arrayCar[i];
var status = "";
var tanggal = "never";
var car_type = (car.type != "" || car.type != null)?' ('+car.type+')':'';
if(car.lastUpdate == null){
car_icon = ctx + 'web/img/car_black.png';
status = "Belum pernah kirim data";
}else if((not_active = (currentdate - stringToDate(car.lastUpdate))/ 1000 / 60) >= 30){ //diff in minute
car_icon = ctx + 'web/img/car_red.png';
status = convertMinute(not_active);
}else if((((currentdate - stringToDate(car.lastUpdate))/ 1000 / 60) >= 5) && (car.lastSpeed == 0)){ //diff in minute
car_icon = ctx + 'web/img/car_yellow.png';
status = "Berhenti";
}else
car_icon = ctx + 'web/img/car_green.png';
if(car.lastUpdate != null){
var splitDate = car.lastUpdate.split("T");
tanggal = splitDate[1]+" "+splitDate[0].split("-")[2]+"-"+bulan[parseInt(splitDate[0].split("-")[1])]+"-"+splitDate[0].split("-")[0];
}
var coordinate = new google.maps.LatLng(car.latitude, car.longitude);
var windowContent =[
'<div class="windowcontent"><ul class="nav infowindow nav-pills nav-stacked">',
'<li class="active">'+car.plate +car_type+' - '+ car.driverName +'</li>',
(status != null)?'<li>'+status+'</li>':'',
(car.phoneNumber != null)?'<li>Phone : ' + car.phoneNumber+ '</li>':'',
'<li>Last Temp : ' + car.lastTemp+ '</li>',
(parseInt(car.lastSpeed)>0)?'<li>Last Speed : ' + car.lastSpeed+ '</li>':'',
(car.type != "" || car.type != null)?'<li>Last Speed : ' + car.lastSpeed+ '</li>':'',
'<li>Last Connected : ' + tanggal+ '</li>',
'<li>'+((car.note != null)?car.note:'no notes')+'<li>',
'<div id="'+car.id+'"></div></ul>',
'<span id="'+car.id+'" onclick="editinfo(this, \''+car.note+'\');">Edit Note</span></div>']
.join('');
if (ident == 0){
var marker = createMarker({
map: map,
position: coordinate,
icon: car_icon,
labelContent: ((car.driverName == null)?car.plate:car.driverName)+'-'+car.lastSpeed,
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
});
loc_array[car.id] = i;
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
jQuery('.viewlog').click(function() {
jQuery.history.load(jQuery(this).attr('href'));
return false;
});
});
}else{
if (car.totalUpdate > totUpdateOld[car.id]) {
var map_post = loc_array[car.id];
markers[map_post].setMap(null);
var marker = updateMarker({
map: map,
position: coordinate,
icon: car_icon,
labelContent: ((car.driverName == null)?car.plate:car.driverName)+'-'+car.lastSpeed,
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
}, map_post);
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
jQuery('.viewlog').click(function() {
jQuery.history.load(jQuery(this).attr('href'));
return false;
});
});
}
}
totUpdateOld[car.id] = car.totalUpdate;
}
fitMapToBounds();
});
setTimeout("showCarPosition()",5000);
}
function createMarker(markerOptions) {
var marker = new MarkerWithLabel(markerOptions);
markers.push(marker);
lat_longs.push(marker.getPosition());
return marker;
}
function updateMarker(markerOptions,id) {
var marker = new MarkerWithLabel(markerOptions);
markers[id] = marker;
lat_longs[id] = marker.getPosition();
return marker;
}
function fitMapToBounds() {
var bounds = new google.maps.LatLngBounds();
if (fitMap == 0){
if (lat_longs.length>0) {
for (var i=0; i<lat_longs.length; i++) {
bounds.extend(lat_longs[i]);
}
map.fitBounds(bounds);
fitMap = 1;
}
}
}
function bindInfoWindow(marker, event, windowContent) {
google.maps.event.addListener(marker, event, function() {
infoWindow.setContent(windowContent);
infoWindow.open(map, marker);
});
}
jQuery(document).ready(function() {
showMap();
});
</script>
<div id="map_canvas" class="widgettitle" style="height:540px;"></div>

call this function when the marker position is changed .
infowindow.open(map,marker);

Put an onblur event handler on the text field that calls a halt to the repositioning.
Then when it is submitted and goes to the new point, restart it (if needed).

Related

Google Maps API V3, Marker InfoWindows not opening

I am building a GoogleMap with multiple markers with infowindows attached. I have tried to build this into a re-usable Javascript Class using prototypes but my infowindows will not open (the markers show up fine).
If I test console.log within the click event listener it triggers, but the infowindows themselves refuse to open.
Markers.json is just a JSON object which returns a list of data to be looped through.
JS Fiddle
I am initiating the map using:
$(document).ready(function(){
var customMap = new CustomMap('mapitems');
customMap.init();
customMap.setMarkers();
});
My Javascript:
function CustomMap(mapId, defaultLat, defaultLng, defaultZoom)
{
this.map = null;
this.markerBounds = null;
this.$mapContainer = document.getElementById(mapId);
this.defaultLat = (defaultLat ? defaultLat : '-36.848460');
this.defaultLng = (defaultLng ? defaultLng : '174.763332');
this.defaultZoom = (defaultZoom ? defaultZoom : 15);
}
CustomMap.prototype.init = function() {
var position = new google.maps.LatLng(this.defaultLat, this.defaultLng);
this.map = new google.maps.Map(this.$mapContainer, {
scrollwheel: true,
mapTypeId: 'roadmap',
zoom: this.defaultZoom,
position: position
});
this.markerBounds = new google.maps.LatLngBounds();
};
CustomMap.prototype.setMarkers = function() {
var that = this;
$.get('/locations.json', null, function(locations) {
for (var i = 0; i < locations.length; i++) {
that.processMarker(locations[i]);
}
that.map.fitBounds(that.markerBounds);
}, 'json');
};
CustomMap.prototype.processMarker = function(data) {
if (data.lat && data.lng) {
var position = new google.maps.LatLng(data.lat, data.lng);
this.markerBounds.extend(position);
var marker = this.getMarker(position);
this.setInfoWindow(marker, data);
}
};
CustomMap.prototype.getMarker = function(position) {
return new google.maps.Marker({
map: this.map,
draggable:false,
position: position
});
};
CustomMap.prototype.setInfoWindow = function(marker, data) {
var that = this;
marker.infoWindow = new google.maps.InfoWindow({
content: that.buildInfoHtml(data)
});
google.maps.event.addListener(marker, 'click', function() {
marker.infoWindow.open(that.map, marker);
});
};
CustomMap.prototype.buildInfoHtml = function(data) {
var html = '';
html += '<strong>' + data.title + '</strong><br>';
if (data.address.length > 0)
html += data.address + '<br>';
if (data.freephone.length > 0)
html += 'Freephone: ' + data.freephone + '<br>';
if (data.depotPhone.length > 0)
html += 'Depot Phone: ' + data.depotPhone + '<br>';
if (data.hours.length > 0)
html += 'Depot Hours: ' + data.hours + '<br>';
return html;
};

Duplicate values in google map pagination

The code below display a map and display the results in UL. I have 2 buttons that display train station and shopping mall.Initially, it will display the results correctly but If I click the other button, it will display duplicate values.
Javascript
var map;
var pos;
var distance;
var distancearray = [];
var markers = [];
//=================================================================
function initialize() {
googleMapsLoaded = false;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13
});
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var request = {
location:pos,
radius:3000, //3000 Meters
type:initialtype
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'You Are Here',
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function callback(results, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
else{
for (var i = 0; i < results.length; i++)
markers.push(createMarker(results[i]));
}
} //end callback function
/* listen to the tilesloaded event
if that is triggered, google maps is loaded successfully for sure */
google.maps.event.addListener(map, 'tilesloaded', function() {
googleMapsLoaded = true;
// document.getElementById("mapnotification").innerHTML = "Map Loaded!";
$("#mapnotification").hide();
$("#map-loaded").show();
$("#map-loaded").css('visibility', 'hidden');
$("#map-notloaded").hide();
//clear the listener, we only need it once
google.maps.event.clearListeners(map, 'tilesloaded');
});
setTimeout(function() {
if (!googleMapsLoaded) {
//we have waited 7 secs, google maps is not loaded yet
document.getElementById("mapnotification").innerHTML = "Map NOT Loaded! Make sure you have stable internet connnection";
$("#mapnotification").hide();
$("#map-notloaded").show();
$("#map-loaded").hide();
}
}, 7000);
function createMarker(place) { // Create Marker and the Icon of the marker
// var bounds = new google.maps.LatLngBounds();
var markerlat;
var markerlon;
var p2;
var output="";
var placesList = document.getElementById('places');
placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8,
fillColor:'00a14b',
fillOpacity:0.3,
fillStroke: '00a14b',
strokeWeight:4,
strokeOpacity: 0.7
}, // end icon
}); //end of marker variable
markerlat = marker.getPosition().lat()
markerlon = marker.getPosition().lng()
console.log("Markers Lat" + markerlat);
console.log("Markers Lon" + markerlon );
p2 = new google.maps.LatLng(markerlat, markerlon);
distance = [calcDistance(pos, p2)];
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
distancearray.push([distance, place.name]);
distancearray.sort();
console.log("distancearraylength" + distancearray.length);
console.log("Summary" + distancearray);
for(var i = 0; i < distancearray.length; i++){
output += '<li>' + distancearray[i][1] + " " + distancearray[i][0]+ " " + "km" + '</li>';
placesList.innerHTML = output;
}
google.maps.event.addListener(marker, 'click', function() { //show place name when marker clicked
infowindow.setContent(place.name);
infowindow.open(map, marker);
}); // end of marker show place name
} // end createMarker function
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
} // End handleNoGeolocation function
} //End function initialize
//==========================================================================================================//
$(document).on('pagebeforeshow','#itemPanel2', function(e, data){ // Loading of Nearest Place Options
bindchoicesclick();
function bindchoicesclick(){
$("#subway_station").on("click",function(){
// alert("subway");
markers = [];
pos="";
while(distancearray.length > 0) {
distancearray.pop();
}
while(markers.length > 0) {
markers.pop();
}
//$("#places").empty();
initialtype = ['subway_station'];
buttonholder = "Nearest Station";
$("#find").val(buttonholder);
$("#find").button("refresh");
initialize();
});
$("#shopping_mall").on("click",function(){
// alert("stores");
markers = [];
pos="";
while(distancearray.length > 0) {
distancearray.pop();
}
while(markers.length > 0) {
markers.pop();
}
// distancearray.splice(0).
// $("#places").empty();
initialtype = ['shopping_mall'];
buttonholder = "Nearest Mall";
$("#find").val(buttonholder);
$("#find").button("refresh");
initialize();
});
}
});
HTML
<h1 id="headerField">Nearby Search</h1>
</div>
Search Nearest Train Station
Search Nearest Mall
</div>
<!--Train Stations -->
<div id="globa_map" data-role="page">
<div data-role="header">
Back
Refresh
<h1 id="headerField">Global</h1>
</div>
<div data-role="content">
<!-- <input type="button" id="refreshmap" value="Refresh"> -->
<p id="mapnotification">Please wait while the map is loading...</p>
<p id="map-loaded">Map Loaded!</p>
<p id="map-notloaded">Map NOT Loaded! Make sure you have stable internet connnection</p>
<h2>Results</h2>
<ul id="places"></ul>
<button id="more">More results</button>
<div id="map" style="height:400px;">
</div>
</div>

Show/Hide markers with category. Not working with MarkerCluster

I'm trying to make a select to show and hide markers with category.
Its working fine, but not working if there is a markercluster on map.
Eg. when i choose category bar markers on map with category restaurant disapear, but markercluster is still on map. Here is my intin function:
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(52.6145, 21.3418);
var mapOptions = {
zoom: 6,
center: chicago
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
// Geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
document.getElementById('field').value = +position.coords
.latitude + "," + position.coords.longitude;
marker = new google.maps.Marker({
position: pos,
animation: google.maps.Animation.DROP,
map: map
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("db/parse_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName(
"marker");
markerArray = [];
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var cover = markers[i].getAttribute("cover");
var point = new google.maps.LatLng(parseFloat(markers[i]
.getAttribute("lat")), parseFloat(markers[i]
.getAttribute("lng")));
var html = "<div id='infobox'><img src='" + cover +
"'/><b>" + name + "</b><br>" + address +
" <br/><input type='button' id='end' onClick=calcRoute() name='" +
name + "," + address +
"' value='Wyznacz trasÄ™'></div>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
category: type
});
markerArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
document.getElementById('pasekBoczny').innerHTML +=
'<li class="list-sidebar" ><a href="javascript:myclick(' +
i + ')" >' + name + '</a></li>';
// markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markerArray);
});}
and my filter function:
filterMarkers = function (category) {
for (i = 0; i < markers.length; i++) {
marker = markers[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}}
I'm assuming you're not wanting to completely remove the marker clusters, just change those where you're hiding the markers. As you're looping over the markers, remove those you're hiding from the cluster, like so:
// Categories don't match
else {
marker.setVisible(false);
markerCluster.removeMarker(marker);
}
Similarly if you show the marker, you probably need to add it back into the cluster, using addMarker
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
markerCluster.addMarker(marker);
}
Then you probably need to call the redraw function on the MarkerClusterer.
See https://googlemaps.github.io/js-marker-clusterer/docs/reference.html
redraw() Redraws the clusters.
You'll need to amend your code to make the MarkerClusterer a global variable first. e.g.
var markerCluster;
function initialize() {
...
markerCluster = new MarkerClusterer(map, markerArray);
}
filterMarkers = function (category) {
for (i = 0; i < markers.length; i++) {
marker = markers[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
markerCluster.addMarker(marker);
}
// Categories don't match
else {
marker.setVisible(false);
markerCluster.removeMarker(marker);
}
}
markerCluster.redraw();
};

Google Maps API: Markers from XML file not being displayed

Using code that was posted on here, I'm trying to map markers from an XML file to a Google Map in a JSP using the Google Maps Javascript API V3.
My markers file has the following format:
<markers>
<marker>
<id>0</id>
<lat>53341428</lat>
<lng>-6246720</lng>
<name>Fenian Street</name>
<number>63</number>
</marker>
<marker>
<id>1</id>
<lat>53346637</lat>
<lng>-6246154</lng>
<name>City Quay</name>
<number>99</number>
</marker>
And the code is:
<script type="text/javascript">
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.3430347, -6.2550587),
zoom: 14,
mapTypeId: 'roadmap'`enter code here`
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl( "markers.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//var id = markers[i].getElement("id");
var id = markers[i].getElementsByTagName("id")[0];
var point = new google.maps.LatLng(
parseFloat(markers[i].getElementsByTagName("lat")[0]),
parseFloat(markers[i].getElementsByTagName("lng")[0]));
var name = markers[i].getElementsByTagName("name")[0];
//var number = markers[i].getElementsByTagName("number");
var html = "<b>" + id + "</b> <br/>" + name;
var image = 'img.png';
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
position: point,
map: map,
title: name,
icon: image
});
marker.setMap(map);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function () {
if (request.readyState === 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send();
}
function doNothing() {
}
</script>
When I load the page, I see an error in he console: InvalidValueError: setTitle: not a string
What am I doing wrong? The markers are not appearing on the map.
You are getting that error because "name" is not a string, it is an XML DOM object. There is a function nodeValue that can be used to get the string content out of an XML DOM element.
Also, your latitude and longitude are not valid, they are not in decimal degrees.
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.3430347, -6.2550587),
zoom: 14,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// downloadUrl( "markers.xml", function(data) {
// var xml = data.responseXML;
var xml = xmlParse(xmlString);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//var id = markers[i].getElement("id");
var id = nodeValue(markers[i].getElementsByTagName("id")[0]);
var point = new google.maps.LatLng(
parseFloat(nodeValue(markers[i].getElementsByTagName("lat")[0])),
parseFloat(nodeValue(markers[i].getElementsByTagName("lng")[0])));
var name = nodeValue(markers[i].getElementsByTagName("name")[0]);
//var number = markers[i].getElementsByTagName("number");
var html = "<b>" + id + "</b> <br/>" + name;
var image = 'img.png';
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
position: point,
map: map,
title: ""+name /*,
icon: image */
});
marker.setMap(map);
bindInfoWindow(marker, map, infoWindow, html);
}
// });
}
where nodeValue was "borrowed" from geoxml3:
//nodeValue: Extract the text value of a DOM node, with leading and trailing whitespace trimmed
function nodeValue (node, defVal) {
var retStr="";
if (!node) {
return (typeof defVal === 'undefined' || defVal === null) ? '' : defVal;
}
if(node.nodeType==3||node.nodeType==4||node.nodeType==2){
retStr+=node.nodeValue;
}else if(node.nodeType==1||node.nodeType==9||node.nodeType==11){
for(var i=0;i<node.childNodes.length;++i){
retStr+=arguments.callee(node.childNodes[i]);
}
}
return retStr;
};
working fiddle

Google Maps populate text field with additional detail

I am trying to populate a text field with a dblclick event using information from a database. When I double click on the marker, the incorrect information is used to populate the fields. I get the same values for any marker I double click on. I have tried various ways to reference the colid, driver and vehicle values, but if I change anything, all I get is an unknown values in the field.
map = new google.maps.Map(document.getElementById("map"), map_options);
var infoWindow = new google.maps.InfoWindow;
downloadUrl(url, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var ThisMarker = markers[i];
var InfoText = ThisMarker.getAttribute("InfoText");
var colid = ThisMarker.getAttribute("colid");
var driver = ThisMarker.getAttribute("driver");
var vehicle_reg = ThisMarker.getAttribute("vehicle");
var mtype = ThisMarker.getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(ThisMarker.getAttribute("lat")),
parseFloat(ThisMarker.getAttribute("lng"))
);
var icon = customIcons[mtype] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
clickable: true
});
bindInfoWindow(marker, map, infoWindow, InfoText);
if(mtype == 'col' || mtype == 'del') {
google.maps.event.addListener(marker, 'dblclick', function() {
document.getElementById("collivery_id").value = colid;
document.getElementById("command").value = 'action';
});
}
if(mtype == 'bike' || mtype == 'car' || mtype == 'bakkie' || mtype == 'truck') {
google.maps.event.addListener(marker, 'dblclick', function() {
document.getElementById("driver").value = driver;
document.getElementById("vehicle").value = vehicle_reg;
});
}
}
});
function bindInfoWindow(marker, map, infoWindow, InfoText) {
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(InfoText);
infoWindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infoWindow.close(map, marker);
});
}
Possible solution using function closure:
map = new google.maps.Map(document.getElementById("map"), map_options);
var infoWindow = new google.maps.InfoWindow;
downloadUrl(url, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var ThisMarker = markers[i];
var InfoText = ThisMarker.getAttribute("InfoText");
var colid = ThisMarker.getAttribute("colid");
var driver = ThisMarker.getAttribute("driver");
var vehicle_reg = ThisMarker.getAttribute("vehicle");
var mtype = ThisMarker.getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(ThisMarker.getAttribute("lat")),
parseFloat(ThisMarker.getAttribute("lng"))
);
var icon = customIcons[mtype] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
clickable: true
});
bindInfoWindow(marker, map, infoWindow, ThisMarker);
});
function bindInfoWindow(marker, map, infoWindow, marker)
{
var InfoText = marker.getAttribute("InfoText");
var colid = marker.getAttribute("colid");
var driver = marker.getAttribute("driver");
var vehicle_reg = marker.getAttribute("vehicle");
var mtype = marker.getAttribute("type");
if(mtype == 'col' || mtype == 'del') {
google.maps.event.addListener(marker, 'dblclick', function() {
document.getElementById("collivery_id").value = colid;
document.getElementById("command").value = 'action';
});
}
if(mtype == 'bike' || mtype == 'car' || mtype == 'bakkie' || mtype == 'truck') {
google.maps.event.addListener(marker, 'dblclick', function() {
document.getElementById("driver").value = driver;
document.getElementById("vehicle").value = vehicle_reg;
});
}
// whatever code is currently in your bindInfoWindow function
// possibly this:
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(InfoText);
infoWindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infoWindow.close(map, marker);
});
}

Categories