Esri JavaScript map center, zoom level and extent





Using jsformat with Sublime Text 26th July, 2014

There are many d3 demos like this but this one is mine 08th June, 2014


Esri JavaScript map center, zoom level and extent

Posted on .

Several times a day, I need to find one or more of the following from a map on a web page using the Esri JavaScript API:

  • map center
  • map zoom level
  • map extent AKA bounding box

Most of the time, I want this info because I need it for a map I’m putting in something I’m building. I prefer that the map’s center is printed as a two element array with two floats (each with three decimal places, which is sufficient for a location specified in geographic coordinates), zoom level should be an integer and extent should be a string version of an object I can pass to esri/geometry/Extent. Extent coordinates should be integers since I’m almost always working in web mercator where decimal places mean very little and can be ignored.

Below are code snippets I run in a browser’s console for my preferred way to get each one. Use the simple map sample if you’d like to try these out on your own.

Map center:

(function(){require(["esri/geometry/webMercatorUtils"],function(w){var c=w.webMercatorToGeographic(map.extent.getCenter());console.log([parseFloat(c.x.toFixed(3)), parseFloat(c.y.toFixed(3))]);});})();

Example output:

[-122.45, 37.768]

Map zoom level:


Example output:


Map extent:

(function(){require(["dojo/json"],function(j){console.log(j.stringify(function(){var e=map.extent.toJson();e.xmin=parseInt(e.xmin);e.ymin=parseInt(e.ymin);e.xmax=parseInt(e.xmax);e.ymax=parseInt(e.ymax);return e;}()));})})();

Example output:


Admittedly, a couple of those are pretty ugly, but they get the job done. Rather than copy and paste these all day, or worse, type them each time, I use a wonderful little utility called TextExpander to map those snippets to shorter strings. I’m sure there are other utilities to do the same thing but I can’t recommend any since TextExpander works so well and I’ve never needed to search for alternatives.

When I want the map’s center, I open the browser’s console and type ;;center. For zoom level, I use ;;zoom. Extent? You guessed it: ;;extent. I use double semi-colon as the prefix for all my snippets so I don’t accidentally trigger these (I think this is semi-common among TextExpander users, I probably picked it up from Merlin Mann or Brett Terpstra).

One caveat with all of this stuff: a page’s map has to be available via a global variable. If a page’s map isn’t global, you’re out of luck.


Author Tom

Posted at 10:59 am February 20, 2014.

Great tips! Thanks for sharing!


Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

View Comments (2) ...