Thursday 17 July 2014

Update google map location on click with jquery

Google maps can provide you directions, interactive maps, and satellite/aerial imagery of many countries. Maps can also search by keyword such as type of business.In this blog post, am sharing with you the code snippet which can help you to display google maps inside html DIV. I will also create multiple location links with location names, and on click of link, it will update the DIV with location in map.

here we load jQuery and google maps library from CDN.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"> </script>
<script src ="http://maps.googleapis.com/maps/api/js?sensor=false&extension=.js"> </script>

We first create HTML like below code and we assign "div"  with id "googleMap" as below.

<h1>Jquery for Multiple Click Map</h1>
<div id="googleMap" style="width:500px;height:380px;"></div>

Three anchor tags with unique id. so that we can update map location inside HTMl div, when user click's on any link.

<a id="miami" href="#">Miami Link</a>
<a id="shaven" href="#">South Haven Link</a>
<a id="troy" href="#">Troy Link</a>

Here is the JAVASCRIPT that will do the job for you.

<script type="text/javascript">
function map1()
{
var mapTroy = {
  center:new google.maps.LatLng(42.5803,-83.1431),
  zoom:10,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };
var map=new google.maps.Map(document.getElementById("googleMap"), mapTroy);
}



function map2()
{
  var mapMiami = {
  center:new google.maps.LatLng(25.7877,-80.2241),
  zoom:10,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("googleMap"), mapMiami);
}


function map3()
{
  var mapSouthHaven = {
  center:new google.maps.LatLng(42.4031,-86.2736),
  zoom:10,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("googleMap"), mapSouthHaven);
}

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



$(document).ready(function(){
    $('#miami').click(function() {        
      map2();
    });
   
    $('#shaven').click(function() {
     map3();
    });
    
    $('#troy').click(function() {
     map1();
    });
}); 

</script>

DEMO : http://jsfiddle.net/zP746/