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';
Related
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;
};
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>
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();
JS FIDDLE HERE:
http://jsfiddle.net/useyourillusiontoo/g77np63c/1/
I've created a google map that plants markers down and allows my to filter then with checkboxes without the page or map reloading. Yay!
Next I added marker cluster which worked too. However, when I now click on my markers the cluster doesn't update. That is.. the number inside the cluster doesnt change to reflect markers that are being hidden/displayed.
When I zoom in the markers are still being hidden/displayed but its just the cluster doesn't show this when zoomed out.
I've pasted my code below and would love any advice because i've been scratching my head.
var map;
var infowindow;
var image = [];
var gmarkers = [];
var clusterMarkers = [];
function mapInit(){
var centerCoord = new google.maps.LatLng(53.01265600000,-1.466105200000);
var mapOptions = {
zoom: 6,
center: centerCoord,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
addLocation();
var markerCluster = new MarkerClusterer(map, clusterMarkers);
function addLocation(place,category) {
for (var x in points){
var development = points[x];
var location = new google.maps.LatLng(development.lat, development.lng);
storeMarker(location, development);
}
}
function storeMarker(location, development){
var latLng = location;
var storedmarker = new google.maps.Marker({
position: latLng
});
storedmarker.mycategory = development.tid;
google.maps.event.addListener(storedmarker, 'click', function() {
if(typeof infowindow != 'undefined') infowindow.close();
infowindow = new google.maps.InfoWindow({
content: "<h3>"+ development.name +"</h3><a href='http://www.bbc.co.uk'>Show more!</a>"
});
infowindow.open(map, storedmarker);
});
clusterMarkers.push(storedmarker);
}
function show(category) {
for (var i=0; i<clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
clusterMarkers[i].setVisible(true);
}
}
document.getElementById(category+"box").checked = true;
}
function hide(category) {
for (var i=0; i<clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
clusterMarkers[i].setVisible(false);
}
}
document.getElementById(category+"box").checked = false;
infowindow.close();
}
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
}
jQuery(document).ready(function($) {
$('.b2bfilter').click(function () {
boxclick(this, this.value);
});
});
}
jQuery(document).ready(function(){
mapInit();
});
added markers as requested. They are a basic JSON object
var points = [
{"name":"House","lat":"53.341265600000","lng":"- 1.466105200000","tid":"1"},
{"name":"Old house","lat":"53.361066200000","lng":"-1.465752700000","tid":"2"}]
setting the visible-property will not have an effect when a marker is inside a cluster, you must also remove/add the marker from/to the markerclusterer.
Possible solution:
observe the visible_changed -event of the markers:
google.maps.event.addListener(storedmarker,'visible_changed',function(){
markerCluster[(this.getVisible())?'addMarker':'removeMarker'](this)
});
http://jsfiddle.net/doktormolle/g77np63c/4/
another(possibly better) approach(especially whene there are a lot of markers, because the solution above will force a redraw of the clusters for each affected marker):
First collect all affected markers and then use addMarkers/showMarkers to toggle them:
function toggle(category, show) {
var markers = [];
for (var i = 0; i < clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
markers.push(clusterMarkers[i]);
clusterMarkers[i].setVisible(show);
}
}
if (markers.length) {
markerCluster[(show) ? 'addMarkers' : 'removeMarkers'](markers);
}
if (!show && infowindow) infowindow.close();
}
function boxclick(box, category) {
toggle(category, box.checked);
}
jQuery(document).ready(function ($) {
$('.b2bfilter').click(function () {
boxclick(this, this.value);
});
});
http://jsfiddle.net/doktormolle/g77np63c/5/
I created a google map with this code:
function load() {
var markersArray = [];
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("getMapMarkers.php", function(data) {
var bounds = new google.maps.LatLngBounds();
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var brewID = markers[i].getAttribute("brewID");
//construct url
var breweryLink = "http://beerportfolio.com/breweryPage.php?id=" + brewID;
//create directions link
http://maps.google.com/maps?daddr=
var directionsLink = "http://maps.google.com/maps?daddr=";
directionsLink = directionsLink + markers[i].getAttribute("lat") +"," + markers[i].getAttribute("lng")
var html = "<b>"+name+" </b> <br/>" ;
html = html + "<br> <br>";
html = html + "(Click for Directions)";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
markersArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
bounds.extend(point);
}
map.fitBounds(bounds);
});
}
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(null);
}
function getMapVisit()
{
alert("clearing overlays...");
clearOverlays();
return false;
}
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function doNothing() {}
When I try an delete the markers to re-load different ones, I cannot delete them off the map.
On button press I call getMapVisit() which then calls clearOverlays(), but clearOverlays() doesn't clear the map. In Chrome, when I inspect the element I get this error:
Uncaught ReferenceError: markersArray is not defined
The error is called on line 86 which is:
if (markersArray) {
I do not know why its not defined when its clearly initialized array at the top of load()
You need to define var markersArray = []; above the load function so it will be globally defined and will be accessible in all the functions .