How to show multiple markers on Google maps from database in ASP.Net

A simple way to show multiple markers on Google maps from database in ASP.Net using SQL and Repeater.
Follow the steps below:

1) Create a Table in you DB.

CREATE TABLE [dbo].[CustomerDetails] (
    [ID]           INT            IDENTITY (1, 1) NOT NULL,
    [CustomerName] NVARCHAR (MAX) NULL,

    [Address] NVARCHAR (MAX) NULL,
     [Latitude]     FLOAT (53)     NULL,
    [Longitude]    FLOAT (53)     NULL,
    [Image]        IMAGE          NULL,
    CONSTRAINT [PK_CustomerDetails] PRIMARY KEY CLUSTERED ([ID] ASC)
);


2) HTML Markup and Google Maps Scripts

<script src="http://maps.google.com/maps/api/js?libraries=places&key=YOUR-APIKEY-HERE"></script>


<script type="text/javascript">
         var markers = [
         <asp:Repeater ID="rptMarkers" runat="server">
         <ItemTemplate>
                     {
                         "title": '<%# Eval("
CustomerName") %>',
                "lat": '<%# Eval("Latitude") %>',
                "lng": '<%# Eval("Longitude") %>',
                         "description": '<%# Eval("Address") %>',
                         "icon":'<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("Image")) %>'

            }
</ItemTemplate>
<SeparatorTemplate>
    ,
</SeparatorTemplate>
</asp:Repeater>
];
</script>


 <script type="text/javascript">
         window.onload = function () {
             var mapOptions = {
                 center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
                 zoom: 15,
                 disableDefaultUI: true,
                 scrollwheel: false,
                 zoomControl: false,
                 scaleControl: true,
                 disableDoubleClickZoom: true,
                 mapTypeId: google.maps.MapTypeId.ROADMAP,
 <%--  This is the part where you style your map and also remove Point of Interest from the map so only your location will show up in the map. --%>
                 styles: [{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#e0efef"}]},{"featureType":"poi","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"hue":"#1900ff"},{"color":"#c0e8e8"}]},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":100},{"visibility":"simplified"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"transit.line","elementType":"geometry","stylers":[{"visibility":"on"},{"lightness":700}]},{
                     "featureType":"water","elementType":"all","stylers":[{"color":"#7dcdcd"}],
                 },
                 { "featureType": "poi", "stylers": [{ "visibility": "off" }]}
                 ]


             };
            
             var infoWindow = new google.maps.InfoWindow();
             var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
             for (i = 0; i < markers.length; i++) {
                 var data = markers[i]
                 var myLatlng = new google.maps.LatLng(data.lat, data.lng);
                 var marker = new google.maps.Marker({
                     position: myLatlng,
                     map: map,
                     title: data.title,
                     icon:data.icon
                 });
                 (function (marker, data) {
                     google.maps.event.addListener(marker, "click", function (e) {
                         //infoWindow.setContent(data.description);
                         infoWindow.setContent("<div style = 'width:200px;min-height:40px'>"+data.title+" <br/>" + data.description + "</div>");
                         infoWindow.open(map, marker);
                     });
                 })(marker, data);
             }
         }
</script>




  <div id="map_canvas"></div>

In order to populate the map with our custom location from the database we will use a Repeater Control to populate the markers array. Thus when the page is rendered in the browser the values from database are loaded within the marker array. The image is saved as binary in the DB.
 
3) In the Page_Load event of the ASP.Net Page we will populate the ASP.Net Repeater control using the records from the CustomerDetails table of the SQL Server database
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;



protected void Page_Load(object sender, EventArgs e)
        {

            if (!this.IsPostBack)
            {
           
                try
                {
                    DataTable dt = this.GetData(" Select * from CustomerDetails");
                    rptMarkers.DataSource = dt;
                    rptMarkers.DataBind();
                }
                catch (Exception)
                {
                }
            }
        }
   private DataTable GetData(string query)
        {
            string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            SqlCommand cmd = new SqlCommand(query);
            using (SqlConnection con = new SqlConnection(conString))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;

                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        return dt;
                    }
                }
            }
        }

Comments

Post a Comment

Popular posts from this blog

How to Solve Bootstrap Tooltip disappearing inside a updatepanel control when a button is click or in postback in ASP.NET

Show Bootstrap Popup Modal from inside a Repeater in Asp.Net