Google Maps - Make the map zoom to include all my markers

Hi

I have the following code that plots 5 random local businesses on a map. At present this just loads them zoomed in to the default so there is a lot of space around them on the map which is unnecessary.

I would like to be able to display these within the bounds of the map so for instance rather than this:
nig space around locationsI get this:
locations fit to map space
Ideally I would also be able to number them similar to this, is that possible?
numerically labled
### NOTE, although these are all local at present they could be anywhere in UK so I cannot just set a default scale etc ###

    

	<div id="map_canvas_local_businesses" style="width:400px;height:300px;"></div>

       <script type="text/javascript" src="//maps.google.com/maps/api/js?sensor=false"></script>
       <script type="text/javascript">
        
		var infowindow = null;		
    
		var centerMap = new google.maps.LatLng(51.421196,0.392989);

		var myOptions = {
			zoom: 7,
			center: centerMap,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}

		var map = new google.maps.Map(document.getElementById("map_canvas_local_businesses"), myOptions);
		
		var sites = [["A1 Carpet Guard","51.409184","0.182972","33 Main Road Hextable"], ["Medway Clearance","51.467670","0.643445","Saint Matthew's Way, Allhallows, Rochester, Kent"], ["STN Entertainment","51.360817","0.510236","City Way, Rochester, Kent"], ["My Forever Beauty","51.334141","0.541469","Renown Road, Chatham, Kent"], ["CleanSmart Solutions","51.340851","0.533211","McKenzie Road, Chatham, Kent"]];		
		setMarkers(map, sites);
		
		infowindow = new google.maps.InfoWindow({
			content: "loading..."
		});						      
		
		
        function setMarkers(map, markers) {
			    
            for (var i = 0; i < markers.length; i++) {
				
                var sites = markers[i];
                var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
				 
                var marker = new google.maps.Marker({
                    position: siteLatLng,
                    map: map,
                    title: sites[0],
                    zIndex: i,
                    html: '<div style="min-height:90px;min-width:180px;text-align:right;"><h3>test</p><div>'
                });				
    
                google.maps.event.addListener(marker, "click", function () {
                    infowindow.setContent(this.html);
                    infowindow.open(map, this);
                });
				
            }
        } 

    </script>
    

Open in new window

LVL 3
Neil ThompsonSenior Systems DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
The article in the following link discusses how to do this with code

http://blog.shamess.info/2009/09/29/zoom-to-fit-all-markers-on-google-maps-api-v3/

Code snippet from the above shown below
//  Make an array of the LatLng's of the markers you want to show
var LatLngList = new Array (new google.maps.LatLng (52.537,-2.061), new google.maps.LatLng (52.564,-2.017));
//  Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
//  Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
  //  And increase the bounds to take this point
  bounds.extend (LatLngList[i]);
}
//  Fit these bounds to the map
map.fitBounds (bounds);

Open in new window

0
Neil ThompsonSenior Systems DeveloperAuthor Commented:
Thanks Julian

I've tried adding that to the code but it doesn't seem to make a difference, it doesnt seem to zoom to fit all in, rather just displays them all by being zoomed right out still

    
    <script>
    var sites = [["Amazing Amber ","51.405945","0.536290","Samphire Way, St Mary's Island, Chatham, Kent"], ["JD Carpentry","51.136032","0.228172","52 High Street, Rusthall, Royal Tunbridge Wells, Kent"], ["Kids Bee Happy Dartford","51.443970","0.209283","Miskin Road, Dartford, Kent"], ["Love to bake cake shop","51.372433","0.558175"," 119 Watling Street, Chatham, Gillingham, Kent"], ["Medway Clearance","51.467670","0.643445","Saint Matthew's Way, Allhallows, Rochester, Kent"]];

