我似乎无法在我的脚本中找到问题(错误)

时间:2017-07-26 12:44:36

标签: javascript php json google-maps iis-8

我真的需要你的帮助。我有一个脚本,我有一个显示标记的googlemap首页。

在每个浏览器中,我都会收到json错误。 在mozilla中使用firebug我得到了这个:

  

ReferenceError:未定义json [Meer info] index.js:54:1       loadMarkers / xmlhttp.onreadystatechange http:// /inkaart/index.js:54:1       openRemotePrompt jar:file:/// C:/ Program%20Files%20(x86)/Mozilla%20Firefox/omni.ja!/components/nsPrompter.js:494:9       openPrompt jar:file:/// C:/ Program%20Files%20(x86)/Mozilla%20Firefox/omni.ja!/components/nsPrompter.js:529:17       警报jar:file:/// C:/ Program%20Files%20(x86)/Mozilla%20Firefox/omni.ja!/components/nsPrompter.js:602:9       loadMarkers / xmlhttp.onreadystatechange http:// /inkaart/index.js:49:4

在我的markers.php代码和index.js下面:

markers.php

<?
header('Content-type: application/json');

$connect = mysql_connect("localhost","user","blablabla") or die("Could not connect");

$db = mysql_select_db("databaseblabla",$connect) or die("db invalid");

$sql = 'where 1=1';

foreach ($_GET as $field=>$value) { if ($field!='t') {

$field = substr($field, 0, strlen($field)-1);
if ($vorig_field==$field) {

    $sql = str_replace($field." in (", $field." in ('".$value."', ", $sql);
}
else {
    $sql .= " and ".$field." in ('".$value."')";

}
$vorig_field=$field;
}}

// te optimaliseren: COALESCE gebruikt geen index meer

//$sql = str_replace(' and afdeling ', " and coalesce(afdeling, 'null') ", $sql);

$sql = str_replace('[where]', $sql, return_output('markers.sql'));

$rs = mysql_query($sql) or die($sql.' '.mysql_error());

while ($rw = mysql_fetch_array($rs)) {

// als een vestiging meerdere samenwerkingsverbanden dan samenvoegen!

if ($vorig_id==$rw['vestigingsnummer'].$rw['instelling_id'].$rw['vestigingsnaam']) {

    $markers[$i]['samenwerking'] .= '<br />'.$rw['samenwerking'];
}

// en anders een nieuwe marker met alle kolommen van de query
else {
    $i++;
    foreach ($rw as $field=>$value) {
    if (is_numeric($field)==false && isset($value)==true) {
        $markers[$i][$field] = $rw[$field];
    }}
}
$markers[$i]['samenwerking'] = str_replace(' ()','',$markers[$i]['samenwerking']); //lege opmerkingen

$vorige_afdeling=$rw['afdeling'];

$vorig_id=$rw['vestigingsnummer'].$rw['instelling_id'].$rw['vestigingsnaam'];
}

mysql_close($connect);

die(json_encode($markers));

function return_output($file){    
    ob_start();   
    include $file;   
    return ob_get_clean();   
}
?>

index.js

var map;
var markersArray = [];
var infoArray = [];
var infowindowZIndex = 0;

function initialize() {

    var mapOptions = {
        center: new google.maps.LatLng(52.372, 4.899),
        zoom: 11,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    // object voor AJAX
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('titel'));    
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('legenda'));    
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('zoeken')); 
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('loading'));    

    loadMarkers();

}


function loadMarkers() {

    document.getElementById('loading').style.visibility='visible';

    // parameter ?t om caching te voorkomen
    xmlhttp.open("GET","markers.php?t=" + Math.random() + loadQuerystring(),true);
    xmlhttp.send();

    xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) {

        try {
            json = eval('(' + xmlhttp.responseText + ')'); 
        }
        catch (error) {
            alert('ERROR: ' + xmlhttp.responseText);
        }

        deleteMarkers();

        for(id in json) {
            createMarker(json[id]);
        }

        document.getElementById('loading').style.visibility='hidden';

    }}

}

function loadQuerystring() {

    var where = '';
    var checked = false;

    var boxes = getElementsByClassName("soort", "input");
    for (var i=0;i<boxes.length;i++) { if (boxes[i].checked) {
        where += '&soort'+i+'='+escape(boxes[i].value);
        checked = true;
    }}

    if (checked == false) {
        where += '&soort0=bladiebladiebla';
    }

    checked = false;

    var boxes = getElementsByClassName("specialisatie", "input");
    for (var i=0;i<boxes.length;i++) { if (boxes[i].checked) {
        where += '&specialisatie'+i+'='+escape(boxes[i].value);
        checked = true;
    }}

    if (checked == false) {
        where += '&specialisatie0=bladiebladiebla';
    }

    checked = false;

    var boxes = getElementsByClassName("afdeling", "input");
    for (var i=0;i<boxes.length;i++) { if (boxes[i].checked) {
        where += '&afdeling'+i+'='+escape(boxes[i].value);
        checked = true;
    }}

    if (checked == false) {
        where += '&afdeling0=bladiebladiebla';
    }

    return where;
}

