Archive for March, 2010

Connection to the MySQL Server


Introduction to ADO.NET

ADO.NET is a group of libraries used to create powerful databases using various sources that include Microsoft SQL Server, Microsoft Access, Oracle, XML, etc. ADO.NET relies on the .NET Framework’s various classes to process requests and perform the transition between a database system and the user. The operations are typically handled through the DataSet class. While ADO.NET is the concept of creating and managing database systems, the DataSet class serves as an intermediary between the database engine and the user interface, namely the Windows controls that the user uses to interact with the computer. Still, remember that a DataSet object is used to manage lists, any lists, not just those created using database engines.

Using the MySQL Connector/Net

To support the .NET Framework applications, MySQL provides a series of classes in the MySQL Connector/Net. To use these classes, you should (must) reference the MySql.Data.dll library. The classes used by the MySQL database engine are defined in the MySql.Data namespace.

Connection to a MySQL Database

Introduction

The MySQL Connector/Net allows you to create a graphical Windows application that is data-based. When your application runs, it must connect to a MySQL database. To support this connection, you can use the MySqlConnection class that is defined in the MySql.Data.MySqlClient namespace. Before using this class, you can first include that namespace in your file.

To connect to a database, you can declare a MySqlConnection variable using one of its two constructors. The default constructor allows you to declare the variable without specifying how the connection would be carried. The second constructor takes as argument a String value. Its syntax is:

public MySqlConnection(string connectionString);

If you want, you can first create the string that would be used to handle the connection, then pass that string to the second construction. This would be done as follows:

private void btnConnect_Click(object sender, System.EventArgs e)
{
string strConnection = “”;
MySqlConnection conSQL = new MySqlConnection(strConnection);
}

You can also directly create the necessary (but appropriate) string in the second constructor when declaring the variable:

private void btnConnect_Click(object sender, System.EventArgs e)
{
MySqlConnection conSQL = new MySqlConnection(“”);
}

If you prefer to use the default constructor, you can first define a string value. To pass it to the default constructor, the MySqlConnection class is equipped with a property called ConnectionString that is of type string. You would use it as follows:

private void btnConnect_Click(object sender, System.EventArgs e)
{
string strConnection = “”;
MySqlConnection conServer = new MySqlConnection();

conServer.ConnectionString = strConnection;
}

To use a MySqlConnection object, you must provide various pieces of information, packaged as one and made available to the variable. These pieces are joined into a string but are separated from each other with a semi-colon “;”. Each piece appears as a Key=Value format. In our lesson, we will refer to each of these pieces (Key=Value) as an attribute of the connection string. When joined, these attributes appear as follows:

Key1=Value1;Key2=Value2;Key_n=Value_n

Anything that part of this string is not case-sensitive. Remember that this whole ensemble is either passed as a string to the second constructor:

MySqlConnection conServer = new MySqlConnection(“Key1=Value1;Key2=Value2;Key_n=Value_n”);

or assigned as a string to the MySqlConnection.ConnectionString property:

MySqlConnection conServer = new MySqlConnection();
string strConnection = “Key1=Value1;Key2=Value2;Key_n=Value_n”;

conServer.ConnectionString = strConnection;

How you create these attributes depends on the type of computer you are connecting to, whether you are connecting to a database, what level the security you would use (or need), etc. There are various of these attributes, some of them are always required, some of them are usually optional, and some others depend on the circumstances.

The Source of Data

To establish a connection, you must specify the computer you are connecting to, that has MySQL installed. To indicate the computer you are connecting to, use the Data Source, the DataSource, the Host, the Server, the Addr, the Address, or the Network Address attribute of the connection string. If you are connecting to a local database (installed in the same computer where the application is running), you can omit specifying the name of the computer. Otherwise, you can assign localhost to this attribute. Here is an example

private void btnLoad_Click(object sender, System.EventArgs e)
{
MySqlConnection cnnVideos = new MySqlConnection(“Data Source=localhost;”);
}

The Database

If you have already created a database you want to connect to, you can specify it in your connection string. If you are not trying to connect to a particular database, you don’t need to specify one.

