[GIS] Center And Zoom function using ArcGIS API for JavaScript

arcgis-javascript-apizoom

I'm trying to insert x, and y coordinates manually through input text, and center the map and zoom it to that point. I have this code:

var x = $("#x").val();
var y = $("#y").val();
var point=new esri.geometry.Point(x, y, map.spatialReference);
map.centerAndZoom(point,6);

When executing this code, it gives me a blank page. What's wrong?
I also tried this code:

  map.graphics.clear();
  var xMin, yMin, xMax, yMax;
  var mp = new esri.geometry.Point;

  mp.x = $("#x").val();
  mp.y = $("#y").val();
  mp.spatialReference = map.spatialReference;
  var symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CROSS, 30, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0]), 1), new dojo.Color([0,255,0,0.25]));
  var graphic = new esri.Graphic(mp, symbol);
  xMin = mp.x-1000;
  yMin = mp.y-1000;
  xMax = mp.x+1000; 
  yMax = mp.y+1000;

  var newExtent = new esri.geometry.Extent();
  newExtent.xmin = xMin;
  newExtent.ymin = yMin;
  newExtent.xmax = xMax;
  newExtent.ymax = yMax;

  newExtent.spatialReference = map.spatialReference;

  map.setExtent(newExtent);
  map.graphics.add(graphic);

Also does not work. Any help??

Best Answer

I just finished doing something very similar so perhaps this will help you. I'm not using map.setExtent though (except as a fallback). Instead I'm using map.centerAndZoom. Right after I add the graphic, I have this bit of code. I'm thinking this may point you in the right direction (instead of maxZoom, you may be able to plug that zoom level 6 in?). One other difference is that I'm using a graphics layer ("esri/layers/GraphicsLayer") and adding the graphic to that instead of directly to map.graphics. Try adding this (after my comment line) after you add the graphic to the map.

EDIT: I do also have this line further up in the script.

var mp = webMercatorUtils.webMercatorToGeographic(evt.mapPoint);

graphicsLayer = new GraphicsLayer();  
graphicsLayer.add(graphic);  

map.addLayer(graphicsLayer);
// Add this bit of code after adding your graphic, 
if (graphic.geometry.type === 'point') {  
    maxZoom = map.getMaxZoom();  
    map.centerAndZoom(graphic.geometry, maxZoom - 1);  
} else {  
    map.setExtent(graphicsUtils.graphicsExtent([graphic]));        
} // end if

EDIT: I took out the second else per your commment. I was doing this nested inside a second if block that tests for the presence of a comma in a string entered by a user (lat, long) and the first if is testing for the index of the ",". I don't know what else you would need to do because this is working for me.