Google Maps API V3, Marker InfoWindows not opening - javascript

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;
};

Related

How can I make both external JavaScript files work in my html file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
The first JavaScript code works fine by itself, but when I add the other one it doesn't. I dont understand why.
When I remove the first JavaScript code the other code works fine too, but when I put them together the only js code that works is the first one. I need both of them to work but I can't figure it out.
First js code
var map;
function initialize() {
var mapOptions = {
zoom: 6
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your Location.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
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);
}
google.maps.event.addDomListener(window, 'load', initialize);
Second js code
var map, places, iw;
var markers = [];
var searchTimeout;
var centerMarker;
var autocomplete;
var hostnameRegexp = new RegExp('^https?://.+?/');
function initialize() {
var myLatlng = new google.maps;
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
places = new google.maps.places.PlacesService(map);
google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);
document.getElementById('keyword').onkeyup = function(e) {
if (!e) var e = window.event;
if (e.keyCode != 13) return;
document.getElementById('keyword').blur();
search(document.getElementById('keyword').value);
}
var typeSelect = document.getElementById('type');
typeSelect.onchange = function() {
search();
};
var rankBySelect = document.getElementById('rankBy');
rankBySelect.onchange = function() {
search();
};
}
function tilesLoaded() {
search();
google.maps.event.clearListeners(map, 'tilesloaded');
google.maps.event.addListener(map, 'zoom_changed', searchIfRankByProminence);
google.maps.event.addListener(map, 'dragend', search);
}
function searchIfRankByProminence() {
if (document.getElementById('rankBy').value == 'prominence') {
search();
}
}
function search() {
clearResults();
clearMarkers();
if (searchTimeout) {
window.clearTimeout(searchTimeout);
}
searchTimeout = window.setTimeout(reallyDoSearch, 500);
}
function reallyDoSearch() {
var type = document.getElementById('type').value;
var keyword = document.getElementById('keyword').value;
var rankBy = document.getElementById('rankBy').value;
var search = {};
if (keyword) {
search.keyword = keyword;
}
if (type != 'establishment') {
search.types = [type];
}
if (rankBy == 'distance' && (search.types || search.keyword)) {
search.rankBy = google.maps.places.RankBy.DISTANCE;
search.location = map.getCenter();
centerMarker = new google.maps.Marker({
position: search.location,
animation: google.maps.Animation.DROP,
map: map
});
} else {
search.bounds = map.getBounds();
}
places.search(search, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var icon = 'number_' + (i + 1) + '.png';
markers.push(new google.maps.Marker({
position: results[i].geometry.location,
animation: google.maps.Animation.DROP,
icon: icon
}));
google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
window.setTimeout(dropMarker(i), i * 100);
addResult(results[i], i);
}
}
});
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
if (centerMarker) {
centerMarker.setMap(null);
}
}
function dropMarker(i) {
return function() {
if (markers[i]) {
markers[i].setMap(map);
}
}
}
function addResult(result, i) {
var results = document.getElementById('results');
var tr = document.createElement('tr');
tr.style.backgroundColor = (i % 2 == 0 ? '#00FFFFFFF' : '#00FFFFFFF');
tr.onclick = function() {
google.maps.event.trigger(markers[i], 'click');
};
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = 'number_' + (i + 1) + '.png';
icon.setAttribute('class', 'placeIcon');
icon.setAttribute('className', 'placeIcon');
var name = document.createTextNode(result.name);
iconTd.appendChild(icon);
nameTd.appendChild(name);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results.appendChild(tr);
}
function clearResults() {
var results = document.getElementById('results');
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
function getDetails(result, i) {
return function() {
places.getDetails({
reference: result.reference
}, showInfoWindow(i));
}
}
function showInfoWindow(i) {
return function(place, status) {
if (iw) {
iw.close();
iw = null;
}
if (status == google.maps.places.PlacesServiceStatus.OK) {
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[i]);
}
}
}
function getIWContent(place) {
var content = '';
content += '<table>';
content += '<tr class="iw_table_row">';
content += '<td style="text-align: left"><img class="hotelIcon" src="' + place.icon + '"/></td>';
content += '<td><b>' + place.name + '</b></td></tr>';
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Address:</td><td>' + place.vicinity + '</td></tr>';
if (place.formatted_phone_number) {
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Telephone:</td><td>' + place.formatted_phone_number + '</td></tr>';
}
if (place.rating) {
var ratingHtml = '';
for (var i = 0; i < 5; i++) {
if (place.rating < (i + 0.5)) {
ratingHtml += '✩';
} else {
ratingHtml += '✭';
}
}
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Rating:</td><td><span id="rating">' + ratingHtml + '</span></td></tr>';
}
if (place.website) {
var fullUrl = place.website;
var website = hostnameRegexp.exec(place.website);
if (website == null) {
website = 'http://' + place.website + '/';
fullUrl = website;
}
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Website:</td><td>' + website + '</td></tr>';
}
content += '</table>';
return content;
}
google.maps.event.addDomListener(window, 'load', initialize);
You're defining two functions named initialize(). Either change name on one of them, to set them apart, or merge the code in to one function. As it is written, the second initialize() will overwrite/override the first (in order of load).
You could also define "namespaces" for your different js files. This will enable you to have the same function names, but you'll have to call them using their namespace (outside of the scope of the namespace anyway):
var yourNamespace = {
initialize(): function() {
//...
}
};
var yourOtherNamespace = {
initialize(): function() {
//...
}
};
And to call these:
yourNamespace.initialize();
yourOtherNamespace.initialize();