To specify the database you want to connect to, the connection string includes an attribute named Database or Initial Catalog. This attribute allows you to specify the name of the database you are connecting to, if any. If you are connecting to an existing database, assign its name to this attribute. If you are not connecting to a database, you can omit this attribute. Alternatively, you can assign nothing to this attribute. Here is an example:

MySqlConnection conDatabase = new MySqlConnection(“Address=localhost;Database=; “);

Another alternative is to assign an empty, single-quoted, string to this attribute. Here is an example:

MySqlConnection conDatabase = new MySqlConnection(“Network Address=localhost;Initial Catalog=”; “);

As mentioned above, the Database or Initial Catalog attribute is optional, especially if you are only connecting to the computer and not to a specific database.

Security

An important aspect of establishing a connection to a computer is security. Even if you are developing an application that would be used on a standalone computer, you must take care of this issue. The security referred to in this attribute has to do with the connection, not how to protect your database.

To support security, the connection string of the MySqlConnection class includes an attribute called Persist Security Info that can have a value of true, false, yes, no.

If you are establishing a trusted or simple connection that doesn’t need to be verified, you can assign a value of true. Here is an example:

private void btnLoad_Click(object sender, System.EventArgs e)
{
MySqlConnection cnnVideos = new MySqlConnection(
“Network Address=localhost;Initial Catalog=’Famille’;Persist Security Info=true;”);
}

If the connection exists already, to find it out, remember that you can can get the value of the MySqlConnection.ConnectionString property. If you had set the Persist Security Info attribute to true, the person getting this information may see the username and the password that were used to establish the connection. If you don’t want this information available, you should set this attribute to false or no. If you do this, when somebody inquires about the connection string, he or she would not get the username and the password.

The Username

If you are connecting to a MySQL server and you want to apply authentication, you can specific a username and a password. To specify the user name, use the User Id, the Uid, the User name, or the Username attribute and assign it a valid MySQL login username. Here is an example:

MySqlConnection conDatabase = new MySqlConnection(“Server=localhost;Persist Security Info=no;User ID=MammaMia”);

The Password

When using authentication during connection, after specifying (if you had specified) the username, you must also provide a password to complete the authentication. To specify the password, you can user either the PASSWORD or the PWD (remember that the attributes are not case-sensitive) attribute and assign it the exact password associated with the User Id, the Uid, the User name, or the Username attribute of the same connection string. Here is an example:

