如何获得我的选择框和地图脚本进行交谈

时间:2018-10-24 20:09:23

标签: javascript php google-maps

我正在制作一个Google Map,它从MySQL数据库获取其数据。我修改了“在Go​​ogle Maps中使用MySQL和PHP”中的示例代码,我有一个php文件markerxml.php,当您将类别发送给它时,它以XML格式返回记录,例如:markerxml.php?category_select=Bars

我有一个选择,可以从数据库中获取类别并进行填充。我尝试了onchange='category_select(this)来选择功能category_select的地方:

function category_select(obj){
var urlString = "http://example.com/markerxml.php?category_select=";
var category_select = obj.options[obj.selectedIndex];
if (category_select.value != "nothing"){
window.location=urlString + category_select.value;
}
}

然后在创建地图时出现一个downloadUrl(category_select, function(doc)(我试图在其中放置category_select的值)

如果我绕过我的选择而只是硬代码:downloadUrl('markerxml.php?category_select=Bars', function(doc),那么我会得到带有标记的地图。

以下是地图文件中的代码:

<!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Using MySQL and PHP with Google Maps</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
          <?php
      $conn = new mysqli("localhost","","","") or die($this->mysqli->error);
      $result = $conn->query("select DISTINCT Bus_categories from cmsb_markers ORDER BY Bus_categories ASC");   
        echo "<form action='markerxml.php' method='get' >"; 
          echo "<select style='font-size:14px;height:20px;' name='category_select' onchange='category_select(this)'>";
        echo "<option  value=''selected>Select Business Category</option>";
          while ($row = $result->fetch_assoc()) {
                        unset($name);                  
                        $name = $row['Bus_categories'];         
                        echo '<option  value="'.$name.'">'.$name.'</option>';                
      }
          echo "</select></form>"; ?>
    <div id="map"></div>
    <script>
     var customLabel = {
        restaurant: {
          label: 'R'
        },
        bar: {
          label: 'B'
        }
     };  
  function category_select(obj){
    var urlString = "http://example.com/markerxml.php?category_select=";
    var category_select = obj.options[obj.selectedIndex];
    if (category_select.value != "nothing"){
        window.location=urlString + category_select.value;
    }
  }
        function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(39.1,-94.55),
          zoom: 12
        });
        var infoWindow = new google.maps.InfoWindow;
          downloadUrl('markerxml.php?category_select=Bars', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('marker');
            Array.prototype.forEach.call(markers, function(markerElem) {
              var id = markerElem.getAttribute('id');
              var name = markerElem.getAttribute('name1');
              var address = markerElem.getAttribute('address');
              var type = markerElem.getAttribute('type');
              var point = new google.maps.LatLng(
                  parseFloat(markerElem.getAttribute('lat')),
                  parseFloat(markerElem.getAttribute('lng')));

              var infowincontent = document.createElement('div');
              var strong = document.createElement('strong');
              strong.textContent = name
              infowincontent.appendChild(strong);
              infowincontent.appendChild(document.createElement('br'));

              var text = document.createElement('text');
              text.textContent = address
              infowincontent.appendChild(text);
              var icon = customLabel[type] || {};
              var marker = new google.maps.Marker({
                map: map,
                position: point,
                label: icon.label
              });
              marker.addListener('click', function() {
                infoWindow.setContent(infowincontent);
                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>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=<My API key>&callback=initMap">
    </script>
  </body>
</html>

在浏览器中使用视图源查看的markerxml.php文件的输出(一条记录):

<?xml version="1.0"?>
<markers><marker id="452" Bus_categories="Bars" name1="PBR Big Sky" address="111 E 13th St." phone="(816) 442-8145" Contact="Will Kinser" City="Kansas City" state="MO" zip="64105" email="info@pbrbigskykc.com" web="www.pbrbigskykc.com" lat="39.098391" lng="-94.581677" distance="2.4730047851899717"/></markers>

这是markerxml.php的代码:

<?php
require("phpsqlsearch_dbinfo.php");
// Get parameters from URL
$center_lat = 39.125212;
$center_lng = -94.551136;
$radius = 10;

// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$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());
}
// Search the rows in the markers table
$query = sprintf("SELECT *, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM cmsb_markers WHERE Bus_categories = '$_GET[category_select]' HAVING distance < '%s' ORDER BY distance LIMIT 0 , 1838",

mysql_real_escape_string($center_lat),
mysql_real_escape_string($center_lng),
mysql_real_escape_string($center_lat),
 mysql_real_escape_string($radius));
$result = mysql_query($query);
$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)){
  $node = $dom->createElement("marker");
  $newnode = $parnode->appendChild($node);
  $newnode->setAttribute("id", $row['id']);
  $newnode->setAttribute("Bus_categories", $row['Bus_categories']);
  $newnode->setAttribute("name1", $row['name1']);
  $newnode->setAttribute("address", $row['address']);
  $newnode->setAttribute("phone", $row['Bus_phone']);
  $newnode->setAttribute("Contact", $row['content']);
  $newnode->setAttribute("City", $row['Bus_city']);
  $newnode->setAttribute("state", $row['Bus_state']);
  $newnode->setAttribute("zip", $row['Bus_zip']);
  $newnode->setAttribute("email", $row['Bus_email']);
  $newnode->setAttribute("web", $row['Bus_web']);
  $newnode->setAttribute("lat", $row['lat']);
  $newnode->setAttribute("lng", $row['lng']);
  $newnode->setAttribute("distance", $row['distance']);
}
echo $dom->saveXML();
?>

这是select的html输出:

<form action='markerxml.php' method='get' >
  <select style='font-size:14px;height:20px;' name='category_select' onchange='category_select(this)'>
    <option  value=''selected>Select Business Category</option>
    <option  value=""></option>
    <option  value="Accountants">Accountants</option>
    <option  value="Accountants--Certified Public">Accountants--Certified Public</option>
    <option  value="Accounting & Tax Service">Accounting & Tax Service</option>
    <option  value="Accounting Software">Accounting Software</option><option  value="Advertising">Advertising</option>
    <option  value="Advertising Agencies & Counselors">Advertising Agencies & Counselors</option>
    <option  value="Advertising--Outdoor">Advertising--Outdoor</option>
    <option  value="Agricultural Fertilizer & Chemicals">Agricultural Fertilizer & Chemicals</option>
    <option  value="Air Conditioning & Heating Sales & Service">Air Conditioning & Heating Sales & Service</option>
  </select>
</form>
<div id="map"></div>

1 个答案:

答案 0 :(得分:0)

运行发布的代码时,出现JavaScript错误:Uncaught TypeError: category_select is not a function。最简单的解决方法是重命名category_select函数。

<form action='markerxml.php' method='get'>
  <select style='font-size:14px;height:20px;' name='category_select' onchange='category_select_fn(this)'>
    <option  value=''selected>Select Business Category</option>
    <option  value=""></option>
    <option  value="Accountants">Accountants</option>
    <option  value="Bars">Bars</option>
  </select>
</form>

function category_select_fn(obj) {
  console.log(obj);
  var urlString = "http://example.com/markerxml.php?category_select=";
  var category_selected = obj.options[obj.selectedIndex];
  if (category_selected.value != "nothing") {
    window.location = urlString + category_selected.value;
  }
}

proof of concept fiddle

代码段:

var xmlStr = '<?xml version="1.0"?><markers><marker id="452" Bus_categories="Bars" name1="PBR Big Sky" address="111 E 13th St." phone="(816) 442-8145" Contact="Will Kinser" City="Kansas City" state="MO" zip="64105" email="info@pbrbigskykc.com" web="www.pbrbigskykc.com" lat="39.098391" lng="-94.581677" distance="2.4730047851899717"/></markers>';

function parseXml(str) {
  if (window.ActiveXObject) {
    var doc = new ActiveXObject('MicrosoftXMLDOM');
    doc.loadXML(str);
    return doc;
  } else if (window.DOMParser) {
    return (new DOMParser).parseFromString(str, 'text/xml');
  }
};

function category_select_fn(obj) {
  console.log(obj);
  var urlString = "http://example.com/markerxml.php?category_select=";
  var category_selected = obj.options[obj.selectedIndex];
  if (category_selected.value != "nothing") {
    window.location = urlString + category_selected.value;
  }
}
#map {
  height: 90%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<form action='markerxml.php' method='get'>
  <select style='font-size:14px;height:20px;' name='category_select' onchange='category_select_fn(this)'>
    <option value='' selected>Select Business Category</option>
    <option value=""></option>
    <option value="Accountants">Accountants</option>
    <option value="Bars">Bars</option>
  </select>
</form>
<div id="map"></div>
<script>
  var customLabel = {
    restaurant: {
      label: 'R'
    },
    bar: {
      label: 'B'
    }
  };

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: new google.maps.LatLng(39.1, -94.55),
      zoom: 12
    });
    var infoWindow = new google.maps.InfoWindow;
    // downloadUrl('markerxml.php?category_select=Bars', function(data) {
    var xml = parseXml(xmlStr); //data.responseXML;
    var markers = xml.documentElement.getElementsByTagName('marker');
    Array.prototype.forEach.call(markers, function(markerElem) {
      var id = markerElem.getAttribute('id');
      var name = markerElem.getAttribute('name1');
      var address = markerElem.getAttribute('address');
      var type = markerElem.getAttribute('type');
      var point = new google.maps.LatLng(
        parseFloat(markerElem.getAttribute('lat')),
        parseFloat(markerElem.getAttribute('lng')));

      var infowincontent = document.createElement('div');
      var strong = document.createElement('strong');
      strong.textContent = name
      infowincontent.appendChild(strong);
      infowincontent.appendChild(document.createElement('br'));

      var text = document.createElement('text');
      text.textContent = address
      infowincontent.appendChild(text);
      var icon = customLabel[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        label: icon.label
      });
      marker.addListener('click', function() {
        infoWindow.setContent(infowincontent);
        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>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>