• Unfortunately, we have experienced significant hard drive damage that requires urgent maintenance and rebuilding. The forum will be a state of read only until we install our new drives and rebuild all the configurations needed. Please follow our Facebook page for updates, we will be back up shortly! (The forum could go offline at any given time due to the nature of the failed drives whilst awaiting the upgrades.) When you see an Incapsula error, you know we are in the process of migration.

[G. Map API] I finally did it..

Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
For a while now I've been struggling with the Google Map API. I think I finally understand it now. Or at least a little bit.

I managed to make a map for everyone who gives me an address in my SQL database. I'm using PHP, MySQL, CSV, XML, and mostly JavaScript.

At first, I couldn't figure out how to get the lat, lng varriables. I finally found out I could just send a link query to a CSV file on code.google.com/.../ .
So I parsed it the way I knew how, PHP. This made it easy for me to get the data from the SQL database, (street, city, zip, state), and turn it into varriables, send the query to google, get back the coords, split the coords, and FINALLY, put them in the right spot in the JavaScript thing I got from google.

After I got that all figured out, I gave every paid user a cheap map that couldn't do anything. I don't know much at all about javascript, but after looking at it for a few days, you get to understand it more.

I did some more research in the google documentation, and I found out how to add things like the zoom buttons, drag function, different views (road-map, satellite, hybrid), and many more. Now that I know how to do that, I just need a pin-needle to show where the building is. Oh heck, might as well make it clickable with a message bubble popup. Google teaches you how to do it all! My problem, is the lack of knowledge in JavaScript.

Now, I'm getting better. So I'm gonna keep experimenting.

Click to enlarge the map. (Thai food, anyone?)

The below posted code will not work. You need to get an API key and replace the word YOUR-KEY with your key.



display code:
PHP:
<?php
//If there is a city & a street, include "View Map" Link.
  if($listing[city] != "" && $listing[street] != "") {
  $street=str_replace(" ", "+",$listing[street]);
  $street=str_replace(" ", "+",$street);
$street=str_replace("#", "Suite.",$street);
$company=str_replace("'","'",$listing['company']);
$city=str_replace(" "," ",$listing['city']);
  if(strlen($_GET['mapExpand'])>1 && $_GET['subcat']==$subcat && $_GET['entryID']==$listing['entryID']) {
  print "<p><small><a href='http://www.avsbest.com/categories/directory.php?category=$category#$subcat' target='_self'>Minimize Map</a></small>";
  $link="/includes/paid/map.php?street=". $street ."&city=". $city ."&state=CA&company=".$company."";
  print "<iframe src='$link' width='300' height='300' frameborder='0' scrolling='no' > </iframe>";
  } else {
  print "<p><small><a href='directory.php?category=$category&mapExpand=True&subcat=$subcat&entryID=$listing[entryID]#$subcat' target='_self'>Expand Map</a></small>";
  }
  echo '</p>';
  }
?>
Before I do this, I get the data from the database. This is in the while statement.


This is the map page:
PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  	<?php
$company=stripslashes($_GET['company']);
$street=$_GET['street'];
$city=$_GET['city'];
$state=$_GET['state'];
$zip=$_GET['zip'];
// THIS IS THE MAP CODE IF YOU WANT TO LINK TO THIS PAGE
$street=str_replace(" ", "+",$street);
$street=str_replace("%20", "+",$street);
$street=str_replace(" ", "+",$street);

$streetDisplay=str_replace("+", " ",$street);

list($street, $suite)=split("Suite.",$street);



?>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Map of <?=$company?></title>
	


<?php
$coords="http://maps.google.com/maps/geo?q=+$street,+$city,+$state&output=csv&key=YOUR-KEY";

#reads the file data.csv
$data=file_get_contents($coords);

