Thread
Print

Center Map(C#)

This topic has been move by admin at 3-9-2008 13:41.

Center Map(C#)

Introduction
  This sample describes how to center the map by MapPoint.

Note:
  Before you run this sample,you must apply a map point evaluation account on MS site. https://mappoint-css.live.com/MwsSignUp/eval.aspx and then open app.config in your project and type your name and password   in <add key="MPUser" value="" /> <add key="MPPass" value="" />.

Using the code
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Configuration;
using System.Security.Permissions;
using ClickToCenterMap.MapPointService;

[assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)]

namespace ClickToCenterMap
{
/// <summary>
// This sample centers the map on whichever point is clicked.  
// The pixel coordinate of the clicked point is converted to a
// lat/long coordinate.  This lat/long coordinate is passed in as the
// center of the map and the map is re-rendered.  The lat/long
// coordinate is also used to get the county the point is located in.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
  private System.Windows.Forms.PictureBox pictureBox1;
  private System.Windows.Forms.Label labelXCoordinate;
  private System.Windows.Forms.Label labelYCoordinate;
  private System.Windows.Forms.Label labelLatitude;
  private System.Windows.Forms.Label labelLongitude;
  private System.Windows.Forms.Label labelEntities;
  private System.Windows.Forms.Label labelInstructions;

  /// <summary>
  /// Required designer variable.
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   //
   // Required for Windows Form Designer support
   //
   InitializeComponent();
  }
   

  /// <summary>
  /// Clean up any resources being used.
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }

   if(renderService != null)
   {
    renderService.Dispose();
   }

   if(findService != null)
   {
    findService.Dispose();
   }

   base.Dispose( disposing );
  }

  #region Windows Form Designer generated code
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {
   this.pictureBox1 = new System.Windows.Forms.PictureBox();
   this.labelInstructions = new System.Windows.Forms.Label();
   this.labelXCoordinate = new System.Windows.Forms.Label();
   this.labelYCoordinate = new System.Windows.Forms.Label();
   this.labelLatitude = new System.Windows.Forms.Label();
   this.labelLongitude = new System.Windows.Forms.Label();
   this.labelEntities = new System.Windows.Forms.Label();
   this.SuspendLayout();
   //
   // pictureBox1
   //
   this.pictureBox1.Location = new System.Drawing.Point(8, 40);
   this.pictureBox1.Name = "pictureBox1";
   this.pictureBox1.Size = new System.Drawing.Size(384, 280);
   this.pictureBox1.TabIndex = 0;
   this.pictureBox1.TabStop = false;
   this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
   //
   // labelInstructions
   //
   this.labelInstructions.Location = new System.Drawing.Point(8, 8);
   this.labelInstructions.Name = "labelInstructions";
   this.labelInstructions.Size = new System.Drawing.Size(360, 23);
   this.labelInstructions.TabIndex = 1;
   this.labelInstructions.Text = "Click to center the map.";
   //
   // labelXCoordinate
   //
   this.labelXCoordinate.Location = new System.Drawing.Point(8, 328);
   this.labelXCoordinate.Name = "labelXCoordinate";
   this.labelXCoordinate.Size = new System.Drawing.Size(192, 23);
   this.labelXCoordinate.TabIndex = 2;
   this.labelXCoordinate.Text = "labelXCoordinate";
   //
   // labelYCoordinate
   //
   this.labelYCoordinate.Location = new System.Drawing.Point(8, 360);
   this.labelYCoordinate.Name = "labelYCoordinate";
   this.labelYCoordinate.Size = new System.Drawing.Size(192, 23);
   this.labelYCoordinate.TabIndex = 3;
   this.labelYCoordinate.Text = "labelYCoordinate";
   //
   // labelLatitude
   //
   this.labelLatitude.Location = new System.Drawing.Point(208, 328);
   this.labelLatitude.Name = "labelLatitude";
   this.labelLatitude.Size = new System.Drawing.Size(192, 23);
   this.labelLatitude.TabIndex = 4;
   this.labelLatitude.Text = "labelLatitude";
   //
   // labelLongitude
   //
   this.labelLongitude.Location = new System.Drawing.Point(208, 360);
   this.labelLongitude.Name = "labelLongitude";
   this.labelLongitude.Size = new System.Drawing.Size(192, 23);
   this.labelLongitude.TabIndex = 5;
   this.labelLongitude.Text = "labelLongitude";
   //
   // labelEntities
   //
   this.labelEntities.Location = new System.Drawing.Point(8, 392);
   this.labelEntities.Name = "labelEntities";
   this.labelEntities.Size = new System.Drawing.Size(392, 80);
   this.labelEntities.TabIndex = 6;
   this.labelEntities.Text = "labelEntities";
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
   this.ClientSize = new System.Drawing.Size(440, 486);
   this.Controls.AddRange(new System.Windows.Forms.Control[] {
                    this.labelEntities,
                    this.labelLongitude,
                    this.labelLatitude,
                    this.labelYCoordinate,
                    this.labelXCoordinate,
                    this.labelInstructions,
                    this.pictureBox1});
   this.Name = "Form1";
   this.Text = "Click To Center Map";
   this.Load += new System.EventHandler(this.Form1_Load);
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// The main entry point for the application.
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }


  // The Form1_Load event sets up the service variables and
  // initializes the map.

  MapImage currentMapImage;
  RenderServiceSoap renderService = new RenderServiceSoap();
  FindServiceSoap findService = new FindServiceSoap();

  private void Form1_Load(object sender, System.EventArgs e)
  {
   // Set up the service variables, and get application
   // settings from the config file.
   string myUserID = ConfigurationManager.AppSettings.Get("MPUser");
   string myPassword = ConfigurationManager.AppSettings.Get("MPPass");
   NetworkCredential myCredentials = new NetworkCredential(myUserID, myPassword);

   renderService.Credentials = myCredentials;
   renderService.PreAuthenticate = true;
      
   findService.Credentials = myCredentials;
   findService.PreAuthenticate = true;


            // Set a coordinate in which to center the map the first time the page loads.
   LatLong myLatLong = new LatLong();
   myLatLong.Latitude = 47.617907780749;
   myLatLong.Longitude = -122.316857443578;

   // Hide the coordinate and entity display labels the first time the page loads.
   labelXCoordinate.Visible = false;
   labelYCoordinate.Visible = false;
   labelLatitude.Visible = false;
   labelLongitude.Visible = false;
   labelEntities.Visible = false;
            
   // Get the map image, and display it.
   currentMapImage = renderMap(myLatLong);
            
  }

  private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
  {
   try
   {
                // Create a MapImage object to hold the most recently viewed map.
                MapImage myMapImage = currentMapImage;

                // Create a PixelCoord array to store the clicked pixel coordinate.
                PixelCoord[] myPixelCoords = new PixelCoord[1];
                myPixelCoords[0] = new PixelCoord();
    myPixelCoords[0].X = e.X;
    myPixelCoords[0].Y = e.Y;
            
    // Convert the pixel coordinates into a lat/long coordinate,
    // and store them in a LatLong array.
    LatLong[] myLatLongs = renderService.ConvertToLatLong(myPixelCoords, myMapImage.View.ByHeightWidth, pictureBox1.Size.Width, pictureBox1.Size.Height);

    // Use the lat/long value of the centerpoint to get the associated county.
    string[] entitiesToReturn = new string[1];
    entitiesToReturn[0] = "AdminDivision2";
            
    GetInfoOptions entityOptions = new GetInfoOptions();
    entityOptions.IncludeAddresses = false;
    entityOptions.IncludeAllEntityTypes = false;
    entityOptions.EntityTypesToReturn = entitiesToReturn;
      
    Location[] nearbyLocations = findService.GetLocationInfo(myLatLongs[0],"MapPoint.NA",entityOptions);

    // If the request was successful, display the county associated with the center point,
                // or inform the user that no county is associated with the center point.
    if (nearbyLocations.Length > 0)
    {
     labelEntities.Text = "The center point of the map is in the following county: \n"
      + nearbyLocations[0].Entity.DisplayName;
    }
    else
    {
     labelEntities.Text = "No county entity is associated with the center point of the map.";
    }
   

    // Write the coordinate, and lat/long values, into the labels.
    labelXCoordinate.Text = "Pixel coordinate X: " + e.X.ToString();
    labelYCoordinate.Text = "Pixel coordinate Y: " + e.Y.ToString();
    labelLatitude.Text = "Latitude: " + myLatLongs[0].Latitude.ToString("#.#####");
    labelLongitude.Text = "Longitude: " + myLatLongs[0].Longitude.ToString("#.#####");

    // Display the labels.
    labelXCoordinate.Visible = true;
    labelYCoordinate.Visible = true;
    labelLatitude.Visible = true;
    labelLongitude.Visible = true;
    labelEntities.Visible = true;

    // Get and display the map.
    myMapImage= renderMap(myLatLongs[0]);
    if (myMapImage!=null)
    {
     currentMapImage = myMapImage;
    }

   }
            
   catch(Exception ex)
   {
    // If an error occurred in the GetLocationInfo or ConvertToLatLong call,
    // report it in the label.
    labelEntities.Text = "An error occurred: " + ex.Message;
   }
   
            
  }

        
  private MapImage renderMap(LatLong myLLC)
  {
   // Create the ImageFormat object, and set the
   // height and width of the image to return.
   ImageFormat myImageFormat = new ImageFormat();
   myImageFormat.Width = pictureBox1.Size.Width;
   myImageFormat.Height = pictureBox1.Size.Height;
            
   // Create a MapOptions object.
   MapOptions myMapOptions = new MapOptions();
   myMapOptions.Zoom = 1;
   myMapOptions.Format = myImageFormat;
            
   // Create a MapView object, and center the map view around the LatLong that was passed in.
   ViewByHeightWidth myMapView = new  ViewByHeightWidth();
   myMapView.CenterPoint = myLLC;
   myMapView.Height = 300;
   myMapView.Width = 400;

   // Create and populate a Pushpin object for the map center.
   Pushpin myPushpin = new Pushpin();
   myPushpin.PinID = "pin1";
   myPushpin.Label = "center";
   myPushpin.IconName = "0";
   myPushpin.IconDataSource = "MapPoint.Icons";
   myPushpin.LatLong = myLLC;

   // Create the holder arrays for MapViews, Pushpins, and MapImages,
   // and store the corresponding objects within those arrays.
   ViewByHeightWidth[] myMapViews = new ViewByHeightWidth[1];
   Pushpin[] myPushpins = new Pushpin[1];
            
   MapSpecification mapSpec = new MapSpecification();
   myMapViews[0] = myMapView;
   myPushpins[0] = myPushpin;
   mapSpec.Views = myMapViews;
   mapSpec.Pushpins = myPushpins;
   mapSpec.Options = myMapOptions;
   mapSpec.DataSourceName = "MapPoint.NA";
            
   try
   {
    MapImage[] myMapImages = renderService.GetMap(mapSpec);
    pictureBox1.Image = new Bitmap(new System.IO.MemoryStream(myMapImages[0].MimeData.Bits));

                // If rendering was successful, return the map image.
    return myMapImages[0];
   }
   
   catch (System.Exception myException)
   {
    MessageBox.Show(myException.Message);
               
    // If rendering was not successful, return null.
    return null;
   }
  }
}
}

Attachment

ClickToCenterMap.rar (218.77 KB)

3-9-2008 12:48, Downloaded count: 29

TOP

Thread