Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have trouble with my google map script where the markers on a same location overlapped and not visible to user.
I tried to edit my script using OverlappingMarkerSpiderfier available in this link https://github.com/jawj/OverlappingMarkerSpiderfier. But overlapping issue exist.No improvement occured.
<script type="text/javascript">
var geocoder;
var map;
// initializing the map
function initialize()
{
// define map center
var latlng = new google.maps.LatLng(40.44694705960048,-101.953125);
// define map options
var myOptions =
{
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.MAP,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
};
// initialize map
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// add event listener for when a user clicks on the map
google.maps.event.addListener(map, 'click', function(event) {
findAddress(event.latLng);
});
}
// finds the address for the given location
function findAddress(loc)
{
geocoder = new google.maps.Geocoder();
if (geocoder)
{
geocoder.geocode({'latLng': loc}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
if (results[0])
{
address = results[0].formatted_address;
// fill in the results in the form
document.getElementById('lat').value = loc.lat();
document.getElementById('long').value = loc.lng();
document.getElementById('address').value = address;
}
}
else
{
alert("Geocoder failed due to: " + status);
}
});
}
}
// initialize the array of markers
var markers = new Array();
// the function that adds the markers to the map
function addMarkers()
{
// get the values for the markers from the hidden elements in the form
var lats = document.getElementById('lats').value;
var lngs = document.getElementById('lngs').value;
var addresses = document.getElementById('addresses').value;
var names = document.getElementById('names').value;
var descrs = document.getElementById('descrs').value;
var photos = document.getElementById('photos').value;
var user_names = document.getElementById('user_names').value;
var user_locs = document.getElementById('user_locs').value;
var las = lats.split(";;")
var lgs = lngs.split(";;")
var ads = addresses.split(";;")
var nms = names.split(";;")
var dss = descrs.split(";;")
var phs = photos.split(";;")
var usrn = user_names.split(";;")
var usrl = user_locs.split(";;")
// for every location, create a new marker and infowindow for it
for (i=0; i<las.length; i++)
{
if (las[i] != "")
{
// add marker
var loc = new google.maps.LatLng(las[i],lgs[i]);
var marker = new google.maps.Marker({
position: loc,
map: window.map,
title: nms[i]
});
markers[i] = marker;
var contentString = [
'<div id="tabs">',
'<div id="tab-1">',
'<p><span>'+nms[i]+'</span></p>',
'<p><img src="./photos/'+phs[i]+'"/></p>'+
'</div>',
'<div id="tab-3">',
'<p><img src="images/b-line.jpg"/></p>',
'</div>',
'</div>'
].join('');
var infowindow = new google.maps.InfoWindow;
bindInfoWindow(marker, window.map, infowindow, contentString);
}
}
}
// make conection between infowindow and marker (the infowindw shows up when the user goes with the mouse over the marker)
function bindInfoWindow(marker, map, infoWindow, contentString)
{
google.maps.event.addListener(marker, 'mouseover', function() {
map.setCenter(marker.getPosition());
infoWindow.setContent(contentString);
infoWindow.open(map, marker);
$("#tabs").tabs();
});
}
// highlighting a marker
// make the marker show on top of the others
// change the selected markers icon
function highlightMarker(index)
{
// change zindex and icon
for (i=0; i<markers.length; i++)
{
if (i == index)
{
markers[i].setZIndex(10);
markers[i].setIcon('http://www.google.com/mapfiles/arrow.png');
}
else
{
markers[i].setZIndex(2);
markers[i].setIcon('http://www.google.com/mapfiles/marker.png');
}
}
}
</script>
Thanks in advance.
Refer OverlappingMarkerSpiderfier and this
Related
How to display google map after every x seconds without google map refresh?
1.Markers latLong are coming from database.
2.Allocate that markers on google map.
3.Markers's latLong changes after 30 second.
Problem is google map get refreshed. All I want google map should display without refresh with updated LatLong.
Here is my code.
<script>
function initMap() {
var infowindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 19.9518684, lng: 73.7354084}
});
var image = '<?php echo $getImagePath; ?>'
for (var o in markers) {
lat = markers[ o ].lat;
lng = markers[ o ].lng;
address = markers[ o ].address;
var my = new google.maps.LatLng(lat, lng);
//console.log(my);
var marker = new google.maps.Marker({
position: my,
map: map,
icon: image,
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent("'" + address + "'");
infowindow.open(map, marker);
});
}
}
</script>
I tried google.maps.event.addDomListener(window, "load", initMap); and window.onload = initMap; but didn't work.
Can any one help me out?
I hope this small rewrite of your code will help you on your way. As it stands, there's a lot of information not present in the question, so I can only guess
// note these are globals because they are set in initMap and used outside of it
var image = '<?php echo $getImagePath; ?>';
var map;
var infowindow;
var markers = [/* some initially loaded markers loaded as if by majick unicorn farts */];
function initMap() {
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 19.9518684, lng: 73.7354084}
});
doMarkers(true);
}
function doMarkers(firstLoad) {
markers.forEach(marker => {
var lat = marker.lat;
var lng = marker.lng;
marker.my = new google.maps.LatLng(lat, lng);
if (firstLoad) { // marker has no marker the first time because it's not on a map yet
marker.marker = new google.maps.Marker({
position: marker.my,
map: map,
icon: image,
});
google.maps.event.addListener(marker.marker, 'click', function () {
infowindow.setContent("'" + marker.address + "'");
infowindow.open(map, marker.marker);
});
} else { // move existing marker
marker.marker.setPosition(marker.my);
}
}
}
function magicallyFindAndUpdateMarkerDataUsingUnicornFarts(marker) {
// find corresponding marker in markers array
// update lat, lng and address
}
function doSomeAjaxToGetNewMarkerPositionsAndCallCallback(cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'someURI');
xhr.onload = function() {
var data = JSON.parse(xhr.responseText);
data.forEach(function(marker) {
magicallyFindAndUpdateMarkerDataUsingUnicornFarts(marker);
});
cb()
}
xhr.send();
}
setInterval(function () {
doSomeAjaxToGetNewMarkerPositionsAndCallCallback(function() {
doMarkers(false);
});
}, 30000);
Of course, I can't see how markers are loaded (into markers in your code), nor can I tell you what doSomeAjaxToGetNewMarkerPositionsAndCallCallback or magicallyFindAndUpdateMarkerDataUsingUnicornFarts should be, because you haven't shown any code regarding markers at all
I have a map-making tool that is built with the Google Maps API V3. It allows users to enter two or more locations and produce a map and route. I also have a checkbox that, when clicked, shows markers indicating nearby points of interest.
When I first built the tool, I think it worked well every time. Recently, though, I've noticed that the markers do not always appear when the checkbox is clicked. The map and routing work fine, but the markers only work occasionally. This error seems to occur when they don't work:
Uncaught ReferenceError: map is not defined
It references a section of the "cmarkers" section of javascript (see below).
Background detail: This is part of a Rails web app and a webpage / layout called "Itineraries". When you land on the itineraries webpage and click on the "Map Maker" icon, the map-making tool appears. It's loaded in an i-frame, it's called "map.html.erb", and the map view lives in /views/itineraries. All of the javascript for the map maker lives in the Itineraries layout file, however.
Based on reviewing these posts, I think it might be something in the way that I've ordered or initialized the code, and I think the main culprit is likely in that "cmarkers" section of the code.
Google Maps API Sometimes Not Showing Markers
Google maps api(v3) doesn't show markers
Google Maps API v3 javascript Markers don't always load
I've tried several different changes, but each has either not worked or stopped the map from initializing. Here is the javascript; please note that the API key and other small sections are redacted. Below it is the code for the markers.
<script src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&sensor=false"></script>
<script type='text/javascript'>
$(function(){
var directionsDisplay;
var map;
function overlaysClear() {
if (markersArray) {
for( var i = 0, n = markersArray.length; i < n; ++i ) {
markersArray[i].setVisible(false);
}
}
}
function overlaysShow() {
if (markersArray) {
for( var i = 0, n = markersArray.length; i < n; ++i ) {
markersArray[i].setVisible(true);
}
}
}
$("#showmapview").click(function() {
overlaysClear();
$('#mapeach').attr('checked', false);
});
$('#mapeach').change(function() {
if( $('#mapeach').attr("checked")) {
overlaysShow();
}
else {
overlaysClear();
}
});
cmarkers();
google.maps.event.addDomListener(window, 'load', initialize);
});
var directionsService = new google.maps.DirectionsService();
var markersArray = [];
var arrInfoWindows = null;
function initialize() {
var rendererOptions = {
draggable: true,
panel:document.getElementById('directions_panel')
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var waypts = [];
var checkboxArray = document.getElementById("waypoints");
for (var i = 0; i < checkboxArray.length; i++) {
waypts.push({
location:checkboxArray[i].value,
stopover:true
});
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: optimize,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
};
function cmarkers() {
$.getJSON( "/mapeach.js", {}, function( data ) {
$.each( data, function( i, item ) {
var loc = item.mainlocation;
$("#markers").append('<li>' + loc.nickname + '</li>');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(+loc.latitude, +loc.longitude),
map: map,
title: loc.nickname,
});
markersArray.push(marker);
var infowindow = new google.maps.InfoWindow({
content: '<a class="clink" href="/spots/'+ loc.id +'/'+ loc.nickname +'" target="_blank">'+ loc.nickname +'</a>'
});
google.maps.event.addListener(marker, 'click', function() {
if (arrInfoWindows != null) {
arrInfoWindows.close();
}
infowindow.open(map,marker);
arrInfoWindows = infowindow;
});
});
});
};
</script>
The mapeach.js file is formatted as below:
[{"mainlocation":{"latitude":"40.706352","nickname":"First Location","id":100000,"longitude":"-73.987650"}},{"mainlocation":{"latitude":"34.061148","nickname":"Second Location","id":100001,"longitude":"-118.273067"}}]
I was able to solve this problem by moving the cmarkers code inside the initialize. I think that the javascript wasn't making clear that the map variable in the initialize was also the map variable in the cmarkers function (sorry if the language isn't precise; I'm not great in js). See below:
function initialize() {
var rendererOptions = {
draggable: true,
panel:document.getElementById('directions_panel')
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
cmarkers();
function cmarkers() {
$.getJSON( "/mapeach.js", {}, function( data ) {
$.each( data, function( i, item ) {
var loc = item.mainlocation;
$("#markers").append('<li>' + loc.nickname + '</li>');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(+loc.latitude, +loc.longitude),
map: map,
title: loc.nickname,
});
markersArray.push(marker);
var infowindow = new google.maps.InfoWindow({
content: '<a class="clink" href="/spots/'+ loc.id +'/'+ loc.nickname +'" target="_blank">'+ loc.nickname +'</a>'
});
google.maps.event.addListener(marker, 'click', function() {
if (arrInfoWindows != null) {
arrInfoWindows.close();
}
infowindow.open(map,marker);
arrInfoWindows = infowindow;
});
});
});
};
Special credit to this post for giving me the idea: can't see google marker
So I'm setting up a dynamic Google map on all of the pages on the site to show the locations you can see on every page to help users understand the locations.
It works, but works EXTREMELY slow, so slow that if it has about 40+ it can take around 1 minute to load the map and if it's more locations than that on a page it just get stuck and does not load the map.
Here is a link to see the map:
http://www.exchange-currency.org/wakefield/
And Here's the code as it is on the website, you can also see the code with view source but note the addresses are from a string with php, you can see the output on the view source of the page.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?q=<?php the_title(); ?>&key=AIzaSyDeyknfWm0qmejgXZh_VXihNcHbidewODQ"></script>
<script type="text/javascript">
var delay = 10;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng();
var mapOptions = {
zoom: 4,
center: latlng,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = [<?php echo $locationAddresses; ?>];
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
What can I do to make it work in a normal speed so its actually usable?
Here's a link to a page with more locations so you'll see what I'm talking about:
http://www.exchange-currency.org/montreal/
Thanks!
Edit:
Also if there is a way to make it load async and with clusters instead of multiple markers that would be great, can't seem to get it figured out =/
Hi i'm trying to get markers latlon from ajax, i m getting ajax data every second and also able to create marker within radius , now i'm facing problem with updating marker positions as in current new marker created and old one also showing. Pls help to update markers which i am getting from ajax and remove extra.
var map = null;
var geocoder = null;
var markers = {};
var infoWindow = null;
var minZoomLevel = 16;
jQuery('#search').click(function() {
var address = jQuery('#address').val() || 'India';
if (map === null)
initializeMap();
searchAddress(address);
});
function initializeMap() {
var mapOptions = {
zoom: minZoomLevel,
draggable: true,
disableDefaultUI: true,
scrollwheel: true,
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
});
}
google.maps.event.addListener(map, "idle", function(event) {
searchStoresBounds();
});
geocoder = new google.maps.Geocoder();
infoWindow = new google.maps.InfoWindow();
}
function searchAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var latlng = results[0].geometry.location;
map.setCenter(latlng);
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
searchStoresBounds();
} else {
alert('Geocode was failed: ' + status);
}
});
}
setInterval(function searchStoresBounds() {
var bounds = map.getCenter().toUrlValue();
var url = './store.php';
var parameter = { bounds: bounds };
jQuery.ajax({
url: url,
data: parameter,
dataType: 'json',
success: showStores
});
}, 1000);
function showStores(data, status, xhr) {
if (data['status'] != 'OK')
return;
var id;
// add markers for new stores
for (id in data['data']) {
if (markers[id] === undefined)
createMarker(id, data['data'][id]);
}
var b = map.getBounds();
// remove markers out of the bounds
for (id in markers) {
if (! b.contains(markers[id].getPosition())) {
markers[id].setMap(null);
delete markers[id];
}else{createMarker(id, data['data'][id]);}
}
}
function createMarker(id, store) {
var latlng = new google.maps.LatLng(
parseFloat(store['lat']),
parseFloat(store['lng'])
);
var html = "<b>" + store['address'] + "</b>";
var x = store['distance'];
var y = 1000;
var z = x * y;
var m = 85;
var t = z / m;
document.getElementById("demo").innerHTML = Math.ceil(t);
var headm = store['bearing'];
var car = "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-
2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z
M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z
M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z
M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z";
var icon = {
path: car,
scale: .7,
strokeColor: 'White',
strokeWeight: .4,
fillOpacity: 1,
fillColor: '#333333',
offset: '5%',
rotation: parseInt(headm),
// rotation: parseInt(heading[i]),
anchor: new google.maps.Point(10, 25) // orig 10,50 back of car, 10,0 front of car, 10,25 center of car
};
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers[id] = marker;
}
You are facing the issue due to this part
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
Everytime you get data from ajax it creates a new marker.
Add the following declaration at the top of your js page
var marker;
and change the marker creation to the following
if(marker)
{
marker.setMap(null);
}
marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
Before you create a new marker the previous one is removed from the map. The if(marker) part is needed to check if a marker instance has been created because the first time that you run there will be no marker and you will get an error while trying to remove the marker.
Edit 1 :
As you have multiple markers you will need to store an array of markers and remove them before adding new markers on map
At the top of the page you will need to declare
var markerArray = new Array();
Just before you add the markers you will need to clear the previous markers
for(var i = 0; i<markerArray.length; i++)
{
markerArray[i].setMap(null);
}
markerArray = new Array()
After that will be your current code
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
markerArray.push(marker);
You will need to add the marker to the markerArray so that it can be cleared the next time your code executes.
I have a forloop that has a call to a function inside of it. Within that function, I'm pushing values to an array called markers.
Is there a way to access the values of the markers array outside of the forloop?
Here's the code:
<script type="text/javascript">
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var map = null;
geocoder = new google.maps.Geocoder();
var side_bar_html = "";
var icon = '';
var markers = [];
function codeAddress(this_address,index,callback) {
geocoder.geocode( { 'address': this_address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback.call(window,index,results[0].geometry.location)
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function initialize() {
// create the map
var myOptions = {
zoom: 3,
center: new google.maps.LatLng(46.90, -121.00),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
for (var i = 0; i < businesses.length; i++) {
codeAddress(businesses[i].address,i,function(i,point){
var description = businesses[i].description;
if(businesses[i].business_type == "Wine"){
//http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=A|00CC99|000000
icon = 'http://google-maps-icons.googlecode.com/files/wineyard.png';
}else if(businesses[i].business_type == "Golf"){
icon = 'http://google-maps-icons.googlecode.com/files/golf.png';
}else{
icon = 'http://google-maps-icons.googlecode.com/files/festival.png';
}
var marker = createMarker(point,businesses[i].name,description,icon);
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
});//End codeAddress-function
}//End for-loop
console.log(markers);
var markerCluster = new MarkerClusterer(map, markers);
}
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html,icon) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// save the info we need to use later for the side_bar
markers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (markers.length-1) + ')">' + name + '<\/a><br />'+html+'<br />';
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(markers[i], "click");
}
</script>
As you can see, the last line says "var markerCluster = new MarkerClusterer(map, markers);" This is where I want to be able to access the information from.
Thanks!
The problem is you're not accounting for the asynchronous nature of the call to codeAddress. You're calling that function in a loop, which is triggering a series of calls to the Google Maps API.
You are running this line:
var markerCluster = new MarkerClusterer(map, markers);
...even before the callbacks have been triggered.
To fix, maintain a counter. Each time the callback is triggered increase that counter by 1. Once it is equal to businesses.length you know all the addresses have been geo-coded, and all markers have been added to the array. Now you can create the MarkerCluster.
Yes, Declare it before the for loop.
var markers
for(....
Bring the definition of the marker outside of the for loop ...
var markers = new Array ();
for (var i = 0; i < businesses.length; i++) {
markers[i] = ...