#splits data into lat, lng
list($HTTP, $accuracy, $lat, $lng)=split(",",$data);
?>
	
    <script src="http://maps.google.com/maps?file=api&v=2.x&key=YOUR-KEY"
      type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[

    var iconBlue = new GIcon(); 
    iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
    iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconBlue.iconSize = new GSize(16, 24);
    iconBlue.shadowSize = new GSize(18, 24);
    iconBlue.iconAnchor = new GPoint(6, 20);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);

    var iconRed = new GIcon(); 
    iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
    iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconRed.iconSize = new GSize(16, 24);
    iconRed.shadowSize = new GSize(18, 24);
    iconRed.iconAnchor = new GPoint(6, 20);
    iconRed.infoWindowAnchor = new GPoint(5, 1);

    var customIcons = [];
    customIcons["restaurant"] = iconBlue;
    customIcons["bar"] = iconRed;
    var markerGroups = { "restaurant": [], "bar": []};

    function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(<?=$lat?>, <?=$lng?>), 13);

        GDownloadUrl("xml_convert.php?street=<?=$street?>&name=<?=$company?>&city=<?=$city?>&state=CA&lat=<?=$lat?>&lng=<?=$lng?>&company=<?=$company?>", function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) {
            var name = markers[i].getAttribute("name");
            var address = markers[i].getAttribute("address");
            var type = markers[i].getAttribute("type");
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
            var marker = createMarker(point, name, address, type);
            map.addOverlay(marker);
          }
        });
      }
    }

    function createMarker(point, name, address, type) {
      var marker = new GMarker(point, customIcons[type]);
      markerGroups[type].push(marker);
      var html = "<b>" + name + "</b> <br/>" + address;
      GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
      });
      return marker;
    }
    function toggleGroup(type) {
      for (var i = 0; i < markerGroups[type].length; i++) {
        var marker = markerGroups[type][i];
        if (marker.isHidden()) {
          marker.show();
        } else {
          marker.hide();
        }
      } 
    }
	
	

    //]]>
  </script>
  </head>

  <body style="font-family:Arial, sans serif" onload="load()" onunload="GUnload()">
  <div id="sidebar" style="float:top; width: 280px; border: 1px solid black">
   <input type="checkbox" id="restaurantCheckbox" onclick="toggleGroup('restaurant')" CHECKED />  
   Toggle <?=$company?> Pin
    </div>
    <div id="map" style="float:left; width: 280px; height: 250px; border: 1px solid black"></div>
    
  </body>
</html>
This gets the queries from the link/button and turns them into google javascript readable texts, and submits it to google to get the coords.
Then it does all that, and makes the map. It first gets the data from an XML file.

(xml_convert.php)
PHP:
<?php
$street=$_GET['street'];
$city=$_GET['city'];
$state=$_GET['state'];
$zip=$_GET['zip'];
$company=stripslashes($_GET['company']);

$street=str_replace(" ", "+",$street);
$street=str_replace("%20", "+",$street);
$street=str_replace(" ", "+",$street);

$streetDisplay=str_replace("+", " ",$street);

list($street, $suite)=split("Suite.",$street);

echo("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n");
echo("<markers>\n");
echo("<marker name=\"". $company ."\" address=\"". $streetDisplay ."\" lat=\"". $lat ."\" lng=\"". $lng ."\" type=\"restaurant\" />\n");
echo('</markers>');

?>


TaDa, this code can create a map for over 200 different locations. (in my case) The map doesn't display until the user clicks to unfold it. Once they do, they can minimize it again. It was not easy to find out how to turn an address into coordinate variables. Doing it without dynamic stuff is easy, but to me, this is hard unless you find the place with the right info.

But my database is all dumb and I need to redo it... I have it so that if an admin creates a category, it makes 5 new tables in the databse. (1 for every sub-cat.) I should've made them all in one table, and added the category/subcategory name in a field on every listing.. But I didn't, so now I have to make an engine to change it, or live with it.. (Engine coming soon.)
 
Last edited:
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
Nice 1 anyway, still struggling to get it work.

Yeah.. I don't know why I released this. I was just happy I got it working. Actually, you'd really have to dissect the code to get it to work..

All of the links are to avsbest.com.. And the database is all messy and doesn't match any standards I have today..

I'll edit my original post and try to make it appeal to everyone.
 
Custom Title Activated
Loyal Member
Joined
Jun 28, 2007
Messages
2,986
Reaction score
3
I used to post personal records here as well, but people often have no idea what you're talking about or what use it has, so I stopped with that :). Nice work though ;-)
 
Back
Top