private void btnLoad_Click(object sender, System.EventArgs e)
{
MySqlConnection cnnVideos = new MySqlConnection(“Network Address=localhost;” +
“Initial Catalog=’Famille’;” +
“Persist Security Info=no;” +
“User Name=’root’;” +
“Password=’R0gerMiLl@'”);
}

Additional Attributes

There are various other attributes used in the connection string. They include Encrypt, Connection Timeout (or Connect Timeout), CharSet (or Character Set), Port, Protocol, Logging, Allow Batch, Shared Memory Name, Allow Zero Datetime, Old Syntax (or OldSyntax), Connection Lifetime, Max Pool Size, Min Pool Size, Pooling, and Pipe Name (or Pipe).

After creating the connection string, when the application executes, the compiler would “scan” the string to validate each key=value section. If it finds an unknown Key, an unknown value, or an invalid combination of key=value, it would throw an ArgumentException exception and the connection cannot be established.

Operations on a MySQL Server Database Connection

Opening a Connection

After creating a connection string, to apply it and actually establish the connection, you must call the MySqlConnection.Open(). Its syntax is:

public void Open();

As you can see, this method doesn’t take any argument. The MySqlConnection object that calls it is responsible to get the connection string ready. If the connection fails, the compiler would throw a MySqlException exception. If the connection string doesn’t contain a data source or server, the compiler would throw an InvalidOperationException exception.

Closing a Connection

After using a connection and getting the necessary information from it, you should terminate it. To close a connection, you can call the MySqlConnection.Close() method. Its syntax is:

public void Close();

This method is simply called to close the current connection. While you should avoid calling the Open() method more than once if a connection is already opened, you can call the Close() method more than once.

Advertisements

Comments off

Hoa cải nở ngút ngàn


Đến thăm nhiều miền quê ở Trung Quốc vào mùa xuân, du khách có thể nức lòng trước cảnh những cánh đồng hoa cải dầu vàng rực rỡ, trải dài ngút tầm mắt. Mời bạn chiêm ngưỡng cảnh đẹp hoa cải tại Hồ Bắc và Vân Nam. Ảnh trên Cri và Xinhua.

Hoa cải dầu đang nở rộ ở Hồ Bắc:

Vườn cải tại La Bình, tỉnh Vân Nam những ngày tháng 2:

Comments off

Google geocoding country codes


There may be a magic word that could make the geocoder understand a bare countrycode but I have not found it. So the lookup table system seems to be the only way to do that. Here are the codes:

AD : ANDORRA AE : UNITED ARAB EMIRATES AF : AFGHANISTAN AG : ANTIGUA AND BARBUDA AI : ANGUILLA AL : ALBANIA AM : ARMENIA AN : NETHERLANDS ANTILLES AO : ANGOLA AQ : ANTARCTICA AR : ARGENTINA AS : AMERICAN SAMOA AT : AUSTRIA AU : AUSTRALIA AW : ARUBA AZ : AZERBAIJAN BA : BOSNIA AND HERZEGOVINA BB : BARBADOS BD : BANGLADESH BE : BELGIUM BF : BURKINA FASO BG : BULGARIA BH : BAHRAIN BI : BURUNDI BJ : BENIN BM : BERMUDA BN : BRUNEI DARUSSALAM BO : BOLIVIA BR : BRAZIL BS : BAHAMAS BT : BHUTAN BV : BOUVET ISLAND BW : BOTSWANA BY : BELARUS BZ : BELIZE CA : CANADA CC : COCOS (KEELING) ISLANDS CD : CONGO, THE DEMOCRATIC REPUBLIC OF THE CF : CENTRAL AFRICAN REPUBLIC CG : CONGO CH : SWITZERLAND CI : CÔTE D’IVOIRE CK : COOK ISLANDS CL : CHILE CM : CAMEROON CN : CHINA CO : COLOMBIA CR : COSTA RICA CU : CUBA CV : CAPE VERDE CX : CHRISTMAS ISLAND CY : CYPRUS CZ : CZECH REPUBLIC DE : GERMANY DJ : DJIBOUTI DK : DENMARK DM : DOMINICA DO : DOMINICAN REPUBLIC DZ : ALGERIA EC : ECUADOR EE : ESTONIA EG : EGYPT EH : WESTERN SARARA ER : ERITREA ES : SPAIN ET : ETHIOPIA FI : FINLAND FJ : FIJI FK : FALKLAND ISLANDS (MALVINAS) FM : MICRONESIA, FEDERATED STATES OF FO : FAROE ISLANDS FR : FRANCE GA : GABON GB : UNITED KINGDOM GD : GRENADA GE : GEORGIA GF : FRENCH GUIANA GH : GHANA GI : GIBRALTAR GL : GREENLAND GM : GAMBIA GN : GUINEA GP : GUADELOUPE GQ : EQUATORIAL GUINEA GR : GREECE GS : SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS GT : GUATEMALA GU : GUAM GW : GUINEA-BISSAU GY : GUYANA HK : HONG KONG HM : HEARD ISLAND AND MCDONALD ISLANDS HN : HONDURAS HR : CROATIA HT : HAITI HU : HUNGARY ID : INDONESIA IE : IRELAND IL : ISRAEL IN : INDIA IO : BRITISH INDIAN OCEAN TERRITORY IQ : IRAQ IR : IRAN, ISLAMIC REPUBLIC OF IS : ICELAND IT : ITALY JM : JAMAICA JO : JORDAN JP : JAPAN KE : KENYA KG : KYRGYZSTAN KH : CAMBODIA KI : KIRIBATI KM : COMOROS KN : SAINT KITTS AND NEVIS KP : KOREA, DEMOCRATIC PEOPLE’S REPUBLIC OF KR : KOREA, REPUBLIC OF KW : KUWAIT KY : CAYMAN ISLANDS KZ : KAZAKHSTAN LA : LAO PEOPLE’S DEMOCRATIC REPUBLIC LB : LEBANON LC : SAINT LUCIA LI : LIECHTENSTEIN LK : SRI LANKA LR : LIBERIA LS : LESOTHO LT : LITHUANIA LU : LUXEMBOURG LV : LATVIA LY : LIBYAN ARAB JAMABIRIYA MA : MOROCCO MC : MONACO MD : MOLDOVA, REPUBLIC OF MG : MADAGASCAR MH : MARSHALL ISLANDS MK : MACEDONIA, THE FORMER YUGOSLAV REPU8LIC OF ML : MALI MM : MYANMAR MN : MONGOLIA MO : MACAU MP : NORTHERN MARIANA ISLANDS MQ : MARTINIQUE MR : MAURITANIA MS : MONTSERRAT MT : MALTA MU : MAURITIUS MV : MALDIVES MW : MALAWI MX : MEXICO MY : MALAYSIA MZ : MOZAMBIQUE NA : NAMIBIA NC : NEW CALEDONIA NE : NIGER NF : NORFOLK ISLAND NG : NIGERIA NI : NICARAGUA NL : NETHERLANDS NO : NORWAY NP : NEPAL NU : NIUE NZ : NEW ZEALAND OM : OMAN PA : PANAMA PE : PERU PF : FRENCH POLYNESIA PG : PAPUA NEW GUINEA PH : PHILIPPINES PK : PAKISTAN PL : POLAND PM : SAINT PIERRE AND MIQUELON PN : PITCAIRN PR : PUERTO RICO PT : PORTUGAL PW : PALAU PY : PARAGUAY QA : QATAR RE : RÉUNION RO : ROMANIA RU : RUSSIAN FEDERATION RW : RWANDA SA : SAUDI ARABIA SB : SOLOMON ISLANDS SC : SEYCHELLES SD : SUDAN SE : SWEDEN SG : SINGAPORE SH : SAINT HELENA SI : SLOVENIA SJ : SVALBARD AND JAN MAYEN SK : SLOVAKIA SL : SIERRA LEONE SM : SAN MARINO SN : SENEGAL SO : SOMALIA SR : SURINAME ST : SAO TOME AND PRINCIPE SV : EL SALVADOR SY : SYRIAN ARAB REPUBLIC SZ : SWAZILAND TC : TURKS AND CAICOS ISLANDS TD : CHAD TF : FRENCH SOUTHERN TERRITORIES TG : TOGO TH : THAILAND TJ : TAJIKISTAN TK : TOKELAU TM : TURKMENISTAN TN : TUNISIA TO : TONGA TP : EAST TIMOR TR : TURKEY TT : TRINIDAD AND TOBAGO TV : TUVALU TW : TAIWAN, PROVINCE OF CHINA TZ : TANZANIA, UNITED REPUBLIC OF UA : UKRAINE UG : UGANDA UM : UNITED STATES MINOR OUTLYING ISLANDS US : UNITED STATES UY : URUGUAY UZ : UZBEKISTAN VE : VENEZUELA VG : VIRGIN ISLANDS, BRITISH VI : VIRGIN ISLANDS, U.S. VN : VIET NAM VU : VANUATU WF : WALLIS AND FUTUNA WS : SAMOA YE : YEMEN YT : MAYOTTE YU : YUGOSLAVIA ZA : SOUTH AFRICA ZM : ZAMBIA ZW : ZIMBABWE

Comments off

Google Map API : Tutorial


Đoạn code đơn giản nhất để nhúng google maps vào site của chúng ta :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
  function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

</script>
</head>
<body onload="initialize()">
  <div id="map_canvas" style="width:100%; height:800px"></div>
</body>
</html>

Code basic nhìn chung cũng giống như phiên bản 2 , với các thông số như : zoom , center , MapTypeId .
Có 4 loại MapTypeID :
* MapTypeId.ROADMAP displays the default road map view
* MapTypeId.SATELLITE displays Google Earth satellite images
* MapTypeId.HYBRID displays a mixture of normal and satellite views
* MapTypeId.TERRAIN displays a physical map based on terrain information.

Example : http://code.google.com/apis/maps/documentation/v3/examples/map-simple.html

Comments off

Google Map API : Event


Event trong bản V3 tương tự như bản V2.
1 ) Chúng ta thử với bản code sau :

