via8321 via8321 - 5 months ago 95
PHP Question

Passing XML to Javascript to show markers in Google map

I'm a newbie to php and I'm trying to create a Google map based on this tutorial
https://developers.google.com/maps/articles/phpsqlajax_v3 with a little twist. I've put up a search box and managed to output an XML based on the query.

I'm having a hard time passing the XML data from search.php to make markers in Google maps

here's my code

for the form

<form name="form1" method="POST" action="search.php">
<input type="text" name="search" size="20"/>
<input type="button" onClick="searchLocations()" value="Search"/>
</form>


For the search.php

<?php
include("config.php");

function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}

if(empty($_POST['search'])) {
header("Location:map.html");

}

$query = " SELECT * FROM markers WHERE name LIKE '%".$_POST['search']."%' OR address LIKE '%".$_POST['search']."%' ";
$result = mysql_query($query);

if (!$result) {
die("Invalid query: " . mysql_error());
}

header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}

// End XML file
echo '</markers>';

?>


For the javascript

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[

var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};

function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(14.479, 121.020),
zoom: 14,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;

// Change this depending on the name of your PHP file
downloadUrl("search.php", function(data) {
var xml = data.responseXML;
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 google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}

function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}

function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;

request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};

request.open('GET', url, true);
request.send(null);
}

function doNothing() {}

//]]>
</script>

Answer

html

<!DOCTYPE html >
<head>
  <title</title>
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
  <script type="text/javascript">
    //<![CDATA[
    var map = null;

    var customIcons = {
      restaurant: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
      },
      bar: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
      }
    };

    function load() {
      map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(47.6145, -122.3418),
        zoom: 13,
        mapTypeId: 'roadmap'
      });
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    function searchLocations(){
      var infoWindow = new google.maps.InfoWindow;
      var search_term = document.getElementById('search-term').value;
      jQuery.ajax({
        dataType :'xml', 
        type: 'GET',
        url : 'search.php?search_term='+search_term, 
        success:function(data){
          var markers = data.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 google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
            var html = "<b>" + name + "</b> <br/>" + address;
            var icon = customIcons[type] || {};
            var marker = new google.maps.Marker({
              map: map,
              position: point,
              icon: icon.icon
            });
            bindInfoWindow(marker, map, infoWindow, html);
          }
        }});
      return false;
    }
    //]]>
  </script>
</head>
<body onload="load()">
 <p>
  <form id="search-form" method="post" action="search.php"> 
   <input type="text" name="search" size="20" id="search-term"/>
   <input type="button" value="Search" onclick="searchLocations();" />
 </form>
</p>
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>

php

<?php
include("config.php");

function xml_entities($value) {
    return strtr(
        $value, 
        array(
            "<" => "&lt;",
            ">" => "&gt;",
            '"' => "&quot;",
            "'" => "&apos;",
            "&" => "&amp;",
            )
        );
}

if(isset($_REQUEST['search_term'])){
    $search_term = mysql_real_escape_string(trim($_REQUEST['search_term']));

    if($result = mysql_query("SELECT * FROM markers WHERE name LIKE '%{$search_term}%' OR address LIKE '%{$search_term}%'")){

        $markers = array();

        while ($row = @mysql_fetch_assoc($result)){
            extract($row);
            $markers[] = "<marker name='".xml_entities($name)."' address='".xml_entities($address)."' lat='{$lat}' lng='{$lng}' type='{$type}' />";
        }

        if(count($markers)){
            header("Content-type: text/xml");
            echo '<markers>'.implode('', $markers).'</markers>';
        }
    }
} 
?>