Use Proj4js alongside the ArcGIS API for JavaScript to reproject coordinates on the fly

Blog Post created by JGravois-esristaff Employee on Nov 3, 2014

In technical support, I spoke to lots of folks who wanted to display the latitude and longitude of the current mouse position continuously in their JavaScript applications when using a basemap with a custom projection.  Out of the box the ArcGIS API for JavaScript supports reprojecting pretty much any coordinates you can think of, but if you aren't converting between WGS84 and Web Mercator, its necessary to leverage a geometry service in order to get some help with the math.


Our Geometry Service is an awesome tool that help with all sorts of manipulations and analysis including buffering, calculating convex hulls, decreasing vertex density and reshaping and can work on a collection of features simultaneously, but in this scenario its kind of like bringing out a chainsaw to cut your sandwich in half.


The time it takes to send off the request and wait for the response makes it infeasible to continuously reproject the current location of the mouse.  Thankfully there is an open source JavaScript library called Proj4js that can help.  After loading Proj4js and giving it some information about the two coordinate systems you'd like to reproject, you can get the answer you need directly in the browser.


Screenshot 2014-11-01 12.35.06.png


These are the basic steps you'll need to follow:


1. load Proj4js alongside the JSAPI in your application using an additional script tag

<!-- load proj4js from CDN -->
<script src="//cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.3/proj4.js"></script>
<!-- then load the ArcGIS API for JavaScript-->
<script src="//js.arcgis.com/3.11/"></script>


2. define two custom projections in a format that Proj4js will understand (check out the project in Github for more information on formatting)

var wkid4269 = '+proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees';
var wkid26912 = '+proj=utm +zone=12 +ellps=GRS80 +datum=NAD83 +units=m +no_defs';


3. lastly, wire an event listener so that proj4js can calculate the reprojection each time the mouse moves over the map

map.on("mouse-move", function(evt){
  var reprojectedCoords = proj4(wkid26912, wkid4269, [evt.mapPoint.x, evt.mapPoint.y]);


you can find a live sample which displays latitude and longitude coordinates in an interactive UTM 12N map here: