Working with Google Maps Javascript API V3

Google Maps Javascript API V3 is an awesome API provided by Google. Today I will give you a little flavor about this API. Later I will write about some advance features.

Here is a simple tool, created using this API. Click on the marker, the Latitude and Longitude position will be displayed in a window and also in the textbox. If you set a Latitude, Longitude point in the textbox and click on the button, that point will be shown in the map with a marker.

Latitude

Longitude


Now I'm going to show you, how you can make this tool..

First load the Google Maps Javascript API and the latest jQuery version . Then design the user interface.

 
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://zmodal.googlecode.com/files/jquery-1.6.1.min.js"></script>

<div style="float:left; width:200px; border:1px solid #CCCCCC;">
        Latitude <input type="text" id="tbLattitude"/><br/>
        Longitude <input type="text" id="tbLongitude"/><br/>
        <input type="button" name="btCal" value="Show in Map" onclick="return showInMap();" />
    </div>
    <div id="map_canvas" style="float:left;width: 400px; height: 400px; border: 2px solid #999;margin-left:10px;">
    </div>

The DIV element with id 'map_canvas' will be the container of the Map. This id will be required when you create the map object to display in this div.

Now come to the Javascript part..

Set the window onLoad callback method and in that method, call the LoadMap method with initial latitude,longitude.

 
google.maps.event.addDomListener(window, 'load', initializeMap);
function initializeMap() {
  LoadMap(23.70992, 90.40714);
}

