2

我正在尝试构建一个简单的网络“应用程序”,在其中我将有一个地图(使用谷歌地图 api)和它下面的一些链接作为“过滤器”。我想按类型(即:酒吧或餐厅)过滤数据。

基本上,map.html 页面使用 javascript 来获取由 PHP 脚本生成的 XML。

这是以下代码:

地图.hmtl:

<!doctype html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyASO80RjNn2d_Jjy9vdNHA5E3tfmALkWXw&sensor=false"></script>
    <script type="text/javascript">

        //<![CDATA[

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

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

            // Change this depending on the name of your PHP file
            downloadUrl("genxml3.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 + "<br />" + type;
                    var icon = customIcons[type] || {};
                    var marker = new google.maps.Marker({
                        map: map,
                        position: point,
                        icon: icon.icon,
                        shadow: icon.shadow
                    });
                    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>
</head>
<body onload="load()">
    <div id="map" style="width: 900px; height: 750px;"></div>
    <ul>
        <a href="#">Restaurant</a>
    </ul>
</body>
</html>

genxml3.php:

<?php  

require("dbinfo.php"); 

// Start XML file, create parent node

$dom = new DOMDocument("1.0");
$node = $dom->createElement("map");
$parnode = $dom->appendChild($node); 

// Opens a connection to a MySQL server

$connection=mysql_connect('localhost', $username, $password);
if (!$connection) {  die('Not connected : ' . mysql_error());} 

// Set the active MySQL database

$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
    die ('Can\'t use db : ' . mysql_error());
} 

// Select all the rows in the markers table
// Checks for the 'GET' variable, if there isn't, run normal XML script,
// if there is, get the restriction/filter and query from the database 
// with the filter

if (!empty($_GET)) {    
    $filter = $_GET['f'];
    $query = "SELECT * FROM markers WHERE type = '$filter'";
} else {
    $query = "SELECT * FROM markers WHERE 1";
}

$result = mysql_query($query);
if (!$result) {  
    die('Invalid query: ' . mysql_error());
}

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

// Iterate through the rows, adding XML nodes for each

while ($row = mysql_fetch_assoc($result)){  
  // ADD TO XML DOCUMENT NODE  
  $node = $dom->createElement("marker");  
  $newnode = $parnode->appendChild($node);   
  $newnode->setAttribute("name",$row['name']);
  $newnode->setAttribute("address", $row['address']);  
  $newnode->setAttribute("lat", $row['lat']);  
  $newnode->setAttribute("lng", $row['lng']);   
  $newnode->setAttribute("type", $row['type']);
} 

echo $dom->saveXML();

?>

PHP 脚本生成以下 XML 代码:

<map> 
    <marker name="Pan Africa Market changed" address="1521 1st Ave, Seattle, WA"     lat="47.6089" lng="-122.34" type="restaurant"/> 
    <marker name="Buddha Thai & Bar" address="2222 2nd Ave, Seattle, WA" lat="47.6136" lng="-122.344" type="bar"/> 
    <marker name="The Melting Pot" address="14 Mercer St, Seattle, WA" lat="47.6246" lng="-122.356" type="restaurant"/> 
    <marker name="Ipanema Grill" address="1225 1st Ave, Seattle, WA" lat="47.6064" lng="-122.338" type="restaurant"/> 
    <marker name="Sake House" address="2230 1st Ave, Seattle, WA" lat="47.6128" lng="-122.346" type="bar"/> 
    <marker name="Crab Pot" address="1301 Alaskan Way, Seattle, WA" lat="47.606" lng="-122.34" type="restaurant"/> 
    <marker name="Mama's Mexican Kitchen" address="2234 2nd Ave, Seattle, WA" lat="47.614" lng="-122.345" type="bar"/> 
    <marker name="Wingdome" address="1416 E Olive Way, Seattle, WA" lat="47.6172" lng="-122.327" type="bar"/> 
    <marker name="Piroshky Piroshky" address="1908 Pike pl, Seattle, WA" lat="47.6101" lng="-122.343" type="restaurant"/> 
</map>