var map;
function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var myOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  
  google.maps.event.addListener(map, 'zoom_changed', function() {
    setTimeout(moveToDarwin, 3000);
  });
  
  var marker = new google.maps.Marker({
      position: myLatlng, 
      map: map,
      title:"Hello World!"
  });
  google.maps.event.addListener(marker, 'click', function() {
    map.setZoom(8);
  });
}
  
function moveToDarwin() {
  var darwin = new google.maps.LatLng(-12.461334, 130.841904);
  map.setCenter(darwin);
}

Code trên chỉ đơn giản là : khi click vào điểm marker trên bản đồ , thì sẽ zoom=8 , và sau đó 3 giây thì chuyển tới điểm darwin .

a) Add marker :

var marker = new google.maps.Marker({
      position: myLatlng, 
      map: map,
      title:"Hello World!"
  });

b) Bật sự kiện click thì zoom:

google.maps.event.addListener(marker, 'click', function() {
    map.setZoom(8);
  });

c) Bật sự kiện zoom_change :

google.maps.event.addListener(map, 'zoom_changed', function() {
    setTimeout(moveToDarwin, 3000);
  });

d) Hàm moveToDarwin :

function moveToDarwin() {
  var darwin = new google.maps.LatLng(-12.461334, 130.841904);
  map.setCenter(darwin);
}

