Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Asp.net Show Multiple Markers on Google Map V3 from Database with JavaScript

May 12, 2013
Introduction:

Here I will explain how to show  or add multiple markers to Google maps V3 from database in asp.net website using JavaScript or JavaScript Show multiple markers in Google maps using database in asp.net.

Description:

In previous article I explained clearly how to add Google map to website in asp.net, Add marker to Google map in asp.net website, JavaScript Add multiple markers to google map, jQuery image slideshow in asp.net, Sitemap navigation control example in asp.net and many articles relating to jQuery, JavaScript, asp.net. Now I will explain how to add multiple markers to Google maps from database in asp.net website.

Before add multiple markers to Google map from database we need to get Google API key for that please check below url

Once you got the key create new table in your database like as shown below

Column Name
Data Type
Allow Nulls
Id
int(set identity property=true)
No
City
varchar(50)
Yes
Latitude
numeric(12,6)
Yes
Longitude
numeric(12,6)
Yes
Description
Varchar(250)
Yes
Once table creation completed enter some sample data like as shown below


Now write the following code in your aspx to show multiple markers in Google map from database like as shown below 


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Show/Add multiple markers to Google Maps from database in asp.net website</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyC6v5-2uaq_wusHDktM9ILcqIrlPtnZgEk&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var markers = JSON.parse('<%=ConvertDataTabletoString() %>');
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
//  marker:true
};
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
});
(function(marker, data) {

// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
</head>
<body onload="initialize()">
<form id="form1" runat="server">
<div id="map_canvas" style="width: 500px; height: 400px"></div>
</form>
</body>
</html>
If you observe above code in header section I mentioned multiple latitude and longitudes of different cities and by default I mentioned one city latitude and longitude by using that default details we can center the map to near place of other cities based on that other cities whatever we are going to mark are visible.

In remaining code markers are used to add marking in google map and infowindow is used to show info of all the cities based on the description whatever we mentioned in json string.

Now add following namespaces in code behind

 C# Code


using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
After that write the following code in code behind


// This method is used to convert datatable to json string
public string ConvertDataTabletoString()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=master;Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,description from LocationDetails", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
}

VB.NET Code


Imports System.Collections.Generic
Imports System.Data
Imports System.Data.SqlClient
Partial Class Default3
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
' This method is used to convert datatable to json string
Public Function ConvertDataTabletoString() As String
Dim dt As New DataTable()
Using con As New SqlConnection("Data Source=SureshDasari;Initial Catalog=master;Integrated Security=true")
Using cmd As New SqlCommand("select title=City,lat=latitude,lng=longitude,description from LocationDetails", con)
con.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object)
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)()
For Each col As DataColumn In dt.Columns
row.Add(col.ColumnName, dr(col))
Next
rows.Add(row)
Next
Return serializer.Serialize(rows)
End Using
End Using
End Function
End Class

Demo


Download Sample Code Attached


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

33 comments :

Anonymous said...

Nice article, Thanks :)

Anas

Anonymous said...

Hi suresh..
it shows the following error

Google has disabled use of the Maps API for this application. The provided key is not a valid Google API Key, or it is not authorized for the Google Maps Javascript API v3 on this site. If you are the owner of this application, you can learn about obtaining a valid key here: https://developers.google.com/maps/documentation/javascript/tutorial#api_key

in which way i can solve this

Hi said...

var markers = JSON.parse('<%=ConvertDataTabletoString() %>');

i am getting markers as undefined .is there any other way to parse it...

Anonymous said...

Very helpful.

Unknown said...

good sir ji

Anonymous said...

hi sir..it shows an error..like JSON is not found ... what do i do?

Anonymous said...

Pls provide an article on updating marker on google map taking lat and long from database without reloading the map means only updating the marker positions asap............Shibham

Anonymous said...

Pls provide an article on updating marker on google map taking lat and long from database without reloading the map means only updating the marker positions asap

Unknown said...

Nice

Darpan Pathak said...

I have made it guys .... Contact me for the details ... i solved this issue "updating marker on google map taking lat and long from database without reloading the map means only updating the marker positions"

Anonymous said...

Thanks a lot.

aman said...

i wrote the same code but it is not displaying anything.please help

zuhry said...

my marker didn't show??? but when readeng table the procces is completed nothing error.... how can???

Unknown said...

my marker didnt show why ?

Unknown said...

Hi, i intialize google map intially then i write your javascipt code but marker not displaying.... i have two dropdownlist when i select from one dropdownlist that location should display on google map. how to achieve this

Unknown said...

i run your page in content page but not works

Anonymous said...

I case of master page there is no body tag then how can i call initialize function

Unknown said...

Hi Suresh,

Please give me a solution for,

Code is working nicely but It is not browser responsive .
when i set div id="map_canvas" style="width:100%; height: 400px"
and my page to resize when the browser resizes, but it's not working.
Please help for this..
Thank you.

Anonymous said...

Getting error "0x800a03f6 - JavaScript runtime error: Invalid character" if my database has more then 1 coordinates. please help

Unknown said...

thank you suresh anna..
escape great escape from my project manager.

by
R.suresh kumar chennai

Anonymous said...

getting error like this('<%=ConvertDataTabletoString()%>');,it says it is not decleared

Thank you

Unknown said...

var markers = JSON.parse('<%=ConvertDataTabletoString() %>');
if (marker == null)
alert("nodata");
when i checked it i got that my markers will no any data help me

Unknown said...

sorry for mistake i have data but when the page is load my map is not visible at all ...help me....
var markers = JSON.parse('<%=ConvertDataTabletoString() %>');
if (markers == null)
alert("nodata");
else
alert("data");

Unknown said...

thanks suresh i have completed what i have to do....

Anonymous said...

THANK YOU so much! I've been searching for an efficient way to do this for weeks.

Unknown said...

Its great , its working 100% fast thank you very much

Unknown said...
This comment has been removed by the author.
anji said...

how to show popup description on map like marker

Unknown said...

Thanks for the resources.

Unknown said...

THANK YOU so much! I've been searching for an efficient way to do this for weeks.

Unknown said...

how to current location insert in to database using asp.net C# please responce me

Deepak Chaudhary said...

Thank you sir ...It works thanks lot

Unknown said...

I tried this code but only map is showing. The markers are not displayed. No error on the console. What might be the issue?

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.