Setting the center of map programmatically

By Daniel Du

Q:

I want to zoom a map to screen center without changing the scale, how can I do it?

A:

In Map 3D, if you have connected to FDO data sources and added them to map, you can call AcMapMap.ZoomToExtent() to set the new extent of map. It accepts a parameter of MgEnvelope type. If you do not have any FDO data source, you have to use AutoCAD APIs.

Here is the code snippet:

[CommandMethod("ZoomCenter")]
public void ZoomCenter()
{
 
  Document doc = Application.DocumentManager.MdiActiveDocument;
  Database db = doc.Database;
  Editor ed = doc.Editor;
 
  Point3d centerPt;
  PromptPointOptions ppo = new PromptPointOptions(
                "Click on map to zoom center:");
  PromptPointResult ppr = ed.GetPoint(ppo);
  if (ppr.Status == PromptStatus.OK)
  {
    centerPt = ppr.Value;
 
    AcMapMap map = AcMapMap.GetCurrentMap();
    MgEnvelope mapExtent = map.GetMapExtent();
 
    //There are some FDO feature source connected 
    if (!mapExtent.IsNull())
    {
      double centerX = mapExtent.LowerLeftCoordinate.X 
                                    + mapExtent.Width / 2;
      double centerY = mapExtent.LowerLeftCoordinate.Y 
                                    + mapExtent.Height / 2;
 
      ed.WriteMessage("center:" + centerX.ToString() + "," 
                                + centerY.ToString() + "n");
 
      MgEnvelope newExtent = new MgEnvelope(
          centerPt.X - mapExtent.Width  / 2,
          centerPt.Y - mapExtent.Height / 2,
          centerPt.X + mapExtent.Width  / 2,
          centerPt.Y + mapExtent.Height / 2);
 
      map.ZoomToExtent(newExtent);
    }
    else
    {
      //no FDO data source, use AutoCAD API
 
      using (Transaction Tx = db.TransactionManager.StartTransaction())
      {
        ed.UpdateTiledViewportsInDatabase();
 
        ViewportTableRecord viewportTableRec = Tx.GetObject(
                ed.ActiveViewportId, OpenMode.ForWrite) 
                as ViewportTableRecord;
 
        viewportTableRec.CenterPoint = new Point2d(centerPt.X, centerPt.Y);
 
        ed.UpdateTiledViewportsFromDatabase();
 
        Tx.Commit();
      }
 
    }
 
 
  }
 
}

Hope this helps.


Comments

One response to “Setting the center of map programmatically”

  1. Daniel,
    Thanks very much for this function. It helped me greatly. I created a modified version of this function to zoom to a specific point on a map at a specific scale. I need for the zoom to occur when called from the click event handler of a button on a modal form.
    The problem is that the zoom does not occur until the user closes the modal form. I’ve tried everything I can think of and posted on the boards.
    Any ideas? Thanks again!
    Steve

Leave a Reply to Steve FinchCancel reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading