Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2014-10-24
5
Medium Priority
?
214 Views
Last Modified: 2014-11-03
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

0
Comment
Question by:Neil Thompson
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 59

Expert Comment

by:Julian Hansen
ID: 40401739
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
 
LVL 3

Author Comment

by:Neil Thompson
ID: 40401904
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
 
LVL 59

Accepted Solution

by:
Julian Hansen earned 2000 total points
ID: 40403083
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
 
LVL 3

Author Closing Comment

by:Neil Thompson
ID: 40419127
Many thanks. Apologies for the delay in accepting, just back from hols. Neil
0
 
LVL 59

Expert Comment

by:Julian Hansen
ID: 40419190
You are welcome - good luck with it.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question