2 ) Thử sự kiện click :

var map;
function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var myOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  
  google.maps.event.addListener(map, 'click', function(event) {
    placeMarker(event.latLng);
  });
}
  
function placeMarker(location) {
  var clickedLocation = new google.maps.LatLng(location);
  var marker = new google.maps.Marker({
      position: location, 
      map: map
  });

  map.setCenter(location);
}

Biến : event.latLng để ghi nhận giá trị click .

3 ) Code Info Window :

function attachSecretMessage(marker, number) {
  var message = ["This","is","the","secret","message"];
  var infowindow = new google.maps.InfoWindow(
      { content: message[number],
        size: new google.maps.Size(50,50)
      });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
}

4 ) Lấy properties từ map :
a ) map.getBounds()
b ) map.getCenter()
c ) map.getZoom()
d ) map.setCenter()
… và còn nhiều nữa ở đây :

http://code.google.com/apis/maps/documentation/v3/reference.html

Comments off

Google Map API : OverLays


1) Add marker vào map :

var marker = new google.maps.Marker({
      position: myLatlng, 
      map: map, 
      title:"Hello World!"
});

2) Add marker là ảnh :

var image = 'beachflag.png';
  var myLatLng = new google.maps.LatLng(-33.890542, 151.274856);
  var beachMarker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image
  });

3) Add Marker Complex (hay)

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(-33.9, 151.2),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
                                myOptions);

  setMarkers(map, beaches);
}

/**
 * Data for the markers consisting of a name, a LatLng and a zIndex for
 * the order in which these markers should display on top of each
 * other.
 */
var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

function setMarkers(map, locations) {
  // Add markers to the map

  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.

  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.
  var image = new google.maps.MarkerImage('images/beachflag.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(20, 32),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(37, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML <area> element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
  var shape = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });
  }
}


Giải thích : Đầu tiên ta gọi hàm setMarker :

setMarkers(map, beaches);

và truyền vào 2 tham số là map(bản đồ), và beaches(là 1 mảng các điểm ta muốn add Marker Complex).
Beaches:

var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

Hàm setMarker được đi như sau :
a)Đầu tiên tạo icon

 var image = new google.maps.MarkerImage('images/beachflag.png',new google.maps.Size(20, 32),new google.maps.Point(0,0),new google.maps.Point(0, 32));

new google.maps.Size(20, 32) : Dài * Rộng .
new google.maps.Point(0,0) : Tâm Icon .
new google.maps.Point(0, 32) : Phạm vi Icon .
b)Sau đó tạo bóng(Shadow):

var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',new google.maps.Size(37, 32),new google.maps.Point(0,0),new google.maps.Point(0, 32));

Các tham số cũng tương tự như tạo Icon .
c) Sau đó tạo Shape :

var shape = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };

d) Cuối cùng là add tất cả vào :

for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });
  }

Lưu ý : Vì location của chúng ta là 1 mảng nên dĩ nhiên beach[1],beach[2]… là các giá trị của mảng : beach[0]=’Bondi Beach’ , beach[1]=-33.890542, beach[2]=151.274856, beach[3]=4 .
Demo : http://code.google.com/intl/fr/apis/maps/documentation/v3/examples/icon-complex.html
4) Vẽ các polygon : Phần này không quan trọng lắm, có thể xem chi tiết tại :

