Get User Location Using Latitude And Longitude With OpenStreetMap In ASP.NET MVC

Introduction

Clicking marker of user location displays the user details. This request is based on Ajax method and JsonResult. OpenStreetMap is open data and you are free to use it for any purpose. 

Pre Requisite

  • Windows 7 or above
  • SQL Server 2012 or above
  • ASP.NET MVC 5 above framework
Steps
  1. Create a table as in the following:

    Create a table

  2. Create a new MVC project and name it WebApplication.

  3. Right click model folder and create a new item ADO.NET Entity Data model. Give it a name and then click EF Designer From Data.

    Here's the screenshot:

    ADO.NET Entity Data model

    Connection

    Select given table and click finish and edmx gets created.

    table

    Generated connection automatically creates edmx from database

    model

  4. Write then following code into controller.
    1. using System;    
    2. using System.Collections.Generic;    
    3. using System.Data;    
    4. using System.Data.Entity;    
    5. using System.Linq;    
    6. using System.Net;    
    7. using System.Web;    
    8. using System.Web.Mvc;    
    9. using WebApplication1.Models;    
    10.     
    11.     
    12. namespace WebApplication1.Controllers    
    13. {    
    14.     public class MapsController : Controller    
    15.     {    
    16.         private test2Entities db = new test2Entities();    
    17.     
    18.         // GET: Maps    
    19.         public ActionResult Index()    
    20.         {    
    21.             return View(db.Maps.ToList());    
    22.         }    
    23.   
    24.         #region [Map]    
    25.         [HttpPost]    
    26.         public JsonResult GetMap()    
    27.         {    
    28.             var data1 = Map();    
    29.             return Json(data1, JsonRequestBehavior.AllowGet);    
    30.         }    
    31.         public IEnumerable<Map> Map()    
    32.         {    
    33.     
    34.             return (from p in db.Maps    
    35.                     select new    
    36.                     {    
    37.                         Name = p.Name,    
    38.                         Latitude = p.Latitude,    
    39.                         Longitude = p.Longitude,    
    40.                         Location = p.Location,    
    41.                         Description = p.Description,    
    42.                         Id = p.Id    
    43.                     }).ToList()    
    44.                 .Select(res => new Map    
    45.                 {    
    46.                     Name = res.Name,    
    47.                     Latitude = res.Latitude,    
    48.                     Longitude = res.Longitude,    
    49.                     Location = res.Location,    
    50.                     Description = res.Description,    
    51.                     Id = res.Id    
    52.     
    53.     
    54.                 });    
    55.     
    56.         }    
    57.         #endregion    
    58.       
    59.     }    
    60. }   
    IEnumerable get List of table values. Select query will return set of values and JsonResult post data to ajax request using HttpPost keyword.

    View

    Write the following reference for Leaflet Js and css because it is an important reference to mention.
    1. <link rel="stylesheet" type="text/css" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />    
    2. <script type='text/javascript' src='http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js?2'></script>    
    3.     
    4. <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>  
    Map div tag,
    1. <div id="map" style="height: 440px; border: 1px solid #AAA;"></div>  
    Complete code
    1. @model IEnumerable<WebApplication1.Models.Map>    
    2.     
    3. @{    
    4.     Layout = null;    
    5. }    
    6.     
    7. <link rel="stylesheet" type="text/css" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />    
    8. <script type='text/javascript' src='http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js?2'></script>    
    9.     
    10. <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>    
    11.     
    12. <div id="map" style="height: 440px; border: 1px solid #AAA;"></div>    
    13.     
    14. <script type="text/javascript">    
    15.     
    16. $(document).ready(function () {    
    17.     var map = L.map('map', {    
    18.     
    19.         center: [10.1102278, 77.8958904],    
    20.           minZoom: 4,    
    21.           zoom: 6    
    22.     });    
    23.                 $.ajax({    
    24.                     type: "POST",    
    25.                     url: '/Maps/GetMap',    
    26.                     success: function (data) {    
    27.                         var result = JSON.stringify(data);    
    28.     
    29.                         for (var i = 0; i < result.length; ++i) {    
    30.                             var popup ='<b>Name:</b> '+ data[i].Name +    
    31.                             '<br/><b>Latitude:</b> ' + data[i].Latitude +    
    32.                               '<br/><b>Longitude:</b> ' + data[i].Longitude+    
    33.                            '<br/><b>Location:</b> ' + data[i].Location;    
    34.     
    35.     
    36.                             L.marker([data[i].Latitude, data[i].Longitude])    
    37.                                 .bindPopup(popup)    
    38.                                .addTo(map);    
    39.                         }    
    40.     
    41.                     },    
    42.                     error: function (xhr) {    
    43.     
    44.                         console.log(xhr.responseText);    
    45.                         alert("Error has occurred..");    
    46.                     }    
    47.                 });    
    48.     
    49.                 L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {    
    50.                     attribution: '© <a href="http://osm.org/copyright" title="OpenStreetMap" target="_blank">OpenStreetMap</a> contributors | Tiles Courtesy of <a href="http://www.mapquest.com/" title="MapQuest" target="_blank">MapQuest</a> <img src="http://developer.mapquest.com/content/osm/mq_logo.png" width="16" height="16">',    
    51.                     subdomains: ['otile1''otile2''otile3''otile4']    
    52.                 }).addTo(map);    
    53.     
    54.             });    
    55.     
    56. </script>  
  5. The Div id "map" gets the following functions for showing the map. This map has a default view latitude and longitude using centerkey word, and user can change zoom level also.

  6. Ajax method retrieves latitude and longitude and the retrieved values for map using marker and bind popup method show the user details on clicking this marker.

    Output

    Output

Summary

We learned how to get Osm Map user details and location based on latitude and longitude from database using CRUD Functionality with the Entity Framework in ASP.NET MVC and Leaflet. I hope this article is useful for all .NET beginners.

Read more articles on ASP.NET:

Up Next
    Ebook Download
    View all
    Learn
    View all