Use AJAX to Implement Mapping Scenarios
by Microsoft
This is step 11 of a free “NerdDinner” application tutorial that walks-through how to build a small, but complete, web application using ASP.NET MVC 1.
Step 11 shows how to integrate AJAX mapping support into our NerdDinner application, enabling users who are creating, editing or viewing dinners to see the location of the dinner graphically.
If you are using ASP.NET MVC 3, we recommend you follow the Getting Started With MVC 3 or MVC Music Store tutorials.
NerdDinner Step 11: Integrating an AJAX Map
We’ll now make our application a little more visually exciting by integrating AJAX mapping support. This will enable users who are creating, editing or viewing dinners to see the location of the dinner graphically.
Creating a Map Partial View
We are going to use mapping functionality in several places within our application. To keep our code DRY we’ll encapsulate the common map functionality within a single partial template that we can re-use across multiple controller actions and views. We’ll name this partial view “map.ascx” and create it within the directory.
We can create the map.ascx partial by right-clicking on the directory and choosing the Add->View menu command. We’ll name the view “Map.ascx”, check it as a partial view, and indicate that we are going to pass it a strongly-typed “Dinner” model class:
When we click the “Add” button our partial template will be created. We’ll then update the Map.ascx file to have the following content:
[!code-aspxMain]
1: <script src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2" type="text/javascript"></script>
2: <script src="/Scripts/Map.js" type="text/javascript"></script>
3:
4: <div id="theMap">
5: </div>
6:
7: <script type="text/javascript">
8:
9: $(document).ready(function() {
10: var latitude = <%=Model.Latitude%>;
11: var longitude = <%=Model.Longitude%>;
12:
13: if ((latitude == 0) || (longitude == 0))
14: LoadMap();
15: else
16: LoadMap(latitude, longitude, mapLoaded);
17: });
18:
19: function mapLoaded() {
20: var title = "<%=Html.Encode(Model.Title) %>";
21: var address = "<%=Html.Encode(Model.Address) %>";
22:
23: LoadPin(center, title, address);
24: map.SetZoomLevel(14);
25: }
26:
27: </script>
The first <script> reference points to the Microsoft Virtual Earth 6.2 mapping library. The second <script> reference points to a map.js file that we will shortly create which will encapsulate our common Javascript mapping logic. The <div id=“theMap”> element is the HTML container that Virtual Earth will use to host the map.
We then have an embedded <script> block that contains two JavaScript functions specific to this view. The first function uses jQuery to wire-up a function that executes when the page is ready to run client-side script. It calls a LoadMap() helper function that we’ll define within our Map.js script file to load the virtual earth map control. The second function is a callback event handler that adds a pin to the map that identifies a location.
Notice how we are using a server-side <%= %> block within the client-side script block to embed the latitude and longitude of the Dinner we want to map into the JavaScript. This is a useful technique to output dynamic values that can be used by client-side script (without requiring a separate AJAX call back to the server to retrieve the values – which makes it faster). The <%= %> blocks will execute when the view is rendering on the server – and so the output of the HTML will just end up with embedded JavaScript values (for example: var latitude = 47.64312;).
Creating a Map.js utility library
Let’s now create the Map.js file that we can use to encapsulate the JavaScript functionality for our map (and implement the LoadMap and LoadPin methods above). We can do this by right-clicking on the directory within our project, and then choose the “Add->New Item” menu command, select the JScript item, and name it “Map.js”.
Below is the JavaScript code we’ll add to the Map.js file that will interact with Virtual Earth to display our map and add locations pins to it for our dinners:
[!code-javascriptMain]
1: var map = null;
2: var points = [];
3: var shapes = [];
4: var center = null;
5:
6: function LoadMap(latitude, longitude, onMapLoaded) {
7: map = new VEMap('theMap');
8: options = new VEMapOptions();
9: options.EnableBirdseye = false;
10:
11: // Makes the control bar less obtrusize.
12: map.SetDashboardSize(VEDashboardSize.Small);
13:
14: if (onMapLoaded != null)
15: map.onLoadMap = onMapLoaded;
16:
17: if (latitude != null && longitude != null) {
18: center = new VELatLong(latitude, longitude);
19: }
20:
21: map.LoadMap(center, null, null, null, null, null, null, options);
22: }
23:
24: function LoadPin(LL, name, description) {
25: var shape = new VEShape(VEShapeType.Pushpin, LL);
26:
27: //Make a nice Pushpin shape with a title and description
28: shape.SetTitle("<span class=\"pinTitle\"> " + escape(name) + "</span>");
29: if (description !== undefined) {
30: shape.SetDescription("<p class=\"pinDetails\">" +
31: escape(description) + "</p>");
32: }
33: map.AddShape(shape);
34: points.push(LL);
35: shapes.push(shape);
36: }
37:
38: function FindAddressOnMap(where) {
39: var numberOfResults = 20;
40: var setBestMapView = true;
41: var showResults = true;
42:
43: map.Find("", where, null, null, null,
44: numberOfResults, showResults, true, true,
45: setBestMapView, callbackForLocation);
46: }
47:
48: function callbackForLocation(layer, resultsArray, places,
49: hasMore, VEErrorMessage) {
50:
51: clearMap();
52:
53: if (places == null)
54: return;
55:
56: //Make a pushpin for each place we find
57: $.each(places, function(i, item) {
58: description = "";
59: if (item.Description !== undefined) {
60: description = item.Description;
61: }
62: var LL = new VELatLong(item.LatLong.Latitude,
63: item.LatLong.Longitude);
64:
65: LoadPin(LL, item.Name, description);
66: });
67:
68: //Make sure all pushpins are visible
69: if (points.length > 1) {
70: map.SetMapView(points);
71: }
72:
73: //If we've found exactly one place, that's our address.
74: if (points.length === 1) {
75: $("#Latitude").val(points[0].Latitude);
76: $("#Longitude").val(points[0].Longitude);
77: }
78: }
79:
80: function clearMap() {
81: map.Clear();
82: points = [];
83: shapes = [];
84: }
Integrating the Map with Create and Edit Forms
We’ll now integrate the Map support with our existing Create and Edit scenarios. The good news is that this is pretty easy to-do, and doesn’t require us to change any of our Controller code. Because our Create and Edit views share a common “DinnerForm” partial view to implement the dinner form UI, we can add the map in one place and have both our Create and Edit scenarios use it.
All we need to-do is to open the .ascx partial view and update it to include our new map partial. Below is what the updated DinnerForm will look like once the map is added (note: the HTML form elements are omitted from the code snippet below for brevity):
[!code-aspxMain]
1: <%= Html.ValidationSummary() %>
2:
3: <% using (Html.BeginForm()) { %>
4:
5: <fieldset>
6:
7: <div id="dinnerDiv">
8: <p>
9: [HTML Form Elements Removed for Brevity]
10: </p>
11: <p>
12: <input type="submit" value="Save"/>
13: </p>
14: </div>
15:
16: <div id="mapDiv">
17: <%Html.RenderPartial("Map", Model.Dinner); %>
18: </div>
19:
20: </fieldset>
21:
22: <script type="text/javascript">
23:
24: $(document).ready(function() {
25: $("#Address").blur(function(evt) {
26: $("#Latitude").val("");
27: $("#Longitude").val("");
28:
29: var address = jQuery.trim($("#Address").val());
30: if (address.length < 1)
31: return;
32:
33: FindAddressOnMap(address);
34: });
35: });
36:
37: </script>
38:
39: <% } %>
The DinnerForm partial above takes an object of type “DinnerFormViewModel” as its model type (because it needs both a Dinner object, as well as a SelectList to populate the dropdownlist of countries). Our Map partial just needs an object of type “Dinner” as its model type, and so when we render the map partial we are passing just the Dinner sub-property of DinnerFormViewModel to it:
[!code-aspxMain]
1: <% Html.RenderPartial("Map", Model.Dinner); %>
The JavaScript function we’ve added to the partial uses jQuery to attach a “blur” event to the “Address” HTML textbox. You’ve probably heard of “focus” events that fire when a user clicks or tabs into a textbox. The opposite is a “blur” event that fires when a user exits a textbox. The above event handler clears the latitude and longitude textbox values when this happens, and then plots the new address location on our map. A callback event handler that we defined within the map.js file will then update the longitude and latitude textboxes on our form using values returned by virtual earth based on the address we gave it.
And now when we run our application again and click the “Host Dinner” tab we’ll see a default map displayed along with our standard Dinner form elements:
When we type in an address, and then tab away, the map will dynamically update to display the location, and our event handler will populate the latitude/longitude textboxes with the location values:
If we save the new dinner and then open it again for editing, we’ll find that the map location is displayed when the page loads:
Every time the address field is changed, the map and the latitude/longitude coordinates will update.
Now that the map displays the Dinner location, we can also change the Latitude and Longitude form fields from being visible textboxes to instead be hidden elements (since the map is automatically updating them each time an address is entered). To-do this we’ll switch from using the Html.TextBox() HTML helper to using the Html.Hidden() helper method:
[!code-aspxMain]
1: <p>
2: <%= Html.Hidden("Latitude", Model.Dinner.Latitude)%>
3: <%= Html.Hidden("Longitude", Model.Dinner.Longitude)%>
4: </p>
And now our forms are a little more user-friendly and avoid displaying the raw latitude/longitude (while still storing them with each Dinner in the database):
Integrating the Map with the Details View
Now that we have the map integrated with our Create and Edit scenarios, let’s also integrate it with our Details scenario. All we need to-do is to call <% Html.RenderPartial(“map”); %> within the Details view.
Below is what the source code to the complete Details view (with map integration) looks like:
[!code-aspxMain]
1: <asp:Content ID="Title" ContentPlaceHolderID="TitleContent"runat="server">
2: <%= Html.Encode(Model.Title) %>
3: </asp:Content>
4:
5: <asp:Content ID="details" ContentPlaceHolderID="MainContent" runat="server">
6:
7: <div id="dinnerDiv">
8:
9: <h2><%=Html.Encode(Model.Title) %></h2>
10: <p>
11: <strong>When:</strong>
12: <%=Model.EventDate.ToShortDateString() %>
13:
14: <strong>@</strong>
15: <%=Model.EventDate.ToShortTimeString() %>
16: </p>
17: <p>
18: <strong>Where:</strong>
19: <%=Html.Encode(Model.Address) %>,
20: <%=Html.Encode(Model.Country) %>
21: </p>
22: <p>
23: <strong>Description:</strong>
24: <%=Html.Encode(Model.Description) %>
25: </p>
26: <p>
27: <strong>Organizer:</strong>
28: <%=Html.Encode(Model.HostedBy) %>
29: (<%=Html.Encode(Model.ContactPhone) %>)
30: </p>
31:
32: <%Html.RenderPartial("RSVPStatus"); %>
33: <%Html.RenderPartial("EditAndDeleteLinks"); %>
34:
35: </div>
36:
37: <div id="mapDiv">
38: <%Html.RenderPartial("map"); %>
39: </div>
40:
41: </asp:Content>
And now when a user navigates to a /Dinners/Details/[id] URL they’ll see details about the dinner, the location of the dinner on the map (complete with a push-pin that when hovered over displays the title of the dinner and the address of it), and have an AJAX link to RSVP for it:
Implementing Location Search in our Database and Repository
To finish off our AJAX implementation, let’s add a Map to the home page of the application that allows users to graphically search for dinners near them.
We’ll begin by implementing support within our database and data repository layer to efficiently perform a location-based radius search for Dinners. We could use the new geospatial features of SQL 2008 to implement this, or alternatively we can use a SQL function approach that Gary Dryden discussed in article here: http://www.codeproject.com/KB/cs/distancebetweenlocations.aspx and Rob Conery blogged about using with LINQ to SQL here: http://blog.wekeroad.com/2007/08/30/linq-and-geocoding/
To implement this technique, we will open the “Server Explorer” within Visual Studio, select the NerdDinner database, and then right-click on the “functions” sub-node under it and choose to create a new “Scalar-valued function”:
We’ll then paste in the following DistanceBetween function:
[!code-sqlMain]
1: CREATE FUNCTION [dbo].[DistanceBetween](@Lat1 as real,
2: @Long1 as real, @Lat2 as real, @Long2 as real)
3: RETURNS real
4: AS
5: BEGIN
6:
7: DECLARE @dLat1InRad as float(53);
8: SET @dLat1InRad = @Lat1 * (PI()/180.0);
9: DECLARE @dLong1InRad as float(53);
10: SET @dLong1InRad = @Long1 * (PI()/180.0);
11: DECLARE @dLat2InRad as float(53);
12: SET @dLat2InRad = @Lat2 * (PI()/180.0);
13: DECLARE @dLong2InRad as float(53);
14: SET @dLong2InRad = @Long2 * (PI()/180.0);
15:
16: DECLARE @dLongitude as float(53);
17: SET @dLongitude = @dLong2InRad - @dLong1InRad;
18: DECLARE @dLatitude as float(53);
19: SET @dLatitude = @dLat2InRad - @dLat1InRad;
20: /* Intermediate result a. */
21: DECLARE @a as float(53);
22: SET @a = SQUARE (SIN (@dLatitude / 2.0)) + COS (@dLat1InRad)
23: * COS (@dLat2InRad)
24: * SQUARE(SIN (@dLongitude / 2.0));
25: /* Intermediate result c (great circle distance in Radians). */
26: DECLARE @c as real;
27: SET @c = 2.0 * ATN2 (SQRT (@a), SQRT (1.0 - @a));
28: DECLARE @kEarthRadius as real;
29: /* SET kEarthRadius = 3956.0 miles */
30: SET @kEarthRadius = 6376.5; /* kms */
31:
32: DECLARE @dDistance as real;
33: SET @dDistance = @kEarthRadius * @c;
34: return (@dDistance);
35: END
We’ll then create a new table-valued function in SQL Server that we’ll call “NearestDinners”:
This “NearestDinners” table function uses the DistanceBetween helper function to return all Dinners within 100 miles of the latitude and longitude we supply it:
[!code-sqlMain]
1: CREATE FUNCTION [dbo].[NearestDinners]
2: (
3: @lat real,
4: @long real
5: )
6: RETURNS TABLE
7: AS
8: RETURN
9: SELECT Dinners.DinnerID
10: FROM Dinners
11: WHERE dbo.DistanceBetween(@lat, @long, Latitude, Longitude) <100
To call this function, we’ll first open up the LINQ to SQL designer by double-clicking on the NerdDinner.dbml file within our directory:
We’ll then drag the NearestDinners and DistanceBetween functions onto the LINQ to SQL designer, which will cause them to be added as methods on our LINQ to SQL NerdDinnerDataContext class:
We can then expose a “FindByLocation” query method on our DinnerRepository class that uses the NearestDinner function to return upcoming Dinners that are within 100 miles of the specified location:
[!code-csharpMain]
1: public IQueryable<Dinner> FindByLocation(float latitude, float longitude) {
2:
3: var dinners = from dinner in FindUpcomingDinners()
4: join i in db.NearestDinners(latitude, longitude)
5: on dinner.DinnerID equals i.DinnerID
6: select dinner;
7:
8: return dinners;
9: }
Implementing a JSON-based AJAX Search Action Method
We’ll now implement a controller action method that takes advantage of the new FindByLocation() repository method to return back a list of Dinner data that can be used to populate a map. We’ll have this action method return back the Dinner data in a JSON (JavaScript Object Notation) format so that it can be easily manipulated using JavaScript on the client.
To implement this, we’ll create a new “SearchController” class by right-clicking on the directory and choosing the Add->Controller menu command. We’ll then implement a “SearchByLocation” action method within the new SearchController class like below:
[!code-csharpMain]
1: public class JsonDinner {
2: public int DinnerID { get; set; }
3: public string Title { get; set; }
4: public double Latitude { get; set; }
5: public double Longitude { get; set; }
6: public string Description { get; set; }
7: public int RSVPCount { get; set; }
8: }
9:
10: public class SearchController : Controller {
11:
12: DinnerRepository dinnerRepository = new DinnerRepository();
13:
14: //
15: // AJAX: /Search/SearchByLocation
16:
17: [AcceptVerbs(HttpVerbs.Post)]
18: public ActionResult SearchByLocation(float longitude, float latitude) {
19:
20: var dinners = dinnerRepository.FindByLocation(latitude,longitude);
21:
22: var jsonDinners = from dinner in dinners
23: select new JsonDinner {
24: DinnerID = dinner.DinnerID,
25: Latitude = dinner.Latitude,
26: Longitude = dinner.Longitude,
27: Title = dinner.Title,
28: Description = dinner.Description,
29: RSVPCount = dinner.RSVPs.Count
30: };
31:
32: return Json(jsonDinners.ToList());
33: }
34: }
The SearchController’s SearchByLocation action method internally calls the FindByLocation method on DinnerRespository to get a list of nearby dinners. Rather than return the Dinner objects directly to the client, though, it instead returns JsonDinner objects. The JsonDinner class exposes a subset of Dinner properties (for example: for security reasons it doesn’t disclose the names of the people who have RSVP’d for a dinner). It also includes an RSVPCount property that doesn’t exist on Dinner– and which is dynamically calculated by counting the number of RSVP objects associated with a particular dinner.
We are then using the Json() helper method on the Controller base class to return the sequence of dinners using a JSON-based wire format. JSON is a standard text format for representing simple data-structures. Below is an example of what a JSON-formatted list of two JsonDinner objects looks like when returned from our action method:
[!code-jsonMain]
1: [{"DinnerID":53,"Title":"Dinner with the Family","Latitude":47.64312,"Longitude":-122.130609,"Description":"Fun dinner","RSVPCount":2},
2: {"DinnerID":54,"Title":"Another Dinner","Latitude":47.632546,"Longitude":-122.21201,"Description":"Dinner with Friends","RSVPCount":3}]
Calling the JSON-based AJAX method using jQuery
We are now ready to update the home page of the NerdDinner application to use the SearchController’s SearchByLocation action method. To-do this, we’ll open the /Views/Home/Index.aspx view template and update it to have a textbox, search button, our map, and a <div> element named dinnerList:
[!code-aspxMain]
1: <h2>Find a Dinner</h2>
2:
3: <div id="mapDivLeft">
4:
5: <div id="searchBox">
6: Enter your location: <%=Html.TextBox("Location") %>
7: <input id="search" type="submit" value="Search"/>
8: </div>
9:
10: <div id="theMap">
11: </div>
12:
13: </div>
14:
15: <div id="mapDivRight">
16: <div id="dinnerList"></div>
17: </div>
We can then add two JavaScript functions to the page:
[!code-htmlMain]
1: <script type="text/javascript">
2:
3: $(document).ready(function() {
4: LoadMap();
5: });
6:
7: $("#search").click(function(evt) {
8: var where = jQuery.trim($("#Location").val());
9: if (where.length < 1)
10: return;
11:
12: FindDinnersGivenLocation(where);
13: });
14:
15: </script>
The first JavaScript function loads the map when the page first loads. The second JavaScript function wires up a JavaScript click event handler on the search button. When the button is pressed it calls the FindDinnersGivenLocation() JavaScript function which we’ll add to our Map.js file:
[!code-javascriptMain]
1: function FindDinnersGivenLocation(where) {
2: map.Find("", where, null, null, null, null, null, false,
3: null, null, callbackUpdateMapDinners);
4: }
This FindDinnersGivenLocation() function calls map.Find() on the Virtual Earth Control to center it on the entered location. When the virtual earth map service returns, the map.Find() method invokes the callbackUpdateMapDinners callback method we passed it as the final argument.
The callbackUpdateMapDinners() method is where the real work is done. It uses jQuery’s $.post() helper method to perform an AJAX call to our SearchController’s SearchByLocation() action method – passing it the latitude and longitude of the newly centered map. It defines an inline function that will be called when the $.post() helper method completes, and the JSON-formatted dinner results returned from the SearchByLocation() action method will be passed it using a variable called “dinners”. It then does a foreach over each returned dinner, and uses the dinner’s latitude and longitude and other properties to add a new pin on the map. It also adds a dinner entry to the HTML list of dinners to the right of the map. It then wires-up a hover event for both the pushpins and the HTML list so that details about the dinner are displayed when a user hovers over them:
[!code-htmlMain]
1: function callbackUpdateMapDinners(layer, resultsArray, places, hasMore, VEErrorMessage) {
2:
3: $("#dinnerList").empty();
4: clearMap();
5: var center = map.GetCenter();
6:
7: $.post("/Search/SearchByLocation", { latitude: center.Latitude,
8: longitude: center.Longitude },
9: function(dinners) {
10: $.each(dinners, function(i, dinner) {
11:
12: var LL = new VELatLong(dinner.Latitude,
13: dinner.Longitude, 0, null);
14:
15: var RsvpMessage = "";
16:
17: if (dinner.RSVPCount == 1)
18: RsvpMessage = "" + dinner.RSVPCount + "RSVP";
19: else
20: RsvpMessage = "" + dinner.RSVPCount + "RSVPs";
21:
22: // Add Pin to Map
23: LoadPin(LL, '<a href="/Dinners/Details/' + dinner.DinnerID + '">'
24: + dinner.Title + '</a>',
25: "<p>" + dinner.Description + "</p>" + RsvpMessage);
26:
27: //Add a dinner to the <ul> dinnerList on the right
28: $('#dinnerList').append($('<li/>')
29: .attr("class", "dinnerItem")
30: .append($('<a/>').attr("href",
31: "/Dinners/Details/" + dinner.DinnerID)
32: .html(dinner.Title))
33: .append(" ("+RsvpMessage+")"));
34: });
35:
36: // Adjust zoom to display all the pins we just added.
37: map.SetMapView(points);
38:
39: // Display the event's pin-bubble on hover.
40: $(".dinnerItem").each(function(i, dinner) {
41: $(dinner).hover(
42: function() { map.ShowInfoBox(shapes[i]); },
43: function() { map.HideInfoBox(shapes[i]); }
44: );
45: });
46: }, "json");
And now when we run the application and visit the home-page we’ll be presented with a map. When we enter the name of a city the map will display the upcoming dinners near it:
Hovering over a dinner will display details about it.
Clicking the Dinner title either in the bubble or on the right-hand side in the HTML list will navigate us to the dinner – which we can then optionally RSVP for:
Next Step
We’ve now implemented all the application functionality of our NerdDinner application. Let’s now look at how we can enable automated unit testing of it.
|