Different results in Google Places API and Google Maps

I'm using the Google Places JavaScript API for a desktop application. However, the search results returned by the API aren't the same as the ones I get in maps.google.com. For instance, if I search for "Antique Hostel", I get many results (almost all of them are kinda random) whereas on Google Maps I get the correct (single) result.
Is the quality of the search isn't the same in the API and the service?
Here is my code
function initialize() {
// map setup
var mapOptions = {
center: new google.maps.LatLng(52.519171, 13.406091199999992),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
$map = document.getElementById('mapCanvas'),
map = new google.maps.Map($map, mapOptions),
input = document.getElementById('searchInput'),
autocomplete = new google.maps.places.Autocomplete(input),
service = new google.maps.places.PlacesService(map),
$ajaxSearchInput = $(input),
markers = [];
autocomplete.bindTo('bounds', map);
$ajaxSearchInput.keydown(function(e) {
if (e.keyCode === 13) {
var request = {
query: $(this).val(),
radius: '500',
location: map.getCenter()
}
service.textSearch(request, searchCallBack);
}
});
searchCallBack = function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
console.log(results);
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i], bounds);
}
map.fitBounds(bounds);
}
}
createMarker = function(place, bounds) {
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
});
// event listener to show the InfoWindow.
(function(marker, place) {
google.maps.event.addListener(marker, 'click', function() {
var content = '<h3>' + place.name + '</h3> ' + place.formatted_address + '<br>',
infowindow = new google.maps.InfoWindow({
content: ''
});
if (place.rating) {
content += '<p> <b>Rating</b>: ' + place.rating + '</p>';
}
if (place.types) {
content += '<p> <b>Tags</b>: ';
for (var j = 0, tag; tag = place.types[j]; j++) {
content += tag + ', '
}
content += '</p>';
}
infowindow.content = content;
infowindow.open(map, marker);
});
})(marker, place);
markers.push(marker);
bounds.extend(place.geometry.location);
}
}
google.maps.event.addDomListener(window, 'load', initialize);

Permanent Google Map Infowindow

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).

Google Maps Use Case has a JS error in Firefox

I have a FF error about the info window in GM. Here is the source code:
var lats;
var longs;
var k;
function initialize() {
//parentArray is an object where the elements of the parent page are stored
var parentArray = window.parent.params;
lats = parentArray["lat"].replace(/^\|+|\|+$/g, '').split("|");
longs = parentArray["long"].replace(/^\|+|\|+$/g, '').split("|");
k = parentArray["keys"].replace(/^\|+|\|+$/g, '').split("|");
var myLatlng = new google.maps.LatLng(parseFloat(lats[0]), parseFloat(longs[0]));
var myOptions = {
zoom: 20,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//contentString is built based on the array passed by the parent page
for (var i = 0; i < lats.length; i++) {
var contentString = '<div id="content"' + i + '><b>' + k[i] + '</b>';
for (var f in parentArray)
if ((f !== "long") && (f !== "lat") && (f !== "keys") && (parentArray[f].substring(0, 1) !== "<")) {
contentString += '<br />' + f + ': ' + parentArray[f];
}
contentString += '<br /></div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(lats[i]), parseFloat(longs[i])),
map: map,
title: 'Position'
});
createInfoWindow(marker, contentString);
function createInfoWindow(m, content) {
google.maps.event.addListener(m, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, m);
});
}
}
}
params is an array with information and k is an array of keys for the markers on the google map. Does anybody know why do I have a FF error for this code?
Sample Data For params:
params['foo']: bar
params['keys']: "Start Position|End Position"
params['lat']: "12.5323703|13.5323703"
params['long']: "14.5786987|15.5786987"
EDIT:
The Error is: createInfoWindow is not defined
Thanks in advance,
Lajos Arpad.
You are defining your method inside a loop (this is bad on its own..) and you call the method before you define it ..
just moving the call below the definition fixes the issue..
function createInfoWindow(m, content) {
google.maps.event.addListener(m, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, m);
});
}
createInfoWindow(marker, contentString);
Demo at http://jsfiddle.net/gaby/gdLVd/
But you should really move the definition of the createInfoWindow method somewhere else..
Better demo at http://jsfiddle.net/gaby/gdLVd/1/

