Solved

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

Posted on 2014-10-24
5
196 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:NeilT
  • 3
  • 2
5 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
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:NeilT
Comment Utility
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 51

Accepted Solution

by:
Julian Hansen earned 500 total points
Comment Utility
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:NeilT
Comment Utility
Many thanks. Apologies for the delay in accepting, just back from hols. Neil
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
You are welcome - good luck with it.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
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…

763 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now