[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1941
  • Last Modified:

google maps autozoom to fit locations

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
Lmillard
Asked:
Lmillard
  • 2
  • 2
2 Solutions
 
EZFragCommented:
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
 
LmillardAuthor Commented:
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
 
EZFragCommented:
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
 
timhighamCommented:
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
 
LmillardAuthor Commented:
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

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now