function createMarker(json) {

    var contentString = '<div class="infowindow">'+
        json['vestigingsnaam']+'<br />'+
        json['straatnaam']+' '+json['huisnummer']+'<br />'+
        json['postcode']+' '+json['plaatsnaam']+'<br />'+
        'Tel: '+json['telefoonnummer']+'<p />'+
        '<b>Samenwerking(en):</b><br />'+json['samenwerking']+
        '</div>';

    // InfoWindowZ (met Z) zodat het een click event krijgt (zie verder)
    var infowindow = new google.maps.InfoWindow({
        content: contentString,
        disableAutoPan: true,
        maxWidth: 250
    });

    var myLatlng = new google.maps.LatLng(json['lat'], json['lon']);

    // http://www.googlemapsmarkers.com/v1/LABEL/FILL COLOR/LABEL COLOR/STROKE COLOR/
    // http://chart.apis.google.com/chart?cht=d&chdp=mapsapi&chl=pin'i\'[A'-2'f\hv'a\]h\]o\0099FF'fC\FFFFFF'tC\FF0000'eC\Lauto'f\&ext=.pngs
    //zie ook https://developers.google.com/chart/image/docs/making_charts

    if (json['afdeling']) { 
        var image = 'http://www.googlemapsmarkers.com/v1/'+json['specialisatie']+'/'+json['soort']+'/ffffff/000000';
    }
    else {
        var image = 'images/marker'+json['soort']+'.png';
    }

    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        icon: image,
        title:json['vestigingsnaam']
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });

    markersArray.push(marker);
    infoArray.push(infowindow);

}

function Zoek() {

    var result = false

    document.getElementById('loading').style.visibility='visible';

    var zoektext = document.getElementById('zoektext').value.toLowerCase();
    if (infoArray) {
        for (i in infoArray) {
            infoArray[i].close()
            if (infoArray[i].getContent().toLowerCase().indexOf(zoektext)>-1) {
                infoArray[i].open(map, markersArray[i]);
                result=true;
    }}}

    document.getElementById('loading').style.visibility='hidden';

    if (result == false) {
        alert('Geen zoekresultaat');
        document.getElementById('zoektext').focus();
    }

}

// Deletes all markers in the array by removing references to them
function deleteMarkers() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
    infoArray.length = 0;
  }
}

// http://stackoverflow.com/questions/14348092/bring-googlemaps-infowindow-to-front

google.maps.InfoWindowZ=function(opts){
  var GM = google.maps,
      GE = GM.event,
      iw = new GM.InfoWindow(),
      ce;

     if(!GM.InfoWindowZZ){
        GM.InfoWindowZZ=Number(GM.Marker.MAX_ZINDEX);
     }

     GE.addListener(iw,'content_changed',function(){
       if(typeof this.getContent()=='string'){
          var n=document.createElement('div');
              n.innerHTML=this.getContent();
              this.setContent(n);
              return;
       }
       GE.addListener(this,'domready',
                       function(){
                        var _this=this;
                        _this.setZIndex(++GM.InfoWindowZZ);
                        if(ce){
                          GM.event.removeListener(ce);
                        }
                        ce=GE.addDomListener(this.getContent().parentNode
                                          .parentNode.parentNode,'click',
                                          function(){
                                          _this.setZIndex(++GM.InfoWindowZZ);
                        });
                      })
     });

     if(opts)iw.setOptions(opts);
     return iw;
}