http://code.google.com/intl/fr/apis/maps/documentation/v3/overlays.html

.
5) Info Window:
Đầu tiên ta tạo marker :

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title:"Uluru (Ayers Rock)"
});

Sau đó ta tạo sự kiện cho click vào marker :

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

Cuối cùng khai báo contentString:

<div id="content">'+
    '<div id="siteNotice">'+
    '</div>'+
    '<h1 id="firstHeading">Uluru</h1>'+
    '<div id="bodyContent">'+
    '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
    'sandstone rock formation in the southern part of the '+
    'Northern Territory, central Australia. It lies 335 km (208 mi) '+
    'south west of the nearest large town, Alice Springs; 450 km '+
    '(280 mi) by road. Kata Tjuta and Uluru are the two major '+
    'features of the Uluru - Kata Tjuta National Park. Uluru is '+
    'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
    'Aboriginal people of the area. It has many springs, waterholes, '+
    'rock caves and ancient paintings. Uluru is listed as a World '+
    'Heritage Site.</p>'+
    '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
    'http://en.wikipedia.org/w/index.php?title=Uluru</a> (last visited June 22, 2009).</p>'+
    '</div>'+
    '</div>

Comments off

Google Map API : Services


Geocoding là việc xử lý từ địa chỉ (VD : 1600 Amphitheatre Parkway, Mountain View, CA) tới number trong google maps(VD : latitude 37.423021 and longitude -122.083739) .
1) Code 1 geocode basic (từ địa chỉ leter sang địa chỉ number) như sau :

var geocoder;
  var map;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeAddress() {
    var address = document.getElementById("address").value;
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
              map: map, 
              position: results[0].geometry.location
          });
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
  }

<body onload="initialize()">
 <div id="map_canvas" style="width: 320px; height: 480px;"></div>
  <div>
    <input id="address" type="textbox" value="Sydney, NSW">
    <input type="button" value="Encode" onclick="codeAddress()">
  </div>
</body>

Giải thích :
a) Tạo form :

<div id="map_canvas" style="width: 320px; height: 480px;"></div>
  <div>
    <input id="address" type="textbox" value="Sydney, NSW">
    <input type="button" value="Encode" onclick="codeAddress()">
  </div>

b) Viết hàm Address , trong đó có các điều cần lưu ý như sau :
Đầu tiên lấy address (là tên):

var address = document.getElementById("address").value;

Sau đó gọi geocode:

geocoder.geocode({ 'address': address}, function(results, status) {
...});

Trong đó address là địa chỉ. Mở rộng thêm , ta có mảng geocode :

{
 address: string,
 latLng: LatLng,
 bounds: LatLngBounds,
 language: string,
 region: string,
}

. Các thông số lần lượt khai báo như vậy .
Và cuối cùng là hàm trỏ tới center điểm click và add marker vào :

map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
              map: map, 
              position: results[0].geometry.location
          });

Demo : http://code.google.com/intl/fr/apis/maps/documentation/v3/examples/geocoding-simple.html
2) Code 1 geocode basic (từ địa chỉ number sang địa chỉ letter) như sau :

var geocoder;
  var map;
  var infowindow = new google.maps.InfoWindow();
  var marker;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeLatLng() {
    var input = document.getElementById("latlng").value;
    var latlngStr = input.split(",",2);
    var lat = latlngStr[0];
    var lng = latlngStr[1];
    var latlng = new google.maps.LatLng(lat, lng);
    if (geocoder) {
      geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            map.setZoom(11);
            marker = new google.maps.Marker({
                position: latlng, 
                map: map
            }); 
            infowindow.setContent(results[1].formatted_address);
            infowindow.open(map, marker);
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }
  }

Giải thích :
Code trên chỉ khác code trước là :

var input = document.getElementById("latlng").value;
    var latlngStr = input.split(",",2);
    var lat = latlngStr[0];
    var lng = latlngStr[1];

Đầu tiên lấy giá trị từ id “latlng”, sau đó cắt giá trị đó ra thành 2 phần ,đưa vào mảng . Vd : Giá trị nhập vào là “2,4” thì mảng latlngStr={[0]=>2,[1]=>4} . Sau đó lat={0},lng={4} .
Sau đó , ta so sánh

