Wednesday, December 8, 2010

Google map integration website

For a business website, map is surely necessary. With Google Map, you can easily integrate a map to your website.

Today, I am going to show you how do it with jQuery and Google Map API. See PantipShop's contact page  for an example.



First, you need to know latitude and longitude of your location by using a GPS locator. You can also get the values from Google Map by right-clicking at the location you want to get the values and choose "What's here".

Then let us start with html code.

1) In the <head> section, load Google Map API in the language you preferred (en = English, th = Thai, etc. )

<script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false&language=en'></script>

2) follow by a jQuery script that will setup/ initialize the map


<script type='text/javascript'>
$(function() {
   // define latitude and longitude
   var myLatlng = new google.maps.LatLng(13.732251,100.522158);


   // define zoom value and type of map
   var myOptions = {
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.HYBRID
   }


   // make a new map in an element with "map_canvas" id
   var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);


   // mark my location
   var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'My company'
   });


   // click at the marker will pan the map the that location

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


   // double click at the marker will adjust the zoom value, also pan to that location
   google.maps.event.addListener(marker, 'dblclick', function() {
      map.setZoom(18);
      map.panTo(marker.getPosition());
   })

});
</script>


3) in <body> section, where you want to show a map, put an empty <div> with id "map_canvas" as initialized in the script above.

<div id='map_canvas'></div>

4) That is it !

For advance usages, see Google Map API.

No comments:

Post a Comment