Displaying markers on Google map dynamically in ASP.NET

Sheonarayan
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 17379 red flag
Rating: 5 out of 5  
 2 vote(s)

In this article, we are going to play with Google map and will display different markers for the Latitude and Longitude coming from the database.


 Download source code for Displaying markers on Google map dynamically in ASP.NET

Introduction


Google map has become a ultimate choice to show the location of offices, malls and other places of interest on the website. This makes easy for the end user to understand and get a overall feeling about the location.

Lets place markers on Google map dynamically


To demonstrate how to place markers of different locations on Google map, we will take example of few cities of India namely "Hyderabad, Delhi, Mumbai and Chennai".

Bringing Latitude, Longitude and other information dynamically


To bring Latitude, Longitude and other information, we have code below in the code behind of .aspx page.

Server side code
public partial class _Default : System.Web.UI.Page
{
    protected string _centerMap = string.Empty;
    protected string _markers = string.Empty;
    protected int _mapZoomLevel = 5; // initial zoom level of the map

    protected void Page_Load(object sender, EventArgs e)
    {
       // this show the intial location of the map on the screen
        _centerMap = "21.0000, 78.000";        

       // in real time, this info will come from the database
       // make sure that you are formatting the data in below format only
        _markers = "[ ['Hyderabad', 17.9990, 78.8260, 1, 'D'], " +
                      " ['Delhi', 28.6100, 77.2300, 2, 'I'], " +
                      " ['Mumbai', 18.9750, 72.8258, 3, 'D'], " +
                      " ['Chennai', 13.0839, 80.2700, 4, 'I'] " +
                        "];";
    }
}
In the above code snippet, we have three page level variables that we are going to use in JavaScript code of the .aspx page. These are
  • _centerMap instruct google map to display the initial location when the page loads
  • _markers instruct google map to display the markers on what latitude and longitude; apart from this it also has some data like title of the location, type of the location etc. In real time application, this information should be brought from the database. Please make sure that the formatting of the records are maintained in this format only.
  • _mapZoomLevel instruct google map to show the map at what zoom level when the page loads



HTML code

The HTML code is pretty simple
 <style>
        html, body, #map_canvas {
            height: 100%;
            margin: 0px;
            padding: 0px;
        }
    </style>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<body>
    <form runat="server" id="form1">
        <table>
            <tr>
                <td></td>
                <td>The map with markers
                </td>
            </tr>
        </table>
    </form>

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

</body>
In the above code snippet, we have reference of jQuery and google map script files, both from Google CDN. The body part only contain a simple Title in this case, however can be kept other information as well.

The important code to look for in the body is <div id="map_canvas"></div> where the actual google map is placed by the Google API.

JavaScript code

The JavaScript code that uses objects and methods of Google API are below. In this code, we are setting the values of respective variable and properties from the server side variables declared in the first code snippet.

<script>
        function initialize() {
            var mapOptions = {
                zoom: <%= _mapZoomLevel %>,
                center: new google.maps.LatLng(<%= _centerMap %>)
            }
            map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
            setMarkers(map, markers);
        }

        markers = <%= _markers %>;

        function setMarkers(map, locations) {
            shape = {
                coords: [1, 1, 1, 20, 18, 20, 18, 1],
                type: 'poly'
            };
            
            for (var i = 0; i < locations.length; i++) {
                var marker = locations[i];
                var myLatLng = new google.maps.LatLng(marker[1], marker[2]);
                var marker = new google.maps.Marker({
                    position: myLatLng,
                    map: map,
                    icon: DecideImage(marker[4]),
                    shape: shape,
                    title: marker[0],
                    zIndex: marker[3]
                });
            }
        }

        google.maps.event.addDomListener(window, 'load', initialize);

        // =============
        function DecideImage(flag)
        {
            var url = '';
            switch (flag)
            {
                case "D":
                    url = 'DotNetFunda.png';
                    break;
                case "I":
                    url = 'itfunda.png';
                    break;
                default:
                    url = 'DotNetFunda.png';
                    break;
            }
            return url;
        }
    </script>

Below are explanations of methods and variables in the above code.

initialize() method

This method is responsible to initialize google map options and map object. In the mapOptions variable we set the zoom level and the initial position of the map when it loads on the page.

markers variable

This variable simply holds the server side data that contains Title, Latitude, Longitude etc. of the locations.

setMarkers() method

This method accept map object from Initialize() method and markers variable and loop through each marker and set respective properties value like position, map, icon, shape, title etc.

DecideImage() method

This method simply takes the last value of the respective marker record and returns the image based on it.

At last the Google map initialize method is called when window loads by calling .addDomListener method.

Conclusion

In this way, we can display n number of markers on Google map that is of different types. Thanks to google for providing this nice API for free.

Feel free to download the source code explained in this article and use it in your application.

Thanks for reading and do subscribe to get notification of new articles directly in your email.

Reference


Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Chvrsri on: 10/27/2014 | Points: 25
Hi Sheo,

Excellent article !! 5 from me !! :)

Thanks,
Srikanth
Posted by: Sheonarayan on: 11/4/2014 | Points: 25
Thanks dear!

Login to post response

Comment using Facebook(Author doesn't get notification)