Dynamically populated google maps sidebar

I've been using the code from this V3 example to set up a links bar that dynamically populates when different category filters are selected, but have two problems at the moment. Firstly, I've put the the initial makeSidebar function in the map's idle event, but the sidebar is only created when the map is moved, not on loading of the page. Secondly, I can't seem to get the marker infowindow to open when the corresponding link is clicked in the sidebar. My code is below:
var map;
var infowindow;
var image = [];
var gmarkers = [];
var place;
var side_bar_html = "";
image['attraction'] = 'http://google-maps-icons.googlecode.com/files/beach.png';
image['food'] = 'http://google-maps-icons.googlecode.com/files/restaurant.png';
image['hotel'] = 'http://google-maps-icons.googlecode.com/files/hotel.png';
image['city'] = 'http://google-maps-icons.googlecode.com/files/smallcity.png';
function mapInit(){
var placeLat = jQuery("#placelat").val();
var placeLng = jQuery("#placelng").val();
var centerCoord = new google.maps.LatLng(placeLat, placeLng);
var mapOptions = {
zoom: 15,
center: centerCoord,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListener(map, 'idle', function() {
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var yMaxLat = ne.lat();
var xMaxLng = ne.lng();
var yMinLat = sw.lat();
var xMinLng = sw.lng();
//alert("bounds changed");
updateMap(yMaxLat, xMaxLng, yMinLat, xMinLng);
show("attraction");
show("food");
show("hotel");
show("city");
makeSidebar();
});
function updateMap(yMaxLat, xMaxLng, yMinLat, xMinLng) {
jQuery.getJSON("/places", { "yMaxLat": yMaxLat, "xMaxLng": xMaxLng, "yMinLat": yMinLat, "xMinLng": xMinLng }, function(json) {
if (json.length > 0) {
for (i=0; i<json.length; i++) {
var place = json[i];
var category = json[i].tag;
var name = json[i].name;
addLocation(place,category,name);
//makeSidebar();
}
}
});
}
function addLocation(place,category,name) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(place.geom.y, place.geom.x),
map: map,
title: place.name,
icon: image[place.tag]
});
//var iwNode = document.getElementById("infowindow");
marker.mycategory = category;
marker.myname = name;
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({
content: "<div id='infowindow'><div id='infowindow_name'><p>"+ place.name +"</p></div><div id='infowindow_contents'><p>" + place.tag +"</p><a href='/places/"+place.id+"' id='place_link'>Show more!</a></div></div>"
});
infowindow.open(map, marker);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
});
}
function show(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(true);
}
}
document.getElementById(category+"box").checked = true;
}
function hide(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(false);
}
}
document.getElementById(category+"box").checked = false;
infowindow.close();
}
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
makeSidebar();
}
jQuery('#attractionbox').click(function() {
boxclick(this, 'attraction');
});
jQuery('#foodbox').click(function() {
boxclick(this, 'food');
});
jQuery('#hotelbox').click(function() {
boxclick(this, 'hotel');
});
jQuery('#citybox').click(function() {
boxclick(this, 'city');
});
function myclick(i) {
google.maps.event.trigger(gmarkers[i],"click");
}
function makeSidebar() {
//var html = "";
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
side_bar_html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>';
}
}
document.getElementById("side_bar").innerHTML = side_bar_html;
}
}
jQuery(document).ready(function(){
mapInit();
//makeSidebar();
});
Any help would be much appreciated - what can I do to get the sidebar loaded when the page loads, and to get the link click event working? Thanks!
The reason your links are not working is that you are defining your my_click and makeSidebar functions inside of your mapInit function and so they are not available outside of the scope of mapInit. Simply move them outside of mapInit and everything should just work.
As for the load event ... what you are looking for is the addDomListener method of google.maps.event. Simply use
google.maps.event.addDomListener(window, 'load', name_of_your_inital_function);
// e. g. google.maps.event.addDomListener(window, 'load', mapInit);
Finally; notta bene ... don't do this:
var image = [];
image['attraction'] = 'data';
image['food'] = 'more data';
Arrays are not meant to be used as hashes in Javascript. Use objects for dictionaries / hashes instead -- it's what you are actually doing (Array "subclasses" Object) and it will make it easier for others to use your code (and save you from headaches down the line).
var image = {};
image['attraction'] = 'data';
image['food'] = 'more data';

Categories