当我在导航栏中强制“获取”变量时(即:genxml3.php?f=restaurant),输出以下 XML 代码:

<map>    
    <marker name="Pan Africa Market changed" address="1521 1st Ave, Seattle, WA" lat="47.6089" lng="-122.34" type="restaurant"/>
    <marker name="The Melting Pot" address="14 Mercer St, Seattle, WA" lat="47.6246" lng="-122.356" type="restaurant"/>
    <marker name="Ipanema Grill" address="1225 1st Ave, Seattle, WA" lat="47.6064" lng="-122.338" type="restaurant"/>
    <marker name="Crab Pot" address="1301 Alaskan Way, Seattle, WA" lat="47.606" lng="-122.34" type="restaurant"/>
    <marker name="Piroshky Piroshky" address="1908 Pike pl, Seattle, WA" lat="47.6101" lng="-122.343" type="restaurant"/>    
</map>

所以我知道 PHP 脚本中的逻辑是有效的,因为它过滤了所需的代码。因此,如果我输入“f=restaurant”,则仅显示“restaurant”类型的标记,如果我使用“f=bar”,则相同。

但是 JavaScript 仍然只使用第一个 XML 代码。如何让 JavaScript 代码使用第二个 XML 代码(应用了过滤器的那个)。

所以我现在正在寻找的是一种在按下 map.html 文件中的链接时使用新的 XML 代码运行 JavaScript 代码的方法?

4

2 回答 2

0

您可以在 map.html 上应用 GET 参数并使用 Javascript 将其处理到您的 genxml3.php(map.html?f=restaurant ---> genxml3.php?f=restaurant)。

为此,您定义链接:

<a href="map.html?f=restaurant">Restaurant</a>
<a href="map.html?f=bar">Bar</a>

然后你通过 JS 或 jQuery 解析 GET 参数(如果你只期望这个参数):

var param = location.search;

现在您只需在页面刷新时执行您通常的 load() 调用 downloadUrl() 并添加 map.html 后面的部分

downloadUrl("genxml3.php" + param, function(data) {

这是非常简单的,不是一个好的解决方案,因为根本没有检查参数,但这是你的部分,这取决于你的要求。

如果您根本不想刷新页面,那么您可以为您的链接分配一个函数,该链接具有一个参数(过滤器名称):

<a href="javascript:setFilter('restaurant');" title="">Restaurant</a>

您还可以使用 jQuery 并为所有链接分配一个事件并读出它们的 innerHTML(值)。我不确定我是否正确理解您的问题,希望我能提供帮助。

于 2013-06-25T16:21:14.450 回答
0

好吧...您的 XML(第二个标记节点,名称属性)缺少语法错误:&必须使用 entity 转义与号&amp;

实际上 PHP应该自动执行此操作,您使用的是旧版本吗?

正如对 PHP 的回答中所说- htmlentities() 是否足以创建 xml 安全值?, 将 PHP 更改为

// Iterate through the rows, adding XML nodes for each

while ($row = @mysql_fetch_assoc($result)){  
  // ADD TO XML DOCUMENT NODE  
  $node = $dom->createElement("marker");  
  $newnode = $parnode->appendChild($node);   
  $newnode->setAttribute("name", htmlspecialchars($row['name']));
  $newnode->setAttribute("address", htmlspecialchars($row['address']));  
  $newnode->setAttribute("lat", htmlspecialchars($row['lat']));  
  $newnode->setAttribute("lng", htmlspecialchars($row['lng']));   
  $newnode->setAttribute("type", htmlspecialchars($row['type']));
}

并试一试...

XML 输出现在应该看起来像

<map> 
<marker name="Pan Africa Market changed" address="1521 1st Ave, Seattle, WA"     lat="47.6089" lng="-122.34" type="restaurant"/> 
<marker name="Buddha Thai &amp; Bar" address="2222 2nd Ave, Seattle, WA" lat="47.6136" lng="-122.344" type="bar"/> 
<marker name="The Melting Pot" address="14 Mercer St, Seattle, WA" lat="47.6246" lng="-122.356" type="restaurant"/> 
于 2013-06-25T18:40:26.180 回答