Back to search

Build a realtime map using ASP.NET

  • Neo Ighodaro
February 2nd, 2018
A basic understanding of ASP.NET and jQuery is needed to follow this tutorial.

Realtime maps are a popular feature in most modern applications. They are used in apps like Uber or Lyft, and in courier and delivery services to track the location of parcels or cabs and to monitor their progress and movement as they make their way to the customer.

In this article, we will look at how to build a realtime map using .NET and Pusher. Our resulting application will look like this:

realtime-map-aspnet-demo

Prerequisites

To follow along with this article, you’ll need:

  • Visual Studio IDE, find installation instructions here.
  • Basic knowledge of C#.
  • Basic knowledge of JavaScript (ES6 syntax) and jQuery.

Setting up Pusher and Google Maps

To achieve our realtime map, we’ll be making use of two services: Pusher and Google Maps. Pusher is a service that offers simple implementation of realtime functionality in web and mobile applications. We will use it primarily to transmit the realtime updates on our map.

Create a Pusher account, if you have not already, and then set up your application as seen in the screenshot below.

realtime-map-aspnet-create-app

When you have completed the set up, take note of your Pusher application keys as we will need them later on.

Next, we will set up a Google Maps API project. The Google Maps API provides a service for embedding maps in our applications and provides access to location information of businesses, cities and much more for numerous countries all over the world. We will use this service to generate a map and mark the realtime locations on the map.

Using the Google Maps API guide, create a project and copy out the API key.

Building the backend

In this article, using C#, we will build a small application that renders a map, on which the location will be displayed and marked in realtime.

Creating our project

Using the Visual Studio IDE, follow the New Project Wizard. We will need to:

  • Create our map project.
  • Set C# as our language to use.
  • Select .NET MVC Project as the template.
  • Fill in the Project name e.g. Gaia.
  • Fill in the Solution name i.e. application name.

Setting up our routes and controllers

For the purpose of this application, we will define two routes: the route to render the map and the route to send new locations to our map. Create a RouteConfig.cs file, and paste the following code:

    // RouteConfig.cs
    routes.MapRoute(
        name: "Home",
        url: "",
        defaults: new { controller = "Home", action = "Index" }
    );

    routes.MapRoute(
        name: "Map",
        url:  "map",
        defaults: new { controller = "Map", action = "Index" }
    );

These route definitions specify the route pattern and the Controller and Action to handle it. Based on this, we need to create two controller files in the Controllers directory, HomeController.cs and MapController.cs.

💡 Creating our project with Visual Studio automatically creates the HomeContoller.cs file with an Index action. We will use this for our home route.

In the HomeController.cs file, we add:

    // HomeController.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;

    namespace Gaia.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
        }
    }

The above snippet renders our home view using the View function.

💡 The View function creates a view response which we return. When it is invoked, C# looks for the default view of the calling controller class. This default view is the index.cshtml file found in the Views directory, in a directory with the same name as the Controller. i.e. The default view of the HomeController class will be the Views/Home/index.cshtml file.

In the MapController.cs file, we will receive a location’s longitude and latitude via a POST request and transmit this location data to our map via the Pusher service. Add the following code:

    // MapController.cs

    ...

    public class MapController : Controller
    {
        private Pusher pusher;

        public MapController() 
        {
            var options = new PusherOptions();
            options.Cluster = "app_cluster";

            pusher = new Pusher(
                "app_id",
                "app_key",
                "app_secret", 
                options
            );   
        }

        [HttpPost]
        public JsonResult Index()
        {
            var latitude    = Request.Form["lat"];
            var longitude = Request.Form["lng"];

            var location = new
            {
                latitude = latitude,
                longitude = longitude
            };

            pusher.TriggerAsync("location_channel", "new_location", location);

            return Json( new { status = "success", data = location } );
        }
    }

In the code block above, we create a class variable private Pusher pusher. Then, we instantiate it to a Pusher client in the class constructor using the app credentials copied earlier from the Pusher dashboard.

