Monday, October 22, 2012

Google MAPS With JQuery


Implementing Google maps with with jQuery is quite easy once you know it. In this tip I am going to demonstrate how it can be done.

The prerequisites of the plugin are jQuery and google maps. You will need to obtain your own Google API Key


<html<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Google MAPS in jQuery</title>

<style type="text/css" media="screen">
  #map { float:left; width:500px; height:500px; }
  #list { float:left; width:200px; background:#eee; list-style:none; padding:0; }
  #list li { padding:10px; }
  #list li:hover { background:#555; color:#fff; cursor:pointer; cursor:hand; }
  #message { position:absolute; padding:10px; background:#555; color:#fffwidth:75px; }
</style>


<style media="screen"type="text/css">#map { width:500px; height:500px; }</style>
<script type="text/javascript" src="http://www.google.com/jsapi?key=YOUR API KEY"></script>

<script type="text/javascript"charset="utf-8">
  google.load("maps","2.x");
  google.load("jquery","1.3.1");
</script>

</head>

<body>
  <div id="map"></div>
  <ul id="list"></ul>
  <div id="message"style="display:none;">Hi vicky</div>
  <script type="text/javascript">
  $(document).ready(function(){
    var divMap=document.getElementById("map"); 
    var map = new GMap2(divMap);
    var chennai = new GLatLng(13.060422,80.249583);
    map.setCenter(chennai,8);
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();
    var markers = [];
    for (var i = 0; i<10; i++) {
      var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
      southWest.lng() + lngSpan * Math.random());
      marker = new GMarker(point);
      map.addOverlay(marker);
      markers[i] = marker;
    }
    $(markers).each(function(i,marker){
      GEvent.addListener(marker,"click", function(){
      map.panTo(marker.getLatLng());
    });
  });
  $("<li/>").html("Point"+i).click(function(){
    map.panTo(marker.getLatLng());
  }).appendTo("#list");
  $("#message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));
});

function displayPoint(marker,index){
  $("#message").hide();
  var moveEnd = GEvent.addListener(map,"moveend", function(){
  var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
  $("#message").fadeIn().css({ top:markerOffset.y, left:markerOffset.x });
    GEvent.removeListener(moveEnd);
  });
  map.panTo(marker.getLatLng());
}
</script>
</body>
</html>

No comments:

Post a Comment