Blog - Single Post

OnClick Dynamic Google Maps in Website

  • Friday, January 6, 2012
  • by hbopuri

GoogleMap.js will hold the logic for generating the map

var ad1 = $("#ad1").val();
var ad2 = $("#ad2").val();
var address1 = ad1;
var address2 = ad2;
//var lat = $("#lat").val();
//var lng = $("#lng").val();
var map;
var map2;
var gdir;
var gdir2;
var geocoder = null;
var geocoder2 = null;
var addressMarker;
var addressMarker2;


function initialize() {
if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    gdir = new GDirections(map, document.getElementById("directions"));
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);

    setDirections(address2, address1, "en_US");
    // setDirections("San Francisco", "Mountain View", "en_US");
}
}

function setDirections(fromAddress, toAddress, locale) {
gdir.load("from: " + fromAddress + " to: " + toAddress,
            { "locale": locale });
}

And my screen, I have implemented this in ASP.Ne MVC 3.0 Razor view I am sure you can change it to any screen as it have no much modification for any platform. Notice i have a API Which you will have to alter based on your domain. You can Get Google Map API here

<script src="http://maps.google.com/maps?file=api&v=2&sensor=true_or_false&key=ABQIAAAAOdhD1B3BVBtgDtcx-d52URS1RRrijDm1gy4LClE7B_C-myLe1RRtDZ0LHqXIq8q0z4mVVysLOLUxtA"></script>
 
 
@Html.Raw("<h1>"+PharmacyLocation+"</h1>")
@Html.Hidden("Adrs1", PharmacyLocation, new { id = "ad1" })
@Html.Hidden("Adrs2", DistanceFrom, new { id = "ad2" })
@Html.Hidden("lat", lt, new { id = "lat" })
@Html.Hidden("lng", lg, new { id = "lng" })
 
<style type="text/css">
  body {
    font-family: Verdana, Arial, sans serif;
    font-size: 11px;
    margin: 2px;
  }
  table.directions th {
background-color:#EEEEEE;
  }
 
  img {
    color: #000000;
  }
  .directions
  {
  }
  .directions td
  {
      width:300px;
  }
 #directions
 {
  width: 300px; height: auto;
  float: left;
 
 }
 #map_canvas{ 
  width: 300px; height: 400px;
  float:right;
  margin-top: 16px;
 }
</style>
<script src="../../Scripts/GoogleMap.js" type="text/javascript"></script>
<script>
  $(document).ready(function () {
     initialize()
 });
 
 </script>
<table class="directions">
<tr><th>Directions</th><th>Map</th></tr>
 
<tr>
<td valign="top"><div id="directions"></div></td>
<td valign="top"><div id="map_canvas"></div></td>
 
</tr>
</table>
<script>
    $("#map_canvas").attr("style", "position: absolute; background-color: rgb(229, 227, 223); padding-top:25px;");
</script>