3.4 Metro Web – Using “bounds” to autozoom to the extent of stops

Now that you have mapped the locations of a given bus route, you may have noticed that the map window did not automatically zoom to display all of the bus stop locations. Fortunately, there is a nice Google function that allows you to zoom to the extent of a given “bounds”. Bounds is defined by a bounding box, and its size can be determined by the extent of all points that fall inside of it. In other words, we can create a google “bounds” variable, add each bus stop location to it, and it will automatically adjust itself to generate a bounding box of all bus stop locations. You can then tell your maproom to “fit” the map to the bounds variable you created.

First, let’s create a new Google “bounds” variable in our global scope area.

Next, we need to define the bounds variable as a Google map LatLngBounds instance. Because we want to ensure that a new bounding box is created every time we request a new route, we will define the box inside of the “mapBusStops” function.

Next, we want to add each bus stop location to the “bounds” variable. This needs to happen every time the bus stop is created, so the call needs to be made inside of the “createStop” function. Also, we need to make sure that the map is “fit” to the extent of the “bounds”.

Now, when you refresh the page, the map should automatically zoom to the extent of all the stops on the requested route.

(sample site)

Leave a Reply