Tip: Don't use "map" for HTML div and JavaScript variable

5486
1
01-16-2015 02:06 PM
BryanBaker
Occasional Contributor

Tip for developers: avoid the pattern used in the JavaScript API samples that use "map" for the map HTML div and JavaScript variable. So instead of this:

<script>

  var map;

  require(["esri/map", "dojo/domReady!"], function(Map) {

  map = new Map("map", {

   basemap: "topo",

   center: [-122.45, 37.75], // longitude, latitude

   zoom: 13

  });

  });

</script>

</head>

<body>

<div id="map"></div>

</body>

Do something like this instead:

<script>

  var mapObj;

  require(["esri/map", "dojo/domReady!"], function(Map) {

  mapObj = new Map("mapDiv", {

   basemap: "topo",

   center: [-122.45, 37.75], // longitude, latitude

   zoom: 13

  });

  });

</script>

</head>

<body>

<div id="mapDiv"></div>

</body>

Why? The JavaScript engine (at least some of them) will use a div instead of a JS variable if a variable of that name doesn't exist. This can lead to confusing errors. If you later change the name of the map object, but use "map" as the JS map object, JavaScript will instead substitute the HTML div as the object used. That div is not the same thing as the map object! You will likely then get an odd error sometime later when the code tries to use that div as if it were the map object, since it has none of the same methods and properties. I ran into that problem as discussed in this forum post: https://community.esri.com/message/450315

This extends generally to all IDs and JavaScript variables - don't overlap names. These days most applications create a few custom objects and store objects within those few, which is a good practice for avoiding this kind of problem.

I would like to see ESRI modify the JS API samples to remove these name overlaps, since developers tend to use code as-is from samples.

0 Kudos
1 Reply
ChrisSergent
Regular Contributor III

I use this for my map in HTML5:

<!-- Map Section Begin -->

<section id="mapSection">

</section>

<!-- Map Section End -->

And in my JavaScript, I use this:

// create map and set slider style to small
            map = new Map("mapSection", {
                showAttribution: false,
                sliderStyle: "small",
                extent: initialExtent,
                logo: false
            });

I still use map for the first because I have other objects where it displays map:map and I am not sure how those work.

0 Kudos