/*
    Developed by Robert Nyman, http://www.robertnyman.com
    Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/  
var getElementsByClassName = function (className, tag, elm){
    if (document.getElementsByClassName) {
        getElementsByClassName = function (className, tag, elm) {
            elm = elm || document;
            var elements = elm.getElementsByClassName(className),
                nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
                returnElements = [],
                current;
            for(var i=0, il=elements.length; i<il; i+=1){
                current = elements[i];
                if(!nodeName || nodeName.test(current.nodeName)) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    else if (document.evaluate) {
        getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
                classesToCheck = "",
                xhtmlNamespace = "http://www.w3.org/1999/xhtml",
                namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
                returnElements = [],
                elements,
                node;
            for(var j=0, jl=classes.length; j<jl; j+=1){
                classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
            }
            try {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
            }
            catch (e) {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
            }
            while ((node = elements.iterateNext())) {
                returnElements.push(node);
            }
            return returnElements;
        };
    }
    else {
        getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
                classesToCheck = [],
                elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
                current,
                returnElements = [],
                match;
            for(var k=0, kl=classes.length; k<kl; k+=1){
                classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
            }
            for(var l=0, ll=elements.length; l<ll; l+=1){
                current = elements[l];
                match = false;
                for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
                    match = classesToCheck[m].test(current.className);
                    if (!match) {
                        break;
                    }
                }
                if (match) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    return getElementsByClassName(className, tag, elm);
};

有人可以帮帮我吗?

更新

现在我没有收到错误但仍然没有任何标记。下面是我的index.php脚本。

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="imagetoolbar" content="no" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="pragma" content="no-cache" /> 
    <meta name="author" content="Jorrit Steetskamp" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>De scholen en samenwerkingsverbanden</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDbP9H-ibLr9mQXLfr-rvMzqbta3rILSnY&sensor=false&language=nl&region=NL"></script>
    <script type="text/javascript" src="index.js"></script>
  </head>
  <body onload="initialize()">
    <div id="map_canvas"></div>

    <div class="kader" id="loading"><img src="images/ajax-loader.gif" /> Loading...</div>

    <div class="kader" id="titel">
        <img src="images/bascule-logo.jpg" align="right" />
        <h1>in kaart</h1>Samenwerkingen met scholen en instellingen
    </div>

    <div class="kader" id="zoeken">
        <b>Zoeken<b><br />
        <input type="text" name="zoektext" id="zoektext" onkeydown="if (event.keyCode == 13) Zoek()" /><input type="button" value="Zoek" onclick="Zoek();" />
    </div>

    <div class="kader" id="legenda">
        <b>Soort</b><br />
        <input type="checkbox" class="soort" name="soort" value='51b7bf' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/51b7bf" />Basisonderwijs<br />
        <input type="checkbox" class="soort" name="soort" value='367a7f' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/367a7f" />Gecombineerd onderwijs<br />
        <input type="checkbox" class="soort" name="soort" value='1b3d40' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/1b3d40" />Voortgezet onderwijs<br />
        <input type="checkbox" class="soort" name="soort" value='ff9600' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/ff9600" />Instelling<br />
        <br />
        <b>Specialisatie</b><br />
        <input type="checkbox" class="specialisatie" name="specialisatie" value='r' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/r/FFFFFF/" />Regulier onderwijs<br />
        <input type="checkbox" class="specialisatie" name="specialisatie" value='1' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/1/FFFFFF/" />Cluster 1<br />
        <input type="checkbox" class="specialisatie" name="specialisatie" value='2' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/2/FFFFFF/" />Cluster 2<br />
        <input type="checkbox" class="specialisatie" name="specialisatie" value='3' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/3/FFFFFF/" />Cluster 3<br />
        <input type="checkbox" class="specialisatie" name="specialisatie" value='4' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/4/FFFFFF/" />Cluster 4<br />
        <input type="checkbox" class="specialisatie" name="specialisatie" value='S' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/S/FFFFFF/" />SBO<br />
        <input type="checkbox" class="specialisatie" name="specialisatie" value='P' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/P/FFFFFF/" />PRO<br />
        <input type="checkbox" class="specialisatie" name="specialisatie" value='I' checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/I/FFFFFF/" />Instelling<br />
        <br />
        <b>Samenwerkende afdeling</b><br />
        <?php

        $db = new PDO('mysql:host=localhost;dbname=unknown', 'userblaablabla', 'blabla');

        foreach($db->query('SELECT * FROM bascule_afdelingen') as $row) {
            echo '<input type="checkbox" class="afdeling" name="afdeling" value="'.$row['afdeling'].'" checked onchange="loadMarkers()" /><img class="druppel" src="http://www.googlemapsmarkers.com/v1/A/FFFFFF/FFFFFF/000000/" /><div class="afdeling">'.$row['afdeling'].'</div><br />';
        }
        ?>
        <input type="checkbox" class="afdeling" name="afdeling" value="" onchange="loadMarkers()" /><img class="stip" src="images/markerffffff.png" />[geen samenwerking]<br />
    </div>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

错误正确解释了问题。 &#39; JSON&#39;变量在用于“loadMarkers”之前尚未定义。功能

在loadMarkers函数的开头键入以下行:

var json = null;