var siteLatLng = "new google.maps.LatLng(51.405945,0.536290),new google.maps.LatLng(51.136032,0.228172),new google.maps.LatLng(51.443970,0.209283),new google.maps.LatLng(51.372433,0.558175),new google.maps.LatLng(51.467670,0.643445)";    </script>
    

	<div id="map_canvas_local_businesses" style="width:400px;height:300px;"></div>

       <script type="text/javascript" src="//maps.google.com/maps/api/js?sensor=false"></script>
       <script type="text/javascript">
        
		var infowindow = null;		
    
		var centerMap = new google.maps.LatLng(51.421196,0.392989);

		var myOptions = {
			zoom: 7,
			center: centerMap,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}

		var map = new google.maps.Map(document.getElementById("map_canvas_local_businesses"), myOptions);
		
		setMarkers(map, sites);
		
		infowindow = new google.maps.InfoWindow({
			content: "loading..."
		});	
					 		
		// fit the map to selected lat/lng bounds			
		var LatLngList = new Array(siteLatLng);			
		var bounds = new google.maps.LatLngBounds();				
		for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
		  bounds.extend (LatLngList[i]);
		  alert("test:"+LatLngList[i]);
		} 				
		map.fitBounds (bounds);	
		
		//	
        function setMarkers(map, markers) {
			    
            for (var i = 0; i < markers.length; i++) {
				
                var sites = markers[i];
                var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
				 
                var marker = new google.maps.Marker({
                    position: siteLatLng,
                    map: map,
                    title: sites[0],
                    zIndex: i
                });				
    
                google.maps.event.addListener(marker, "click", function () {
                    infowindow.setContent(this.html);
                    infowindow.open(map, this);
                });
				
			}
		}

    </script>
    

Open in new window

0
Julian HansenCommented:
Two things that come to mind

1. The location of your google maps script include
<script type="text/javascript" src="//maps.google.com/maps/api/js?sensor=false"></script>

Open in new window

Seems to me this should be above your other script

2. Your siteLatLng variable is a string which you are putting into an array - but all that is doing is creating an array with 1 string value. In other words there is no where that you are converting that string value into an actual array of co-ordinates.

Try changing your script to this
<!doctype html>
<html>
<head>Test</head>    
<!-- THIS MUST BE INCLUDED BEFORE YOU CAN USE MAPS FUNCTIONS
SEE WHERE siteLatLng  CHANGED FROM STRING TO ARRAY -->
<script type="text/javascript" src="//maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var sites = [["Amazing Amber ","51.405945","0.536290","Samphire Way, St Mary's Island, Chatham, Kent"], ["JD Carpentry","51.136032","0.228172","52 High Street, Rusthall, Royal Tunbridge Wells, Kent"], ["Kids Bee Happy Dartford","51.443970","0.209283","Miskin Road, Dartford, Kent"], ["Love to bake cake shop","51.372433","0.558175"," 119 Watling Street, Chatham, Gillingham, Kent"], ["Medway Clearance","51.467670","0.643445","Saint Matthew's Way, Allhallows, Rochester, Kent"]];

// CAN'T SEE WHY YOU MADE THIS A STRING
// JUST MAKE IT AN ARRAY
  var siteLatLng = [new google.maps.LatLng(51.405945,0.536290),new google.maps.LatLng(51.136032,0.228172),new google.maps.LatLng(51.443970,0.209283),new google.maps.LatLng(51.372433,0.558175),new google.maps.LatLng(51.467670,0.643445)];
</script>
</head>
<body>
  <div id="map_canvas_local_businesses" style="width:400px;height:300px;"></div>
<script type="text/javascript">
        
var infowindow = null;    

var centerMap = new google.maps.LatLng(51.421196,0.392989);

var myOptions = {
  zoom: 7,
  center: centerMap,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}

var map = new google.maps.Map(document.getElementById("map_canvas_local_businesses"), myOptions);

setMarkers(map, sites);

infowindow = new google.maps.InfoWindow({
  content: "loading..."
});  
          
// fit the map to selected lat/lng bounds      
// YOU SHOULD REFACTOR THIS
// LatLngList IS NOT NECESSARY
// THIS IS JUST TO ILLUSTRATE HOW I GOT HERE
var LatLngList = siteLatLng; // new Array(siteLatLng);      
console.log(LatLngList);
var bounds = new google.maps.LatLngBounds();        
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
  bounds.extend (LatLngList[i]);
}         
map.fitBounds (bounds);  
    
//  
function setMarkers(map, markers) {
    
  for (var i = 0; i < markers.length; i++) {
    
    var sites = markers[i];
    var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
     
    var marker = new google.maps.Marker({
      position: siteLatLng,
      map: map,
      title: sites[0],
      zIndex: i
    });        

    google.maps.event.addListener(marker, "click", function () {
      infowindow.setContent(this.html);
      infowindow.open(map, this);
    });
    
  }
}
</script>
</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Neil ThompsonSenior Systems DeveloperAuthor Commented:
Many thanks. Apologies for the delay in accepting, just back from hols. Neil
0
Julian HansenCommented:
You are welcome - good luck with it.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.