{'latLng': latlng}

chứ không so sách

'address': address

như ở ví dụ 1.
Và 1 điểm nữa là : giá trị result trả về .
Ở ví dụ 1 , ta thấy result[0], còn ví dụ này, result[1], tại sao vậy ?
Sau khi google trỏ tới địa chỉ mà ta gõ vào , thì kết quả trả về là 1 mảng result gồm nhiều kết quả định dạng khác nhau . Và ta chỉ việc lọc lấy kết quả mình mong muốn trả về .
List full định dạng như sau (gồm 7 định dạng):

results[0].formatted_address: "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
results[1].formatted_address: "Williamsburg, NY, USA",
results[2].formatted_address: "New York 11211, USA",
results[3].formatted_address: "Kings, New York, USA",
results[4].formatted_address: "Brooklyn, New York, USA",
results[5].formatted_address: "New York, New York, USA",
results[6].formatted_address: "New York, USA",
results[7].formatted_address: "United States"

Vậy VD 1 ta lấy result[0] tức là giá trị trả về có đầy đủ các tham số .
Còn VD 2 ta lấy result[1] tức là giá trị trả về chỉ bao gồm 3 tham số .
Ngoài ra , result còn trả về nhiều giá trị hơn , chứ không chỉ là format_address :

results[]: {
 types[]: google.maps.GeocoderLocationType,
 formatted_address: String,
 address_components[]: {
   short_name: String,
   long_name: String,
   types[]: String
 },
 geometry: {
   location: LatLng,
   location_type: String
   viewport: LatLngBounds,
   bounds: LatLngBounds
 }
}

Các giá trị đó là :
+ types : là kiểu biểu trưng cho dạng trả về. VD : “Chicago” thì type là locality . Sau đây là list các types trả về :

* street_address indicates a precise street address.
* route indicates a named route (such as "US 101").
* intersection indicates a major intersection, usually of two major roads.
* political indicates a political entity. Usually, this type indicates a polygon of some civil administration.
* country indicates the national political entity, and is typically the highest order type returned by the Geocoder.
* administrative_area_level_1 indicates a first-order civil entity below the country level. Within the United States, these administrative levels are states. Not all nations exhibit these administrative levels.
* administrative_area_level_2 indicates a second-order civil entity below the country level. Within the United States, these administrative levels are counties. Not all nations exhibit these administrative levels.
* administrative_area_level_3 indicates a third-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.
* colloquial_area indicates a commonly-used alternative name for the entity.
* locality indicates an incorporated city or town political entity.
* sublocality indicates an first-order civil entity below a locality
* neighborhood indicates a named neighborhood
* premise indicates a named location, usually a building or collection of buildings with a common name
* subpremise indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a common name
* postal_code indicates a postal code as used to address postal mail within the country.
* natural_feature indicates a prominent natural feature.
* airport indicates an airport.
* park indicates a named park.
* post_box indicates a specific postal box.
* street_number indicates the precise street number.
* floor indicates the floor of a building address.
* room indicates the room of a building address.

+ formatted_address : Là địa chỉ trả về .
+ address_components : là chi nhỏ địa chỉ ra .
+ geometry[] : các tham số cần lấy ra.
.location : tâm điểm trả về … và các thông số khác .
3) Hướng(Directions) : Ta có thể tính toán Hướng bằng Object DirectionsService .
Ta tham khảo code sau

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var myOptions = {
    zoom:7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: chicago
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  directionsDisplay.setMap(map);
}
  
function calcRoute() {
  var start = document.getElementById("start").value;
  var end = document.getElementById("end").value;
  var request = {
    origin:start, 
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
    }
  });
}

<div>
<b>Start: </b>
<select id="start" onchange="calcRoute();">
  <option value="chicago, il">Chicago</option>
  <option value="st louis, mo">St Louis</option>
  <option value="joplin, mo">Joplin, MO</option>
  <option value="oklahoma city, ok">Oklahoma City</option>
  <option value="amarillo, tx">Amarillo</option>
  <option value="gallup, nm">Gallup, NM</option>
  <option value="flagstaff, az">Flagstaff, AZ</option>
  <option value="winona, az">Winona</option>
  <option value="kingman, az">Kingman</option>
  <option value="barstow, ca">Barstow</option>
  <option value="san bernardino, ca">San Bernardino</option>
  <option value="los angeles, ca">Los Angeles</option>
