in this article, i will show you, how to use google map and add location dynamically using
asp.net mvc
---db script---
create table GoogleMap
(
ID int identity(1,1) NOT NULL,
CityName nvarchar(50) NULL,
Latitude numeric(18,4) NULL,
Longitude numeric(18,4) NULL,
Description nvarchar(500) NULL
)
go
create procedure usp_addnewlocation
(
@cityname nvarchar(50),
@latitude numeric(18,4),
@longitude numeric(18,4),
@description nvarchar(100)
)
as
begin
insert into GoogleMap (CityName,Latitude,Longitude,Description) values(@citname,@latitude,@longitude,@description)
end
go
create procedure usp_getmap
as
begin
select CityName,Latitude,Longitude, Description from GoogleMap
end
---model class---
public class Locations
{
public int ID { get; set; }
[Required(ErrorMessage = "Please enter city name")]
[Display(Name = "City Name")]
public string CityName { get; set; }
[Required(ErrorMessage = "Please enter city latitude")]
public double Latitude { get; set; }
[Required(ErrorMessage = "Please enter city longitude ")]
public double Longitude { get; set; }
public string Description { get; set; }
}
---controller---
private SqlConnection con;
private SqlCommand cmd;
private void connection()
{
con = new SqlConnection("Data Source=.;Integrated Security=true;Initial Catalog=TESTDB");
}
public List<Locations> GetData()
{
List<Locations> loclst = new List<Locations>();
DataSet ds = new DataSet();
connection();
cmd = new SqlCommand("usp_getmap", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Locations locobj = new Locations();
locobj.CityName = ds.Tables[0].Rows[i]["CityName"].ToString();
locobj.Latitude = Convert.ToDouble(ds.Tables[0].Rows[i]["Latitude"]);
locobj.Longitude = Convert.ToDouble(ds.Tables[0].Rows[i]["Longitude"]);
locobj.Description = ds.Tables[0].Rows[i]["Description"].ToString();
loclst.Add(locobj);
}
con.Close();
return loclst;
}
public JsonResult GetMapData()
{
return Json(GetData(), JsonRequestBehavior.AllowGet);
}
public ActionResult Location()
{
return View();
}
[HttpPost]
public ActionResult AddLocation(Locations location)
{
try
{
connection();
cmd = new SqlCommand("usp_addnewlocation", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@cityname", location.CityName);
cmd.Parameters.AddWithValue("@latitude", location.Latitude);
cmd.Parameters.AddWithValue("@longitude", location.Longitude);
cmd.Parameters.AddWithValue("@description", location.Description);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
ex.Message.ToString();
}
return RedirectToAction("Location");
}
---view page---
@model GoogleMapMarker.Models.Locations
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>google map location</title>
<style>
.pac-container {
z-index: 10000 !important;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7ySADLW8s5JR9LvasMVvQ_1S84JgYNzo&libraries=places"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/scripts/jquery-3.3.1.min.js"></script>
<script src="~/scripts/bootstrap.min.js"></script>
<script src="~/scripts/jquery.validate.min.js"></script>
<script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
//create a blank array
var markers = [], center;
$.ajax({
url: '/home/GetMapData',
type: 'GET',
success: function (data) {
$.each(data, function (index, item) {
//create a blank array of address
var marker = {};
//fill data
marker["name"] = item.CityName;
marker["lat"] = item.Latitude;
marker["log"] = item.Longitude;
marker["description"] = item.Description;
//push the current marker details in markers array
markers.push(marker);
})
}
});
console.log(markers)
window.onload = function () {
$("#CityName").removeAttr('placeholder').trigger('change');
if (markers.length > 0) {
center = new google.maps.LatLng(markers[0].lat, markers[0].log)
}
else {
center = new google.maps.LatLng(0, 0);
}
var mapOptions = {
center: center,
zoom: 4.2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("GoogleMap"), mapOptions);
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.log);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
<script>
$(document).ready(function () {
location_input = $("#CityName");
var options = {
types: ['(cities)']
};
autocomplete = new google.maps.places.Autocomplete(location_input.get(0), options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace().formatted_address;
getlatlog(showlatlog, place)
});
});
function showlatlog(result) {
document.getElementById('Latitude').value = result.geometry.location.lat();
document.getElementById('Longitude').value = result.geometry.location.lng();
}
function getlatlog(callback, address) {
// If adress is not supplied, use default value 'INDIA'
address = address || 'INDIA';
// Initialize the Geocoder
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(results[0]);
}
});
}
}
</script>
</head>
<body>
@using (Html.BeginForm("AddLocation", "Home", FormMethod.Post))
{
<div class="container py-4">
<h5 class="text-center">how to create google map and add location dynamically using asp.net mvc</h5>
<div class="card">
<div class="card-header bg-danger">
<h6 class="card-title text-uppercase text-white text-center">Google Map Location</h6>
</div>
<div class="card-body">
<button style="margin-bottom:10px;" type="button" data-target="#myMap" data-toggle="modal" class="btn btn-danger btn-sm rounded-0"><i class="fa fa-plus-circle"></i> Add New Location</button>
<div class="modal fade" id="myMap">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add New Location</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-4 col-md-4 col-xs-12">
<div class="form-group">
<label>City Name:</label>
@Html.EditorFor(model => model.CityName, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CityName, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-sm-4 col-md-4 col-xs-12">
<div class="form-group">
<label>Latitude:</label>
@Html.EditorFor(model => model.Latitude, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Latitude, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-sm-4 col-md-4 col-xs-12">
<div class="form-group">
<label>Longitude:</label>
@Html.EditorFor(model => model.Longitude, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Longitude, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-xs-12">
<div class="form-group">
<label>Description:</label>
<textarea name="Description" rows="5" class="form-control"></textarea>
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>
<button class="btn btn-primary rounded-0">Submit</button>
</div>
</div>
</div>
</div>
<div id="GoogleMap" class="card" style="width: 100%; height: 500px">
</div>
</div>
</div>
</div>
}
</body>
</html>
asp.net mvc
---db script---
create table GoogleMap
(
ID int identity(1,1) NOT NULL,
CityName nvarchar(50) NULL,
Latitude numeric(18,4) NULL,
Longitude numeric(18,4) NULL,
Description nvarchar(500) NULL
)
go
create procedure usp_addnewlocation
(
@cityname nvarchar(50),
@latitude numeric(18,4),
@longitude numeric(18,4),
@description nvarchar(100)
)
as
begin
insert into GoogleMap (CityName,Latitude,Longitude,Description) values(@citname,@latitude,@longitude,@description)
end
go
create procedure usp_getmap
as
begin
select CityName,Latitude,Longitude, Description from GoogleMap
end
---model class---
public class Locations
{
public int ID { get; set; }
[Required(ErrorMessage = "Please enter city name")]
[Display(Name = "City Name")]
public string CityName { get; set; }
[Required(ErrorMessage = "Please enter city latitude")]
public double Latitude { get; set; }
[Required(ErrorMessage = "Please enter city longitude ")]
public double Longitude { get; set; }
public string Description { get; set; }
}
---controller---
private SqlConnection con;
private SqlCommand cmd;
private void connection()
{
con = new SqlConnection("Data Source=.;Integrated Security=true;Initial Catalog=TESTDB");
}
public List<Locations> GetData()
{
List<Locations> loclst = new List<Locations>();
DataSet ds = new DataSet();
connection();
cmd = new SqlCommand("usp_getmap", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Locations locobj = new Locations();
locobj.CityName = ds.Tables[0].Rows[i]["CityName"].ToString();
locobj.Latitude = Convert.ToDouble(ds.Tables[0].Rows[i]["Latitude"]);
locobj.Longitude = Convert.ToDouble(ds.Tables[0].Rows[i]["Longitude"]);
locobj.Description = ds.Tables[0].Rows[i]["Description"].ToString();
loclst.Add(locobj);
}
con.Close();
return loclst;
}
public JsonResult GetMapData()
{
return Json(GetData(), JsonRequestBehavior.AllowGet);
}
public ActionResult Location()
{
return View();
}
[HttpPost]
public ActionResult AddLocation(Locations location)
{
try
{
connection();
cmd = new SqlCommand("usp_addnewlocation", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@cityname", location.CityName);
cmd.Parameters.AddWithValue("@latitude", location.Latitude);
cmd.Parameters.AddWithValue("@longitude", location.Longitude);
cmd.Parameters.AddWithValue("@description", location.Description);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
ex.Message.ToString();
}
return RedirectToAction("Location");
}
---view page---
@model GoogleMapMarker.Models.Locations
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>google map location</title>
<style>
.pac-container {
z-index: 10000 !important;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7ySADLW8s5JR9LvasMVvQ_1S84JgYNzo&libraries=places"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/scripts/jquery-3.3.1.min.js"></script>
<script src="~/scripts/bootstrap.min.js"></script>
<script src="~/scripts/jquery.validate.min.js"></script>
<script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
//create a blank array
var markers = [], center;
$.ajax({
url: '/home/GetMapData',
type: 'GET',
success: function (data) {
$.each(data, function (index, item) {
//create a blank array of address
var marker = {};
//fill data
marker["name"] = item.CityName;
marker["lat"] = item.Latitude;
marker["log"] = item.Longitude;
marker["description"] = item.Description;
//push the current marker details in markers array
markers.push(marker);
})
}
});
console.log(markers)
window.onload = function () {
$("#CityName").removeAttr('placeholder').trigger('change');
if (markers.length > 0) {
center = new google.maps.LatLng(markers[0].lat, markers[0].log)
}
else {
center = new google.maps.LatLng(0, 0);
}
var mapOptions = {
center: center,
zoom: 4.2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("GoogleMap"), mapOptions);
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.log);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
<script>
$(document).ready(function () {
location_input = $("#CityName");
var options = {
types: ['(cities)']
};
autocomplete = new google.maps.places.Autocomplete(location_input.get(0), options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace().formatted_address;
getlatlog(showlatlog, place)
});
});
function showlatlog(result) {
document.getElementById('Latitude').value = result.geometry.location.lat();
document.getElementById('Longitude').value = result.geometry.location.lng();
}
function getlatlog(callback, address) {
// If adress is not supplied, use default value 'INDIA'
address = address || 'INDIA';
// Initialize the Geocoder
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(results[0]);
}
});
}
}
</script>
</head>
<body>
@using (Html.BeginForm("AddLocation", "Home", FormMethod.Post))
{
<div class="container py-4">
<h5 class="text-center">how to create google map and add location dynamically using asp.net mvc</h5>
<div class="card">
<div class="card-header bg-danger">
<h6 class="card-title text-uppercase text-white text-center">Google Map Location</h6>
</div>
<div class="card-body">
<button style="margin-bottom:10px;" type="button" data-target="#myMap" data-toggle="modal" class="btn btn-danger btn-sm rounded-0"><i class="fa fa-plus-circle"></i> Add New Location</button>
<div class="modal fade" id="myMap">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add New Location</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-4 col-md-4 col-xs-12">
<div class="form-group">
<label>City Name:</label>
@Html.EditorFor(model => model.CityName, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CityName, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-sm-4 col-md-4 col-xs-12">
<div class="form-group">
<label>Latitude:</label>
@Html.EditorFor(model => model.Latitude, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Latitude, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-sm-4 col-md-4 col-xs-12">
<div class="form-group">
<label>Longitude:</label>
@Html.EditorFor(model => model.Longitude, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Longitude, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-xs-12">
<div class="form-group">
<label>Description:</label>
<textarea name="Description" rows="5" class="form-control"></textarea>
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>
<button class="btn btn-primary rounded-0">Submit</button>
</div>
</div>
</div>
</div>
<div id="GoogleMap" class="card" style="width: 100%; height: 500px">
</div>
</div>
</div>
</div>
}
</body>
</html>
0 Comments
if you have any doubts , please let me know