Hospital Locator using Bing Maps

Hi Guys,

This time I had a requirement to find the closest hospital from a given location. And map the route to get to that hospital. So I made a small application for that. Hope you like it.



















1) ILocationService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ILocationService" in both code and config file together.
[ServiceContract]
public interface ILocationService
{
    [OperationContract]
    [WebGet(UriTemplate = "/GetAllLocations",
    ResponseFormat = WebMessageFormat.Json)]
    List<Location> GetAllLocations();

    [OperationContract]
    [WebGet(UriTemplate = "/GetClosestLocation?latitude={latitude}&longtitude={longtitude}",
    ResponseFormat = WebMessageFormat.Json)]
    Location GetClosestLocation(string latitude,string longtitude);

}

2) LocationService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "LocationService" in code, svc and config file together.
public class LocationService : ILocationService
{
    [OperationBehavior]
    public List<Location> GetAllLocations()
{
        using (LocationDataDataContext context = new LocationDataDataContext())
        {
            var temp = (from r in context.Locations
                        where r.IsActive == true
                        select r);
            return temp.ToList();

        }
}

    [OperationBehavior]
    public Location GetClosestLocation(string latitude, string longtitude)
    {
        using (LocationDataDataContext context = new LocationDataDataContext())
        {
            Dictionary<int, double> distances = new Dictionary<int, double>();
            var temp = (from r in context.Locations
                        where r.IsActive == true
                        select r);
            foreach (var item in temp)
            {
              distances.Add(item.ID,GetDistanceBetweenPoints(double.Parse(latitude), double.Parse(longtitude),
                    double.Parse(item.Latitude), double.Parse(item.Longtitude)));
            }

            var min = distances.OrderBy(kvp => kvp.Value).First();
            return (from t in temp
                   where t.ID == min.Key
                   select t).FirstOrDefault();

        }
    }

    private double GetDistanceBetweenPoints(double lat1, double long1, double lat2, double long2)
    {
        double distance = 0;

        double dLat = (lat2 - lat1) / 180 * Math.PI;
        double dLong = (long2 - long1) / 180 * Math.PI;

        double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2)
                    + Math.Cos(lat1 / 180 * Math.PI) * Math.Cos(lat2 / 180 * Math.PI)
                    * Math.Sin(dLong / 2) * Math.Sin(dLong / 2);
        double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

        //Calculate radius of earth
        // For this you can assume any of the two points.
        double radiusE = 6378135; // Equatorial radius, in metres
        double radiusP = 6356750; // Polar Radius

        //Numerator part of function
        double nr = Math.Pow(radiusE * radiusP * Math.Cos(lat1 / 180 * Math.PI), 2);
        //Denominator part of the function
        double dr = Math.Pow(radiusE * Math.Cos(lat1 / 180 * Math.PI), 2)
                        + Math.Pow(radiusP * Math.Sin(lat1 / 180 * Math.PI), 2);
        double radius = Math.Sqrt(nr / dr);

        //Calculate distance in meters.
        distance = radius * c;
        return distance; // distance in meters
    }

}

3) Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

    <script type="text/javascript">
        var map;
        //var lat, lng;
        var lat = 24.704179, lng = 46.721524;
        var directionsManager;
        var directionsErrorEventObj;
        var directionsUpdatedEventObj;
        $(document).ready(function () {
            Microsoft.Maps.loadModule('Microsoft.Maps.Themes.BingTheme', {
                callback: function () {
                    
                    if (navigator.geolocation) {
                        alert(navigator.geolocation);
                        navigator.geolocation.getCurrentPosition(function (position) {
                            alert(position.coords );
                            lat = position.coords.latitude; lng = position.coords.longitude;
                        }, errorHandler);

                    }

                    

                    map = new Microsoft.Maps.Map(document.getElementById('SDKmap'), {
                        credentials: 'Your Key Here',
                        theme: new Microsoft.Maps.Themes.BingTheme(),
                        width: screen.width / 1.2, height: screen.height / 1.1
                    });
                    var infoboxOptions = { icon: '/Images/Current.png', width: 32, height: 32 };
                    var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(), infoboxOptions);
                    map.entities.push(pushpin);
                  
                    pushpin.setLocation(new Microsoft.Maps.Location(lat, lng));
                    
                }
            });

            $.get("/Services/LocationService.svc/GetAllLocations", function (data, status) {
                if (map) {
                    if (map.entities)
                        map.entities.clear();
                    var pushpinOptions;
                    var pushpin;
                    var infoboxOptions;
                    for (var i = 0; i < data.length; i++) {
                       

                        infoboxOptions = { icon: '/Images/Hospital.png', width: 32, height: 32 };

                        pushpin = new Microsoft.Maps.Pushpin(map.getCenter(), infoboxOptions);
                        map.entities.push(pushpin);
                        pushpin.setLocation(new Microsoft.Maps.Location(
                        data[i].Latitude,
                        data[i].Longtitude));

                    }
                    createDirections();
                }
                
            });


        });

       
        function errorHandler(err) {
            console.warn('ERROR(' + err.code + '): ' + err.message);
        };

        function handlerEvent() {
            alert('Handler clicked');
        }

        function createDirectionsManager() {
            var displayMessage;
            if (!directionsManager) {
                directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
                displayMessage = 'Directions Module loaded\n';
                displayMessage += 'Directions Manager loaded';
            }
            console.log(displayMessage);
            directionsManager.resetDirections();
            directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', function (arg) { console.log(arg.message) });
            directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function () { console.log('Directions updated') });
        }

        function createDrivingRoute() {
            if (!directionsManager) { createDirectionsManager(); }

            $.get("/Services/LocationService.svc/GetClosestLocation?latitude="+lat+"&longtitude="+lng, function (data, status) {
                
                directionsManager.resetDirections();
                // Set Route Mode to driving 
                directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
                var pointA = new Microsoft.Maps.Directions.Waypoint({

                    location: new Microsoft.Maps.Location(lat, lng)
                });
                directionsManager.addWaypoint(pointA);
                var pointB = new Microsoft.Maps.Directions.Waypoint({

                    location: new Microsoft.Maps.Location(data.Latitude, data.Longtitude)
                });
                directionsManager.addWaypoint(pointB);
                // Set the element in which the itinerary will be rendered
                directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });

                directionsManager.calculateDirections();

                
            });



            
        }

        function createDirections() {
            if (!directionsManager) {
                Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute });
            }
            else {
                createDrivingRoute();
            }
        }

        

    </script>
  

    <div id="SDKmap" style="width:500px;height:500px"></div>

   

</asp:Content>


5) Solution and Data




Comments

Popular posts from this blog

Secure .NET Core Api Server and Client

Security tips for hosting .NET Web Application on IIS

Simple API using Python, Flask and pyodbc