Populate Google Maps based on DropDownList selection using AngularJS in ASP.Net MVC

Last Reply 13 days ago By dharmendr

Posted 13 days ago

How to filter map based on dropdownlist selection.

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

Posted 13 days ago

Hirani,

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

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

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();
    }

    public JsonResult GetPlaceNames()
    {
        List<SelectListItem> names = PopulateLocations()
                                    .Select(x => new SelectListItem { Text = x.name, Value = x.name })
                                    .Distinct().ToList();
        return Json(names, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public JsonResult GetLocations(string location)
    {
        List<Location> locations;
        if (!string.IsNullOrEmpty(location))
        {
            locations = PopulateLocations().Where(x => x.name == location).ToList();
        }
        else
        {
            locations = PopulateLocations();
        }
        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; }
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <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) {
            GetMap('');
            $http({
                method: 'Get',
                url: '/Home/GetPlaceNames/'
            }).success(function (response) {
                $scope.Names = response;
            });

            $scope.Search = function () {
                GetMap($scope.searchTerm);
            }

            function GetMap(location) {
                $http({
                    method: 'POST',
                    url: '/Home/GetLocations',
                    params: { location: location }
                }).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">
        <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 />
        <div id="dvMap" style="width: 300px; height: 300px">
        </div>
    </div>
</body>
</html>

Screenshot