In the LoadMap method first create a LatLng object using the lat, long parameter

 
function LoadMap(lat, longitude) {
var latlng = new google.maps.LatLng(lat, longitude);
Create a Map object using map options and the container ID
 
var myOptions = {
  zoom: 12,
  center: latlng, // previously created LatLng object
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

For the information window first create the content of the window then create a InfoWindow object using the content. This object will be later used in the onClick event of the Marker.

var contentString = '
' + 'Latitude : '+lat+'
Longitude : ' + longitude + '' '
'; var infowindow = new google.maps.InfoWindow({ content: contentString });

Now create the Marker object using the LatLng and Map object.

var marker = new google.maps.Marker({
  position: latlng,
  map: map,
  title: 'Location',
  draggable: true,
  animation: google.maps.Animation.DROP
});

Finally add an event listener for the Marker object. First open the InfoWindow object then call the method which set LatLng value to the textbox.

  google.maps.event.addListener(marker, 'click', function (event) {
    infowindow.open(map, marker);
    setLatLongToTextBox(event.latLng);
  });

}
Here is the setLatLongToTextBox and showInMap method
function setLatLongToTextBox(latlong) {
  var latstr = latlong + '';
  var value = latstr.slice(1, latstr.length - 1);
  var latlongs = value.split(",");
  $("#tbLattitude").attr("value", latlongs[0]);
  $("#tbLongitude").attr("value", latlongs[1]);
}

//this method is used as the onclick method of the button 
function showInMap() {
  var lat = $("#tbLattitude").attr("value");
  var longitude = $("#tbLongitude").attr("value");
  LoadMap(lat, longitude);
  return false;
}

Working with Google Chart Tools : Create a Geochart

Geochart can be a handy tool if you want to represent the demographic behavior of your service. In my recent project for Bangladesh Post Office I used this tool to represent the usage of their service in each Division of Bangladesh. Another big example is the Google Analytics where you can view the location based visitor information of your site. Here I am going to show you how you can use this in your project.

First load the Google's Javascript API
<script src="https://www.google.com/jsapi" type="text/javascript">  
</script> 

Now create a DIV element and give it an ID. This id will be required when you create the chart object to display in this div.

<div id="map">
    </div>

In your Javascript code first load the geomap package and set the onLoadCallback method name.

<script type="text/javascript">
 google.load('visualization', '1', { 'packages': ['geomap'] });
 google.setOnLoadCallback(drawGeoChart);

In the callback method first create a DataTable object add two columns. Just give a suitable name as per your requirement.

 function drawGeoChart() {
            var data = new google.visualization.DataTable();
            data.addRows(6);
            data.addColumn('string', 'Country');
            data.addColumn('number', 'Visit');

Now set some value to the DataTable. The first column can be an Address, country name, region name locations, or US metropolitan area codes. For country and region name follow this ISO-3166 code or text equivalent to the code. The second column will be the value of the area.

            data.setValue(0, 0, 'Germany');
            data.setValue(0, 1, 600);
            data.setValue(1, 0, 'United States');
            data.setValue(1, 1, 500);
            data.setValue(2, 0, 'Bangladesh');
            data.setValue(2, 1, 400);
            data.setValue(3, 0, 'Canada');
            data.setValue(3, 1, 200);
            data.setValue(4, 0, 'France');
            data.setValue(4, 1, 200);
            data.setValue(5, 0, 'RU');
            data.setValue(5, 1, 300);
Finally configure some property of the chart and draw it using the data previously set.
  var regionOptions = {};
  regionOptions['width'] = '400';
  regionOptions['height'] = '250';
  // Look the div id is used here to create the chart object 
  var regionChart = new  google.visualization.GeoMap(document.getElementById('map'));
  regionChart.draw(data, regionOptions);
        
}
</script>
And here is the outcome. On mouse over you can view the data of the area



You can load the chart data by a webservice call. For C# see my previous blog. Visit this link to know more about Geochart.

Working with Google Chart Tools in C# .NET : Create a Simple Pie Chart

If you want to load a chart asynchronously in C# . NET, Google Chart Tools will be the perfect choice for you. It is easy to use and enough flexible to customize. Suppose you want to show how many students in your class like Pizza, Burger, Hotdog, and Fried Chicken in a Pie chart. Here I will show you how to load the students' data from server side using WebService and show it in a chart asynchronously.

First create a new WebService file suppose GoogleChart.asmx . In this file create a Public Class named FoodLikingCount

    public class FoodLikingCount
    {
        public int PizzaCount { get; set; }
        public int BurgerCount { get; set; }
        public int HotdogCount { get; set; }
        public int FriedChickenCount { get; set; }
    }

After the class declaration add the following line

[System.Web.Script.Services.GenerateScriptType(typeof(FoodLikingCount))]

It will enable you to use the FoodLikingCount object in your Javascript code.

Create a new WebMethod in the WebService class named GetFoodLikingCountData

[WebMethod]
public FoodLikingCount GetFoodLikingCountData()
{
       FoodLikingCount countModel = new FoodLikingCount 
       {
           PizzaCount = 12,
           BurgerCount = 16,
           HotdogCount = 8,
           FriedChickenCount = 4,
       };
       // you can also load data from your database here

       return countModel ;
}

Now come to client side code. Create an aspx file named GoogleChartToolTest.aspx and add this line between head tag.

 <script src="https://www.google.com/jsapi" type="text/javascript">
 </script> 

Create a DIV element and give it an ID. This id will be required when you create the chart object to display in this div. Also add a ScriptManager to call your webservice method.

    <form id="form1" runat="server">
        <asp:ScriptManager ID="sm1" runat="server">
            <Services>
                 <asp:ServiceReference Path="~/[your_package]/GoogleChart.asmx" />
            </Services>
        </asp:ScriptManager>
    </form>
    <div id="pie_chart">
    </div>

Here is the Javascript code which you require to load data through the webservice call, create, and show chart in the div.

<script type="text/javascript">

//load the corechart package, the pie chart is in this package
google.load('visualization', '1', { packages: ['corechart'] });

//provide the method name which you want to call as onload callback
google.setOnLoadCallback(loadFoodLikingChart);

function loadFoodLikingChart()
{
       [your_package].GoogleChart.GetFoodLikingCountData(
            function (ws_rsp) {
              var foodLikingData= new google.visualization.DataTable();
              foodLikingData.addColumn('string', 'Food');
              foodLikingData.addColumn('number', 'Count');
              foodLikingData.addRows(4);
              
              foodLikingData.setValue(0, 0, "Pizza");
              foodLikingData.setValue(0, 1, ws_rsp.PizzaCount );
              foodLikingData.setValue(1, 0, "Burger");
              foodLikingData.setValue(1, 1, ws_rsp.BurgerCount );
              foodLikingData.setValue(2, 0, "Hotdog");
              foodLikingData.setValue(2, 1, ws_rsp.HotdogCount );
              foodLikingData.setValue(3, 0, "Fried Chicken");
              foodLikingData.setValue(3, 1, ws_rsp.FriedChickenCount );

              var options = {};
              options ['width'] = '400';
              options ['height'] = '250';
              options ['chartArea'] = { left: 20, top: 20, width: '95%', height: '90%' };

              // Look the div id is used here to create the chart object
              var chart = new google.visualization.PieChart(document.getElementById('pie_chart'));
              chart.draw(foodLikingData,options);
            },
            function (e) {
               alert("Error");
           }
      );
}
</script>

The result will be like this.

Visualize the DataTable as a two dimensional array. It will help you to understand the above code. Here is the Google Chart Gallery. You will get a lot of example there.

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers