indexu.com

developer blog

Adding dynamic gmap with navigation and zooming

google map with navigation

As many of you request how to replace the static gmap image with dynamic gmap which allow navigation and zooming, I made some test how to do this for the easiest way.

Ok. This is the easiest way. We only need to change the template files. Actually only 2 files.

Edit header.html, usually we use

but now we need to add onload call to js to load gmap only when detail page is accessed.

<%php%>
global $page_identifier;
 
if ($page_identifier=='detail.php') {
  print '<body onload="initialize()" onunload="GUnload()">';
}
else {
  print "<body>";
}
<%/php%>

Edit detail_link.html, add the div container to show the map, it must have id gmapnav_canvas.

<h3>Location Map</h3>
<div id="gmapnav_canvas" style="width: 640px; height: 400px;text-align:center;margin: 20px;"></div>

Next, the last step is to construct the js code for google map. Edit detail_link.html, you can put the code at the of this file.

<%php%>
 
  $api_key = "";
 
  global $dbConn;
  $query = "select * from idx_link where link_id = '{$_REQUEST['linkid']}' limit 1";
  $result = $dbConn->Execute($query);
 
  $address  = $result->Fields("address");
  $city  = $result->Fields("city");
  $zip  = $result->Fields("zip");
  $state  = $result->Fields("state");
  $country  = $result->Fields("country");
 
  $loc = urlencode("$address, $city, $state, $zip, $country");
 
  $api_req = 'http://maps.google.com/maps/geo?q='.$loc.'&key='.$api_key.'&sensor=false&output=csv';
 
  $api_result = file_get_contents($api_req);
  $arr = explode(',',$api_result);
 
  if ($arr[0]=='200') {
    $latlng = $arr[2].','.$arr[3];
 
    $gmap_js = "
    <script src=\"http://maps.google.com/maps?file=api&amp;v=2&amp;key={$api_key}\" type=\"text/javascript\"></script>
    <script type=\"text/javascript\">
    function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById(\"gmapnav_canvas\"));
        map.setCenter(new GLatLng({$latlng}), 10);
 
        var latlng = new GLatLng({$latlng});
        map.addOverlay(new GMarker(latlng));
 
        map.addControl(new GSmallMapControl());
      }
    }
   </script>
    ";
  }
 
  print $gmap_js;
<%/php%>