Add Markers to Google Map on CheckBox selection using AngularJS in ASP.Net MVC

Last Reply 13 days ago By dharmendr

Posted 13 days ago

I have a dropdownlist. Based on that binding grid in mvc and angularjs.

In grid i have checkbox. When checkbox is clicked add marker to the map.

How to implement this.

Populate Google Maps with markers from database using AngularJS in ASP.Net MVC

Posted 13 days ago

Hi rani,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of LocationDB database with the table named as Locations.

You can download the database table SQL by clicking the download link below.

Download SQL file

Namespaces

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult GetLocations(string letter)
    {
        List<Location> locations;
        if (!string.IsNullOrEmpty(letter))
        {
            locations = PopulateLocations().Where(x => x.name.ToLower().Contains(letter.ToLower())).ToList();
        }
        else
        {
            locations = PopulateLocations();
        }
        return Json(locations, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public JsonResult GetMapData(string location)
    {
        List<string> places = location.Split(',').ToList();
        List<Location> locations = PopulateLocations().Where(x => places.Any(y => x.name == y)).ToList();
        return Json(locations, JsonRequestBehavior.AllowGet);
    }

    private static List<Location> PopulateLocations()
    {
        List<Location> locations = new List<Location>();
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        SqlCommand cmd = new SqlCommand("SELECT * FROM Locations");
        using (SqlConnection con = new SqlConnection(conString))
        {
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    locations.Add(new Location
                    {
                        name = sdr["Name"].ToString(),
                        lat = Convert.ToDecimal(sdr["Latitude"]),
                        lng = Convert.ToDecimal(sdr["Longitude"]),
                        description = sdr["Description"].ToString()
                    });
                }
            }
            con.Close();
        }

        return locations;
    }

    public class Location
    {
        public string name { get; set; }
        public decimal lat { get; set; }
        public decimal lng { get; set; }
        public string description { get; set; }
        public bool selected { get; set; }
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_Key"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $http) {
            $scope.Names = [
                { Text: "A", Value: "A" }, { Text: "B", Value: "B" },
                { Text: "J", Value: "J" }, { Text: "M", Value: "M" },
                { Text: "P", Value: "P" }];

            $scope.Search = function () {
                $http({
                    method: 'Post',
                    url: '/Home/GetLocations/',
                    params: { letter: $scope.searchTerm }
                }).success(function (response) {
                    $scope.Locations = response;
                });
            }
            $scope.PopulateMap = function () {
                var names = [];
                angular.forEach($scope.Locations, function (item, index) {
                    if (item.selected) {
                        names.push(item.name);
                    }
                });

                GetMap(names.join(','));
            }
            function GetMap(locations) {
                $http({
                    method: 'POST',
                    url: '/Home/GetMapData',
                    params: { location: locations }
                }).then(function (response) {
                    $scope.Markers = response.data;
                    $scope.MapOptions = {
                        center: new google.maps.LatLng($scope.Markers[0].lat, $scope.Markers[0].lng),
                        zoom: 8,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };

                    $scope.InfoWindow = new google.maps.InfoWindow();
                    $scope.Latlngbounds = new google.maps.LatLngBounds();
                    $scope.Map = new google.maps.Map(document.getElementById("dvMap"), $scope.MapOptions);

                    for (var i = 0; i < $scope.Markers.length; i++) {
                        var data = $scope.Markers[i];
                        var myLatlng = new google.maps.LatLng(data.lat, data.lng);
                        var marker = new google.maps.Marker({
                            position: myLatlng,
                            map: $scope.Map,
                            title: data.description
                        });

                        (function (marker, data) {
                            google.maps.event.addListener(marker, "click", function (e) {
                                $scope.InfoWindow.setContent("<div style = 'width:250px;min-height:40px'>" + data.description + "</div>");
                                $scope.InfoWindow.open($scope.Map, marker);
                            });
                        })(marker, data);

                        $scope.Latlngbounds.extend(marker.position);
                    }

                    $scope.Map.setCenter($scope.Latlngbounds.getCenter());
                    $scope.Map.fitBounds($scope.Latlngbounds);
                });
            }
        });
    </script>
</head>
<body>
    <div ng-app="MyApp" ng-controller="MyController">
        <div class="container">
            <select ng-model="searchTerm" ng-options="c.Value as c.Text for c in Names" ng-change="Search()">
                <option value="">-- Select Name --</option>
            </select>
            <hr />
            <table class="table table-bordered ">
                <tr class="success">
                    <th></th>
                    <th>Name</th>
                    <th>Description</th>
                </tr>
                <tr ng-repeat="location in Locations">
                    <td>
                        <input type="checkbox" ng-model="location.selected" ng-click="PopulateMap()" />
                    </td>
                    <td>{{location.name }}</td>
                    <td>{{location.description }}</td>
                </tr>
            </table>
            <hr />
            <div id="dvMap" style="width: 300px; height: 400px">
            </div>
        </div>
    </div>
</body>
</html>

Screenshot