</select>
<b>End: </b>
<select id="end" onchange="calcRoute();">
  <option value="chicago, il">Chicago</option>
  <option value="st louis, mo">St Louis</option>
  <option value="joplin, mo">Joplin, MO</option>
  <option value="oklahoma city, ok">Oklahoma City</option>
  <option value="amarillo, tx">Amarillo</option>
  <option value="gallup, nm">Gallup, NM</option>
  <option value="flagstaff, az">Flagstaff, AZ</option>
  <option value="winona, az">Winona</option>
  <option value="kingman, az">Kingman</option>
  <option value="barstow, ca">Barstow</option>
  <option value="san bernardino, ca">San Bernardino</option>
  <option value="los angeles, ca">Los Angeles</option>
</select>
</div>

Giải thích : Code trên đầu tiên ta tạo select box để chọn giá trị, khi change thì gọi hàm calcRoute() và xử lý .
Để hiểu rõ code , đầu tiên ta phải hiểu :
a)Direction Request : 1 Direction cần những gì ? Nó là 1 mảng chứa

{
  origin: LatLng | String,
  destination: LatLng | String,
  travelMode: DirectionsTravelMode,
  unitSystem: DirectionsUnitSystem,
  waypoints[]: DirectionsWaypoint,
  provideTripAlternatives: Boolean,
  region: String
}

+origin: Điểm đầu.
+destination: Điểm cuối
+travelMode: Có 2 tham số là DirectionsTravelMode.DRIVING và DirectionsTravelMode.WALKING .
+unitSystem : Kết quả trả về là met hoặc kilomet : DirectionsUnitSystem.METRIC và DirectionsUnitSystem.IMPERIAL .
+waypoints : Các chặng dừng giữa đường đi .Xem chi tiết tại : Đây .

+provideTripAlternatives : Nếu set true, có thể có nhiều đường đi để tới điểm đích , dĩ nhiên , khi làm vậy thì thời gian xử lý bản đồ sẽ cao hơn .
Và đây là 1 điểm ví dụ :

{
  origin: "Chicago, IL",
  destination: "Los Angeles, CA",
  waypoints: [
    {
      location:"Joplin, MO", 
      stopover:false
    },{
      location:"Oklahoma City, OK",
      stopover:true
    }],
  provideTripAlternatives: false,
  travelMode: DirectionsTravelMode.DRIVING,
  unitSystem: DirectionsUnitSystem.IMPERIAL
}

b) Tiếp theo ta cần hiểu biến DirectionsService và DirectionsRenderer .
DirectionsService sẽ được khởi tạo , thông qua điểm Request trên mà ta đã tạo , sau đó nó return về DirectionsResult , sau đó DirectionsResult trả kết quả tới DirectionsRenderer .
Vầy để tạo DirectionsRenderer ta làm như sau :
# Tạo đối tượng DirectionsRenderer .
# Gọi method setMap() để đưa nào vào map.
# Gọi setDirections() để đưa DirectionsResult vào .
Vậy là ta có thể hiểu được đường đi của code rồi .
Demo : http://code.google.com/intl/fr/apis/maps/documentation/v3/examples/directions-simple.html
4) DirectionsRenderer không chỉ hiện ra đường đi, mà nó còn có thể hiện ra list danh sách các điểm mà nó đi ngang qua :
– Chỉ đơn giản thêm Panel hiện ra :

directionsDisplay.setPanel(document.getElementById("directionsPanel"));

– Và định nghĩa div có id là “directionsPanel”

<div id="directionsPanel" style="float:right;width:30%;height 100%"></div>

.
Demo : http://code.google.com/intl/fr/apis/maps/documentation/v3/examples/directions-panel.html
5) Và các direction phức tạp khác :
Demo 1 : http://code.google.com/intl/fr/apis/maps/documentation/v3/examples/directions-complex.html
Demo 2 : http://code.google.com/intl/fr/apis/maps/documentation/v3/examples/directions-waypoints.html

<sưu tầm>

Comments off