Solved

google maps autozoom to fit locations

Posted on 2011-02-28
5
1,698 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.

707 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

17 Experts available now in Live!

Get 1:1 Help Now