This is quite a possible scenario in web development to show Google maps in your web-application, so in this article, I am going to explain and show that, how you can easily integrate Google maps in your ASP.NET MVC web application & show pin (marker) inside Map using Lat/Long from the database.
If you just have the address of the location you can get location name (address) from lat-long in c# using the answer of the post, you can also calculate the distance between two location using javascript in Google Maps
Let's get started with integration, suppose we have the sample database table as given below
As you can see in the above image we have Latitude/Longitude of the address with some description to show on location pin click.
Create an MVC project
Open our Visual Studio IDE, create a new project, by navigating to "File"-> "New"-> "Project".
Select "Web" in the left pane and "ASP.NET Web application" in the right pane, provide a name for your web application(In my example it's "MultipleModelSingleView"), Click "OK".
Connect your MVC project with the above-given table using Entity framework (Database first approach), if you are new to ADO.NET, you can visit the https://qawithexperts.com/article/asp.net/mvc-tutorial-part-2-connecting-to-database-fetchinginserting/29 and learn how to connect database with MVC application using Entity framework.
Get API Key from Google's developer console
You need to get an API key from your Google's developer console. If you haven't created the project yet on the developer's console you need to create one, here is the image reference to get API from developer's console.
Also, you would have to enable Google Maps Javascript API plugin.
Get addresses data from the database
Go to your HomeController and create a new ActionResult, which will list of addresses from the database as JSON
public JsonResult GetMapMarker()
{
var ListOfAddress = context.MapsAddresses.ToList();
return Json(ListOfAddress, JsonRequestBehavior.AllowGet);
}
So, your complete HomeController Code will be as below
public class HomeController : Controller
{
private MapsExampleDBEntities context = new MapsExampleDBEntities();
public ActionResult Index()
{
return View();
}
public JsonResult GetMapMarker()
{
var ListOfAddress = context.MapsAddresses.ToList();
return Json(ListOfAddress, JsonRequestBehavior.AllowGet);
}
}
Now go to your Index ActionMethod view and add the following HTML to render the map
<div id="MapDiv" style="width: 500px; height: 500px">
</div>
Create Javascript to Load data from Controller and show it in Google Map
We will be using created JsonResult ActionMethod (GetMapMarker) to get addresses JSON using Ajax and then loop each address to get Lat/Long of the address and show it in the Map.
First, refer the Google Maps script
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YourAPIKeyHere"></script>
then Create Ajax Request and create an array of marker
$.ajax({
url: '/home/GetMapMarker',
type: 'GET',
success: function (data) {
//create a blank array
var markers = [];
//loop the list of addresses returned from Ajax request
$.each(data, function (index, item) {
//create a blank array of address
var marker = {};
//fill data
marker["title"] = item.AddressName;
marker["lat"] = item.Lat;
marker["lng"] = item.Long;
marker["description"] = item.Description;
//push the current marker details in markers array
markers.push(marker);
})
//call Map function with all markers passed as list of arrays
initializeMap(markers);
}
});
Nowe, we will create the initializeMap javascript method, which takes all addresses as an array(markers) and then loops through each array to set marker icon.
function initializeMap(markers) {
//you can check your marker data in console
console.log(markers);
//Create Google map options
var GoogleMapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//create a variable of InfoWindow type to show data on clicking map icon
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("MapDiv"), GoogleMapOptions);
//loop through each marker data
for (i = 0; i < markers.length; i++) {
var data = markers[i]
//set lat long of current marker
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) {
// add a on marker click event
google.maps.event.addListener(marker, "click", function (e) {
//show description
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
So your complete javascript code will be
<script type="text/javascript">
$.ajax({
url: '/home/GetMapMarker',
type: 'GET',
success: function (data) {
//create a blank array
var markers = [];
//loop the list of addresses returned from Ajax request
$.each(data, function (index, item) {
//create a blank array of address
var marker = {};
//fill data
marker["title"] = item.AddressName;
marker["lat"] = item.Lat;
marker["lng"] = item.Long;
marker["description"] = item.Description;
//push the current marker details in markers array
markers.push(marker);
})
//call Map function with all markers passed as list of arrays
initializeMap(markers);
}
});
function initializeMap(markers) {
//you can check your marker data in console
console.log(markers);
//Create Google map options
var GoogleMapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//create a variable of InfoWindow type to show data on clicking map icon
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("MapDiv"), GoogleMapOptions);
//loop through each marker data
for (i = 0; i < markers.length; i++) {
var data = markers[i]
//set lat long of current marker
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) {
// add a on marker click event
google.maps.event.addListener(marker, "click", function (e) {
//show description
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
I have also explained each line of the script using the comments to understand it clearly.
Complete Index View Code will be as below
@{
ViewBag.Title = "Home Page";
}
<div id="MapDiv" style="width: 500px; height: 500px">
</div>
@section scripts{
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDw4M0s-wdhkjGK1L5BkWzyilxKp15QnGY"></script>
<script type="text/javascript">
$.ajax({
url: '/home/GetMapMarker',
type: 'GET',
success: function (data) {
//create a blank array
var markers = [];
//loop the list of addresses returned from Ajax request
$.each(data, function (index, item) {
//create a blank array of address
var marker = {};
//fill data
marker["title"] = item.AddressName;
marker["lat"] = item.Lat;
marker["lng"] = item.Long;
marker["description"] = item.Description;
//push the current marker details in markers array
markers.push(marker);
})
//call Map function with all markers passed as list of arrays
initializeMap(markers);
}
});
function initializeMap(markers) {
//you can check your marker data in console
console.log(markers);
//Create Google map options
var GoogleMapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//create a variable of InfoWindow type to show data on clicking map icon
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("MapDiv"), GoogleMapOptions);
//loop through each marker data
for (i = 0; i < markers.length; i++) {
var data = markers[i]
//set lat long of current marker
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) {
// add a on marker click event
google.maps.event.addListener(marker, "click", function (e) {
//show description
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
}
Note: I am using RenderSection in _layout.cshtml of the project, and have already included jQuery with Default code.
Now, build your project and run it in the browser you will get following output
That's it you are done, as you can see in the above image, we have red icon located in the google maps area for which we have given Lat/Long and clicking the icon show's description of it.