By default, a map will initialize to fit all of its layers. However, you may prefer that it be zoomed in on a particular area instead of opening to the full extent. Example 1 builds on the hometown map by setting the map's extent. It does so by creating a new Extent object from a set of four bounding coordinates. The SpatialReference of the Extent object is set to match that of the base map. The Extent object (stored in the startExtent variable) is then used to set the Map's extent property within its constructor.
Example 2 shows a page containing a world topo map that initializes zoomed in on a Louisville land records layer. (It is adapted from this Esri sample.) Refer to the source code to follow along with the discussion below.
The code from this example is a bit complicated as compared to the previous ones. The ultimate goal is to set the Map's extent to match the extent held in the fullExtent property of the Louisville map service layer. However, it is important to wait to read a layer's properties until it's finished loading. Thus, this page includes code that tests whether both layers have successfully loaded before creating the map. Note that the script sets up listeners for the layers' load events, increments a counter variable by 1 when a layer has been loaded, and calls to the createMapAddLayers() function when that counter reaches 2. Unfortunately, the script is further complicated by behavior in Internet Explorer that is documented on Esri's 'Working with Events' page:
In Internet Explorer, due to resource caching, the onLoad event is fired as soon as the layer is constructed. Consequently you should check whether the layer's loaded property is true before registering a listener for the load event..."
This IE behavior is the reason why the lines that increment the counter and call the createMapAddLayers() function are duplicated for each layer.
The createMapAddLayers() function is set up to accept two map service layers as arguments. When the Map is created, note that the Map's extent property is set to the second layer's fullExtent as part of the constructor. Also note that the basemap property is not set as in earlier examples. Instead, the layer in myService1 serves as the basemap after it's added.
Event listeners like those discussed in the example above require memory and unless additional steps are taken that memory will remain tied up unnecessarily when the map is closed. Read on to see how to prevent such memory leaks.