Jump to content

google maps, loop through and add marker for each


jarv

Recommended Posts

Hi,

 

I currently have a google map which shows a marker where the postcode is for a certain pub (converts postcodes to coords lat/long)

I would like to loop through all my pubs in my database as place a marker for each on one map, I am uncertain of how to loop through and show each marker for each postcode either PHP or JavaScript.

 

here is my code for a single pub / postcode:

 

<!doctype html>
<?php 
include "../config.php";
$loggedIn = (isset($_COOKIE['loggedin']) && $_COOKIE['loggedin'] == 'true')?true:false;

$PUBID = intval($_REQUEST['PUBID']);
$PUB = mysql_query("SELECT * FROM pubs WHERE PUBID = '".$PUBID."'");
$pubdetails = mysql_fetch_array($PUB);
?>
<html>
    <head>
        <meta charset="UTF-8" />
        <title><?php echo $pubdetails['rsPubName']; ?>, <?php echo $pubdetails['rsTown']; ?>, <?php echo $pubdetails['rsCounty']; ?></title>
        <style type="text/css" media="screen">@import "jqtouch/jqtouch.min.css";</style>
        <style type="text/css" media="screen">@import "themes/jqt/theme.min.css";</style>
        <script src="jqtouch/jquery.1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="jqtouch/jqtouch.min.js" type="application/x-javascript" charset="utf-8"></script>
        <script src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAAM17e4xGXwO4sBd_QYtRiSRQXB4T7UHWaz4zUQgLx9muJZW0c3hS8jRMJg733CHqOihn7BVfhZTkLiA" type="text/javascript"></script>
		<script type="text/javascript">

    function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP 
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
  }


    </script>

        <script type="text/javascript" charset="utf-8">
            var jQT = new $.jQTouch({
                icon: 'jqtouch.png',
                addGlossToIcon: false,
                startupScreen: 'jqt_startup.png',
                statusBar: 'black',
                preloadImages: [
                    'themes/jqt/img/back_button.png',
                    'themes/jqt/img/back_button_clicked.png',
                    'themes/jqt/img/button_clicked.png',
                    'themes/jqt/img/grayButton.png',
                    'themes/jqt/img/whiteButton.png',
                    'themes/jqt/img/loading.gif'
                    ]
            });
        </script>
    </head>
    <body onLoad="ukPostcodeTest(); return false">
 	<!-- TOWNS -->
	<div id="pub" class="current">
            <div class="toolbar">
                <h1>View Pub</h1>
                <a class="back" href="index.php" rel="external">Home</a>
            </div>
			<h2><?php echo $pubdetails['rsPubName']; ?></h2>
            	<?php echo $pubdetails['rsAddress']; ?><br /> 
				<?php echo $pubdetails['rsTown']; ?><br />
				<?php echo $pubdetails['rsCounty']; ?><br />
				<?php echo $pubdetails['rsPostCode']; ?><br />
				<?php echo $pubdetails['Region']; ?><br />
				<?php echo $pubdetails['rsTel']; ?><br />
				<?php echo '<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.mypubspace.com/pub_info.php?PUBID='.$pubdetails['PUBID'].'&layout=box_count&show_faces=true&width=450&action=like&colorscheme=light&height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:60px; height:65px; float:right;" allowTransparency="true"></iframe>';?>


    <div id="map" style="width: 250px; height: 250px"></div>
  
    <form name="mapform" onsubmit="ukPostcodeTest(); return false" action="#">
	<input id="search" type="hidden" value="<?php echo $pubdetails["rsPostCode"]; ?>" />
    </form>
    
    <div id="message"></div>

    <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
      However, it seems JavaScript is either disabled or not supported by your browser. 
      To view Google Maps, enable JavaScript by changing your browser options, and then 
      try again.
    </noscript>

    <script type="text/javascript">
    //<![CDATA[
    
    if (GBrowserIsCompatible()) { 

      var map = new GMap(document.getElementById("map"));
      
	map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(51.520593197675446,-0.19775390625),16);
      
      // ====== Is the search string a UK Postcode ======
      function ukPostcodeTest() {
        var search = document.getElementById("search").value;
        // take a copy and convert to upper case
        var s = search.toUpperCase();
        // Replace punctuation and whitepsace by a single space
        s = s.replace(/\W+/g, " ");
        // Remove and trailing leading spaces
        s = s.replace(/^ /, "");
        s = s.replace(/ $/, "");
        // Perform the check
        var match = s.match(/^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$/);
        if (!match) {
          // Its not a UK Postcode, so perform a standard GClientGeocoder call on the original search string
          showAddress(search);
        } else {
          // It is a UK Postcode, so call GDirections on the reformatted search string 
          showPostcode(s);
        }
      }


      
      
      // ====== Code for handling search strings that are not UK Postcodes =======
      // ====== Use the GClientGeocoder in the normal way ======
      
      // ====== Create a Client Geocoder ======
      var geo = new GClientGeocoder(); 

      // ====== Array for decoding the failure codes ======
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      
      // ====== Geocoding ======
      function showAddress(search) {
        // ====== Perform the Geocoding ======        
        geo.getLocations(search, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // How many resuts were found
              document.getElementById("message").innerHTML = "Found " +result.Placemark.length +" results";
              // Loop through the results, placing markers
              for (var i=0; i<result.Placemark.length; i++) {
                var p = result.Placemark[i].Point.coordinates;
                var marker = new GMarker(new GLatLng(p[1],p[0]));
                document.getElementById("message").innerHTML += "<br>"+(i+1)+": "+ result.Placemark[i].address + marker.getPoint();
                map.addOverlay(marker);
              }
              // centre the map on the first result
              var p = result.Placemark[0].Point.coordinates;
              map.setCenter(new GLatLng(p[1],p[0]),14);
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              alert('Could not find "'+search+ '" ' + reason);
            }
          }
        );
      }




      // ====== Create a Client Geocoder ======
      var gdir = new GDirections(null); 
      
      // ====== Using GDirections to process a UK postcode ======
      function showPostcode(search) {
        // Call GDirections
        gdir.loadFromWaypoints([search,search],{getPolyline:true});
        // Wait for the reply to come back
        GEvent.addListener(gdir,"load", function() {
          var poly = gdir.getPolyline();
          var point = poly.getVertex(0);
          //document.getElementById("message").innerHTML = "Found a UK Postcode";
          // Process the result
          var marker = new GMarker(point);
          //document.getElementById("message").innerHTML += "<br>" + search + " = " + point.toUrlValue(5);
          map.addOverlay(marker);          
          // centre the map on the result
          map.setCenter(point,16);
        });
      }
    }


    
    // display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

    // This Javascript is based on code provided by the
    // Community Church Javascript Team
    // http://www.bisphamchurch.org.uk/   
    // http://econym.org.uk/gmap/

    //]]>
    </script>


        </div>
    </body>
</html>

Link to comment
Share on other sites

Get all of them into an array in PHP.  At the location where you are creating the hub in Javascript, loop through the PHP array and redo the same thing for each one of the items in the PHP array. This should dynamically add each and every one of the markers.

 

Alternatively you can pass the PHP array into a JS array and then loop through it that way.  Either way is do-able.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.