Solved

google maps autozoom to fit locations

Posted on 2011-02-28
5
1,713 Views
Last Modified: 2012-08-13
I have some test code which is firing locations to a google map via javascript.
If I enter two locations that are beyond the current screen size pr zoom level is there a way to fire an auto zoom function to automatically resize the map to allow viewing of all markers?
0
Comment
Question by:Lmillard
  • 2
  • 2
5 Comments
 
LVL 9

Accepted Solution

by:
EZFrag earned 250 total points
ID: 35005303
Hi There,

There is a way of doing this, it will just take a bit of coding...

http://econym.org.uk/gmap/basic14.htm

Basically, as you create your map markers, you add them to a GLatLngBounds:

 var bounds = new GLatLngBounds();
bounds.extend(point1);
bounds.extend(point2);
bounds.extend(point3);

Open in new window


After that you get the recommended zoom level and re-center the map:

map.setZoom(map.getBoundsZoomLevel(bounds));
map.setCenter(bounds.getCenter());

Open in new window


Hope it helps ^_^
0
 

Author Comment

by:Lmillard
ID: 35006378
I'm not sure what I am doing wrong, at the point the script hits bounds.extend it breaks. I am a total newbie with Google maps so i may just be being stupid here.

The var bounds = new GLatLngBounds() is being declared further up the page so not present in the code below but basically I have two input fields and as I enter a city in one it executes the function below and then executes it again when I input a city in the next input box.  The map centers on the city as it is located and then I would like it to extend as required. Pretty sure that is what the code you advised is doing so must be my implementation, can you see anything obvious?
function checkLocationExists(addString,resultDiv) {
	showGmap();
    var address = addString;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
		var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location,
			title: address
        });
//			bounds.extend(results[0].geometry.location);
//			alert(bounds.getCenter());
//			map.setZoom(map.getBoundsZoomLevel(bounds));
//			map.setCenter(bounds.getCenter());

		document.getElementById(resultDiv).innerHTML = '<img src="assets/img/frontend/iconTick.png">';
      } else {
		document.getElementById(resultDiv).innerHTML = '<img src="assets/img/frontend/iconDelete.png">';
      }
    });
}

Open in new window

0
 
LVL 9

Expert Comment

by:EZFrag
ID: 35009945
Your logic seems to be 100%. is there a chance that you can pass on the full code?

Alternatively, do you know what the error message is that you are recieving when it hits the bounds.extent?

REgards,
EZFrag
0
 
LVL 3

Assisted Solution

by:timhigham
timhigham earned 250 total points
ID: 35012203
Google maps API.
"arrrrrrrrrrrrrrrrrrrrrrrrggggggg" - debuging is a nightmare as this API code is extremely obfusticated. Understandable as certain organisations starting with 'M' have started parasiting on Google resources !
Initial comment noticed above is the 'G' prefix in suggested code which indicates V2 or earlier prefix - this is deprecated. This means it might work for a bit until Google withdraw it. So at any random point you will have a lot of reprogramming to do to get functions using it to work when they are removed.
I know this having spent 2 months trying to convert as there are several functions not in V3 that were in V2.
Your solution is mathematical. You will obviously require to iterate the entire group of points, getting the furthest extremes of Lat range (from north to south) and the Lng range (west to east).
This will give you a rectangle (containing all points) where by you can set center on mid point of all these ranges. Its now a question of zooming.
Already the user can zoom in and out using existing map controls to see the whole collection of points.
However you can further use map class 'google.maps.Map' class function 'panToBounds' to frame this after setting bounds definition by 'google.maps.LatLngBounds' which Google defines as setting the minimal range to to show this rectangle.
0
 

Author Comment

by:Lmillard
ID: 35016159
I have had a bit of a nightmare with this but it does seem to come down to versions.
I have messed about and the following code works a treat, this is a combo of the code posted by EZfrag and version control suggestions from timhigham so thanks to both. It basically came down to the functions either being renamed and called slightly differently.

I am going to be posting a few other google maps questions so if you happen to notice them your feedback would be much appreciated as you both know what your doing and I am only just starting to grasp it all!

Big thanks
Leigh
function checkLocationExists(addString,resultDiv) {
	showGmap();
    var address = addString;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
		var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location,
			title: address
        });
			bounds.extend(results[0].geometry.location);
			map.fitBounds(bounds);
		document.getElementById(resultDiv).innerHTML = '<img src="assets/img/frontend/iconTick.png">';
      } else {
		document.getElementById(resultDiv).innerHTML = '<img src="assets/img/frontend/iconDelete.png">';
      }
    });
}

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Get to know the ins and outs of building a web-based ERP system for your enterprise. Development timeline, technology, and costs outlined.
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
The viewer will learn how to dynamically set the form action using jQuery.

920 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

14 Experts available now in Live!

Get 1:1 Help Now