We use the Pusher instance to transmit the location data on the location_channel channel, in the new_location event. Remember to replace app_id and the other values with your Pusher app credentials.

⚠️ To use the Pusher client in our controller, you must install the PusherServer library via NuGet, and add using PusherServer to the top import statements of your MapController class.

Creating our map view

Since our map will be rendered on our home route, we will use the Views/Home/index.cshtml file (which is the default view of the HomeController class).

💡 Our Views/Home/index.cshtml file extends the Shared/_Layout.cshtml file. We have added the title tag and stylesheet imports to Shared/_Layout.cshtml for this reason.

In the Shared/_Layout.cshtml file, we add:

    <!-- Shared/_Layout.cshtml -->
    <!DOCTYPE html>
    <html>
    <head>
        <title>Gaia</title>
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.3/css/bootstrap.min.css" />
        <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/custom.css")"/>
    </head>
    <body>
        @RenderBody()
    </body>
    </html>

In the Views/Home/index.cshtml file, add the following:

    <!-- Views/Home/index.cshtml -->
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-xs-12 col-lg-6">
                <h3>A realtime Map</h3>
                <div id="map">

                </div>
            </div>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.3/js/bootstrap.min.js"></script>

The block above defines the basic markup of our view. It consists mainly of the div for holding our map. We have also imported the Bootstrap CSS framework and its jQuery library dependency, to take advantage of some pre-made styles.

Next we will import the Google Maps API JavaScript library and initialize our map in Views/Home/index.cshtml:

    <!-- Views/Home/index.cshtml -->
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAniUCyk0Gfp_UT1qNTHg2AF4I4ZmQ6EGo&callback=initMap"></script>
    <script>
        let lineCoordinates = []

        let latitude = 6.4541;
        let longitude = 3.3947;

        let map = false;
        let marker = false;

        function initMap() {
            let lagos = {lat: latitude, lng: longitude};

            map = new google.maps.Map(document.getElementById('map'), {
              zoom: 10,
              center: lagos
            });

            marker = new google.maps.Marker({
              position: lagos,
              map: map
            });

            lineCoordinates.push(marker.getPosition())
        }
    </script>

In the snippet above, we have initialized our map by passing the coordinates of Lagos, Nigeria to the Google Maps library.

Next, we will listen for changes in location (via our Pusher event) and implement the updates to our map. For this we’ll define our map update function. Copy the following code:

    <!-- Views/Home/index.cshtml -->

    [...]

    const updateMap = function(data) {
        latitude = (data.latitude * 1);
        longitude = (data.longitude * 1);

        map.setCenter({
            lat: latitude,
            lng: longitude,
            alt: 0
        });

        marker.setPosition({
            lat: latitude,
            lng: longitude,
            alt: 0
        });

        lineCoordinates.push(marker.getPosition())

        let lineCoordinatesPath = new google.maps.Polyline({
          path: lineCoordinates,
          geodesic: true,
          map: map,
          strokeColor: '#FF0000',
          strokeOpacity: 1.0,
          strokeWeight: 2
        });
    }
    </script>

Finally, we’ll listen for our Pusher events and trigger the updateMap function in our view:

    <!-- Views/Home/index.cshtml

    [...]

    <script src="https://js.pusher.com/4.1/pusher.min.js"></script>
    <script>
      const pusher = new Pusher('app_key', {
        cluster: 'app_cluster'
      });

      const channel = pusher.subscribe('location_channel');

      channel.bind('new_location', function(data) {
          updateMap(data);
      });
    </script>

In the snippet above, we import and initialize the Pusher JavaScript client. Then we subscribe to the location_channel and listen to the new_location event, passing the new location data received to our updateMap function for realtime updates.

Here is the application when we run it again:

realtime-map-aspnet-demo

Conclusion

In a few simple steps, we have built a realtime map that updates and marks its current position based on data it receives. This application can be used to get GPS coordinates from a requested cab, or a tracked parcel to view its location and travel path on a map.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 28 Scrutton Street, London EC2A 4RP.