ARTICLE

Using Bing Service to Display MAP in ASP.NET MVC

Posted by Krishna Garad Articles | ASP.NET MVC with C# February 01, 2012
In this article we will use the Bing Geocode service to find the current location and display it on the map.
Reader Level:
Download Files:
 

Introduction

In this article we will use the Bing Geocode service to find the current location and display it on the map. This article will demonstrate all the things required to display the Bing map on your view in ASP.Net MVC application. In our application we need to implement the location search service; for this kind of task we can implement the Bing Geocode service. So let's start step-by-step.

Step 1:

Before starting our work we need an API key, which you can create here. Just login with your Windows Live id and password and create your own API key.

Step 2:

After you have your API key, add the service references to the application to the given addresses and provide the namespace as given below.

  1. Geocode Service:

    NameSpace : GeocodeServices
    Address: http://dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc?wsdl

  2. Imagery Service:

    NameSpace: ImageryServices
    Address: http://dev.virtualearth.net/webservices/v1/imageryservice/imageryservice.svc?wsdl

Step 3:

After adding the service references, now import these namespaces to your controller like below.

using GeoCodeMVC.GeocodeService;
using GeoCodeMVC.ImageryService;

Step 4:

Next paste these methods into your controller, which will call the GeocodeService and ImageryService and return the address of the image to us and we will use this address and display the image on our view.

private GeocodeService.Location GeocodeAddress(string address)
        {
            GeocodeRequest geocodeRequest = new GeocodeRequest();
            // Set the credentials using a valid Bing Maps Key
            geocodeRequest.Credentials = new GeocodeService.Credentials();
            geocodeRequest.Credentials.ApplicationId = "YourAPIKEY";
            // Set the full address query
            geocodeRequest.Query = address;

            // Set the options to only return high confidence results
            ConfidenceFilter[] filters = new ConfidenceFilter[1];
            filters[0] = new ConfidenceFilter();
            filters[0].MinimumConfidence = GeocodeService.Confidence.High;
            GeocodeOptions geocodeOptions = new GeocodeOptions();
            geocodeOptions.Filters = filters;
            geocodeRequest.Options = geocodeOptions;
            // Make the geocode request
            GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest);

            if (geocodeResponse.Results.Length > 0)
                if (geocodeResponse.Results[0].Locations.Length > 0)
                    return geocodeResponse.Results[0].Locations[0];
            return null;
        }

        private string GetMapUri(double latitude, double longitude, int zoom, string mapStyle, int width, int height)
        {
            ImageryService.Pushpin[] pins = new ImageryService.Pushpin[1];
            ImageryService.Pushpin pushpin = new ImageryService.Pushpin();
            pushpin.Location = new ImageryService.Location();
            pushpin.Location.Latitude = latitude;
            pushpin.Location.Longitude = longitude;
            pushpin.IconStyle = "2";
            pins[0] = pushpin;
            MapUriRequest mapUriRequest = new MapUriRequest();
            // Set credentials using a valid Bing Maps Key
            mapUriRequest.Credentials = new ImageryService.Credentials();
            mapUriRequest.Credentials.ApplicationId = " YourAPIKEY ";

            // Set the location of the requested image
            mapUriRequest.Pushpins = pins;
            // Set the map style and zoom level
            MapUriOptions mapUriOptions = new MapUriOptions();
            //mapUriOptions.ZoomLevel = 17;
            switch (mapStyle.ToUpper())
            {
                case "HYBRID":
                    mapUriOptions.Style = ImageryService.MapStyle.AerialWithLabels;
                    break;
                case "ROAD":
                    mapUriOptions.Style = ImageryService.MapStyle.Road;
                    break;
                case "AERIAL":
                    mapUriOptions.Style = ImageryService.MapStyle.Aerial;
                    break;
                default:
                    mapUriOptions.Style = ImageryService.MapStyle.Road;
                    break;
            }

            mapUriOptions.ZoomLevel = 10;
            // Set the size of the requested image to match the size of the image control
            mapUriOptions.ImageSize = new ImageryService.SizeOfint();
            mapUriOptions.ImageSize.Height = height;
            mapUriOptions.ImageSize.Width = width;
            mapUriRequest.Options = mapUriOptions;

            ImageryServiceClient imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService");
            MapUriResponse mapUriResponse = imageryService.GetMapUri(mapUriRequest);

            return mapUriResponse.Uri;
        }
        private string MapAddress(string address, int zoom, string mapStyle, int width, int height)
        {
            GeocodeService.Location latlong = GeocodeAddress(address);
            double latitude = latlong.Latitude;
            double longitude = latlong.Longitude;          
            return GetMapUri(latitude, longitude, zoom, mapStyle, width, height);
        }

 Step 5:

In your Index action, call the MapAddress method by passing the address and other parameter where mapstyle you can pass as ROAD, AERIAL and HYBRID and receive the URL in a string or store it in ViewBag using this ViewBag we will show in our view.

public ActionResult Index()
        {
            ViewBag.MapUrl = MapAddress("Hyderabad,Andhra Pradesh,India", 17, "ROAD", 240, 320);
            return View();
        }

Step 6:

Now on your view, keep the image control of the HTML and pass the src as ViewBag variable like below.

<input type="image" src="@ViewBag.MapUrl" />

Step 7:

Now run the application and see the given address on Bing map.

Conclusion

In this way we can use the Bing Geocode and Imagery service to display a map on our ASP.Net MVC application. Next we will see how to generate routes and direction services of Bing.

Login to add your contents and source code to this article
post comment
     

Hi, Nice tutorial, however I have a problem.. When I added web references to project one reference missing - my app can't use GeocodeServiceClient. Have you tips for me?

Posted by Pawel Kulas Jan 04, 2013

Nice and clear writing, however, when I try this with my Application ID, I get System.ServiceModel.FaultException`1[[GeoCodeMVC.GeocodeService.ResponseSummary, GeoCodeMVC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]: Credentials are either invalid or unspecified.

Posted by John Marvin Apr 24, 2012

Hi You have written a very good and simple and to the point tutorial. Would it be possible for you to make sequels to this tutorial? Something like showing bing map that can be zoom in on, and which can be drag, basically just more interactive bing map.

Posted by miram miram Mar 22, 2012

thanks DL demo code is available just check it once on the top

Posted by Krishna Garad Feb 02, 2012

Can u upload u r Demo code if possible that is better for all of us.

Posted by Dinkar Chavhan Feb 02, 2012
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.