Adding markers to Google Maps from database using ASP.NET

Introduction

Here, I will explain how to add markers to Google Maps from SQL Server database using ASP.NET

Adding Markers to a Google Maps from database

Description

Here first we will create a table “Locations” in the SQL Server database to store latitude and longitude of the places to which we want to add markers

Step 1:

Create table as following

CREATE TABLE [dbo].[Locations](
     [Latitude] [float] NOT NULL,
     [Longitude] [float] NOT NULL,
     [City] [varchar](50) NULL,
     [Country] [varchar](50)NULL
)

Step 2:

Add following data in the table

Location Table Data

Step 3:

Create a new ASP.NET application and add following in HTML source of a page

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
     <title>
          Adding Markers to a Google Maps from database
     </title>

     <script type="text/javascript"
     src="https://maps.googleapis.com/maps/api/js?key=Your_API_KEY&sensor=false">
     </script>
</head>

<body onload="initialize()">
     <form id="form1" runat="server">
          <div id="mapArea" style="width: 500px; height: 500px;">
          </div>

          <asp:Literal ID="Literal1" runat="server"></asp:Literal>
     </form>
</body>
</html>

Here, we have added only one script tag to include Google Maps API libraries. We will add other script tag to create map and markers on it from the code behind at runtime. We will use the Literal control “Literal1” to add second script at runtime.

Step 4:

Write following in code behind of the page

C#:

protected void Page_Load(object sender, EventArgs e)
{
     string markers=GetMarkers();
     Literal1.Text = @"
     <script type='text/javascript'>
     function initialize() {

     var mapOptions = {
     center: new google.maps.LatLng(28.3213, 77.5435),
     zoom: 2,
     mapTypeId: google.maps.MapTypeId.ROADMAP
     };

     var myMap = new google.maps.Map(document.getElementById('mapArea'),
     mapOptions);"
     +markers+
     @"}
     </script>";
}

protected string GetMarkers()
{
     string markers = "";
     using (SqlConnection con = new
     SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
     {
          SqlCommand cmd = new SqlCommand("SELECT Latitude, Longitude, City FROM Locations", con);
          con.Open();
          SqlDataReader reader = cmd.ExecuteReader();
          int i = 0;

         while (reader.Read())
         {
              i++;
              markers +=
              @"var marker"+i.ToString()+@" = new google.maps.Marker({
              position: new google.maps.LatLng("+reader["Latitude"].ToString() + ", " +
              reader["Longitude"].ToString() +"),"+
              @"map: myMap,
              title:'" + reader["City"].ToString() + "'});";
         }
     }
     return markers;
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     Dim markers As String = ""
     markers = GetMarkers()
     Literal1.Text = "<script type='text/javascript'>" + _
     "function initialize() {" + _
     "var mapOptions = {" + _
     "center: new google.maps.LatLng(28.3213, 77.5435)," + _
     "zoom: 2," + _
     "mapTypeId : google.maps.MapTypeId.ROADMAP" + _
     "};" + _
     "var myMap = new google.maps.Map(document.getElementById('mapArea'), mapOptions);" + _
     markers + _
     "}" + _
     "</script>"
End Sub

Protected Function GetMarkers() As String
     Dim markers As String = ""

     Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConString").ConnectionString)
          Dim cmd As SqlCommand = New SqlCommand("SELECT Latitude, Longitude, City FROM Locations", con)
          con.Open()
          Dim reader As SqlDataReader = cmd.ExecuteReader()
          Dim i As Integer = 0
          While reader.Read()
               i = i + 1
               markers = markers + "var marker" + i.ToString() + "= new google.maps.Marker({" + _
               "position: new google.maps.LatLng( " + reader("Latitude").ToString() + ", " + _
               reader("Longitude").ToString() + ")," + _
               "map: myMap," + _
               "title:'" + reader("City").ToString() + "'});"
          End While
          con.Close()
     End Using
     Return markers
End Function

Here, in the Page Load event we have set Text property of the Literal control to the generated Script tag to draw the map and add markers returned from “GetMarkers” method. “GetMarkers” method creates a marker object for all the records in the “Locations” table and returns string like following:

var marker1 = new google.maps.Marker({
     position: new google.maps.LatLng(28.8, 77.03),
     map: myMap,
     title: 'New Delhi'
});

var marker2 = new google.maps.Marker({
     position: new google.maps.LatLng(18.98, 72.83),
     map: myMap,
     title: 'Mumbai'
});

20 thoughts on “Adding markers to Google Maps from database using ASP.NET

  1. fikar

    could you send me example Adding markers to Google Maps from database using ASP.NET, using mysql database ?
    Regards
    Fikar

    Reply
      1. matt

        hi, can you tell me the solution if there are 2 markers sharing the same address – number or street. what seems to happen on my site is that the marker sits under the other and does not respond to click and seperate like it does with other ones?

        Reply
  2. matt

    hi, I have got this working. I add a SELECT clause that has a parameter @City and it returns the markers where the user has specified a city in text box. But my problem is when map first loads I want it to show a Zoom in on that city with the markers but instead its showing another part of world and not related to the search? please could you show how to by default zoom to the city? in C sharp

    Reply
  3. knz

    Thank you sir your article is really helpful but only problem i am facing is that i am using a master page for my project and there is no body tag in the content page so how can i call initialize function onload.I shall be very thankful to you if you change code according to the problem.

    Reply
  4. Pingback: google maps add marker - Search Yours

  5. R.suresh kumar from vcet erode mca

    hai sir
    , i want to set image icon to different cities how?
    plz send the coding explanation sir

    Reply
  6. khushali

    Hello sir,your code has been very helpful to us so far.But we seek a minor change in this code regarding our project. As in this project ,all the markers are displayed for the the places stored in database,our project is somewhat different.We need marker on one place that is selected from the database.to elaborate,if we select an area from the dropdownlist that contains names of areas stored in database,then “only” marker on that place must be displayed.Further,selecting the subarea from dropdownlist2 should zoom the map and display a marker on that subarea.so how do we do that? what are the changes required to be made in this code?
    Awaiting your rply.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *