未捕获的TypeError:无法读取null的属性'offsetWidth'

时间:2014-04-09 15:50:59

标签: javascript jquery google-maps google-maps-api-3

在发布此问题之前,我读了几个帖子,遗憾的是我无法找到适合我问题的答案。

所以这是我的代码片段

<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
    <!--<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
    <script src="http://goessner.net/download/prj/jsonxml/xml2json.js"></script>
    -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB1Wwh21ce7jnB6yDbjVGN3LC5ns7OoOL4&amp;sensor=false">
</script>

    <link rel="stylesheet" type="text/css" href="bd_css">

    <!-- javascript code for triggering the download for csv file of businesses-->
    <script type="text/javascript">
        function populateIframe(id) 
        {
            var ifrm = document.getElementById(id);
            ifrm.src = "business_data_to_excel";
        }
    </script>

    <script>



        function showCategories(str)
        {
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
        xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            document.getElementById("txt").innerHTML=xmlhttp.responseText;
            }
          }
        // here within this bd_get_subcategories we have to 
        xmlhttp.open("GET","bd_get_subcategories?q="+str,true);
        xmlhttp.send();
        loadMap(str);
        }

    </script>
<!--               Rohit Script ---------------------->
<script type="text/javascript">

var map, actual, iw;
var gmarkers = [];
var icons = {
    img: "http://sites.google.com/site/mxamples/icons-dot.png",
    bar: [0, 0],
    cafe: [128, 32],
    hotel: [32, 32],
    disco: [96, 0],
    white: [192, 0]
};

function shifter(a) {
    var g = google.maps;
    var b = {
        url: icons.img,
        size: new g.Size(32, 32),
        origin: new g.Point(a[0], a[1]),
        anchor: new g.Point(15, 32)
    };
    return b
}

function createMarker(b, c, d, e, f) {
    var g = google.maps;
    var h = shifter(icons[e]);
    var i = new g.Marker({
        position: b,
        map: map,
        title: c,
        clickable: true,
        draggable: false,
        icon: h
    });
    i.category = e;
    i.name = c;
    i.id = f;
    gmarkers.push(i);
    var j = "<b>" + c + "<\/b><p>" + d + "<\/p>";
    g.event.addListener(i, "click", function () {
        iw.setContent(j);
        iw.open(map, this)
    });
    g.event.addListener(i, "mouseover", function () {
        i.setIcon(shifter(icons.white));
        var a = document.getElementById(f);
        if (a) {
            a.className = "focus";
            actual = a
        }
    });
    g.event.addListener(i, "mouseout", function () {
        i.setIcon(shifter(icons[e]));
        if (actual) {
            actual.className = "normal"
        }
    })
}
var hover = {
    over: function (i) {
        var a = gmarkers[i];
        var b = document.getElementById(a.id);
        b.className = "focus";
        a.setIcon(shifter(icons.white))
    },
    out: function (i) {
        var a = gmarkers[i];
        var b = document.getElementById(a.id);
        b.className = "normal";
        a.setIcon(shifter(icons[a.category]))
    }
};
var visible = {
    show: function (a) {
        for (var i = 0, m; m = gmarkers[i]; i++) {
            if (m.category == a) {
                m.setVisible(true)
            }
        }
        document.getElementById(a).checked = true
    },
    hide: function (a) {
        for (var i = 0, m; m = gmarkers[i]; i++) {
            if (m.category == a) {
                m.setVisible(false)
            }
        }
        document.getElementById(a).checked = false;
        iw.close()
    }
};

function boxclick(a, b) {
    if (a.checked) {
        visible.show(b)
    } else {
        visible.hide(b)
    }
    makeSidebar()
}

function triggerClick(i) {
    google.maps.event.trigger(gmarkers[i], "click")
}

function makeSidebar() {
    var a;
    var b = "";
    for (var i = 0, m; m = gmarkers[i]; i++) {
        if (m.getVisible()) {
            var c = gmarkers[i].category;
            c = c.replace(/^./, c.charAt(0).toUpperCase());
            if (a != c) b += "<b>" + c + "s<\/b><br \/>";
            b += '<a id="' + gmarkers[i].id + '" href="javascript:triggerClick(' + i + ')" onmouseover="hover.over(' + i + ')" onmouseout="hover.out(' + i + ')">' + gmarkers[i].name + '<\/a><br \/>';
            a = c
        }
    }
    document.getElementById("sidebar").innerHTML = b
}

function loadMap() {
    var g = google.maps;
    var a = {
        center: new g.LatLng(48.139543, 11.571436),
        zoom: 14,
        mapTypeId: g.MapTypeId.ROADMAP,
        mapTypeControlOptions: {
            mapTypeIds: [g.MapTypeId.ROADMAP, g.MapTypeId.SATELLITE, g.MapTypeId.HYBRID]
        },
        panControl: true,
        zoomControl: true
    };
    map = new g.Map(document.getElementById("map"), a);
    iw = new g.InfoWindow();
    g.event.addListener(map, "click", function () {
        if (iw) iw.close()
    });
    readData()
}

function readData() {
    var k;
    try {
        if (typeof ActiveXObject != "undefined") {
            k = new ActiveXObject("Microsoft.XMLHTTP")
        } else if (window["XMLHttpRequest"]) {
            k = new XMLHttpRequest()
        }
    } catch (e) {}
    k.open("GET", "marker_info_to_xml?p=bar", true);
    k.onreadystatechange = function () {
        if (k.readyState == 4) {
            var a = k.responseXML;
            var b = a.documentElement.getElementsByTagName("marker");
            for (var i = 0, m; m = b[i]; i++) {
                var c = parseFloat(m.getAttribute("lat"));
                var d = parseFloat(m.getAttribute("lng"));
                var e = new google.maps.LatLng(c, d);
                var f = m.getAttribute("address");
                var g = m.getAttribute("nr");
                var h = m.getAttribute("name");
                var j = m.getAttribute("category");
                createMarker(e, h, f, j, g)
            }
            if (gmarkers) {
                gmarkers.sort(compareCats)
            }
            visible.show("bar");
            visible.show("cafe");
            visible.hide("hotel");
            visible.hide("disco");
            makeSidebar()
        }
    };
    k.send(null)
}
var compareCats = function (a, b) {
    var c = a.name;
    c = c.toLowerCase();
    c = c.replace(/ä/g, "a");
    c = c.replace(/ö/g, "o");
    c = c.replace(/ü/g, "u");
    c = c.replace(/ß/g, "s");
    var d = b.name;
    d = d.toLowerCase();
    d = d.replace(/ä/g, "a");
    d = d.replace(/ö/g, "o");
    d = d.replace(/ü/g, "u");
    d = d.replace(/ß/g, "s");
    var e = a.category;
    var f = b.category;
    if (a.category == b.category) {
        if (a.name == b.name) {
            return 0
        }
        return (a.name < b.name) ? -1 : 1
    }
    return (a.category < b.category) ? -1 : 1
};
//window.onload = loadMap;
google.maps.event.addDomListener(window, "load", loadMap);

</script>

<!--               Rohit SCript end -------------------->



    </head>
    <body>
    <div id="business_form"><form action= "">
        <div id='radiobtn'>Search By:
            <input type="radio">Title
            <input type="radio">Keywords
            <input type="radio">Both
        </div></br>
        <div id="searchfor">Search For:
            <td><input type="text" maxlength="30"></td>
            <td><input type="submit" name="submit_query" value="Search"></td>
            <iframe id="frame1" style="display:none"></iframe>
            <a href="javascript:populateIframe('frame1')">Download entire directory in Excel format</a>
        </div></br>
        <div id='cat_select'>Catgories:<select name='users' onchange='showCategories(this.value)'>
        <?php
          $query_select = ee()->db->query('SELECT DISTINCT category_name,cat_counter FROM stab_num_of_cat_subcat');


        echo "<option value=''>All Categories</option>";
        foreach($query_select->result_array() as $row_value){
            echo "<option value='".$row_value['category_name']."'>".$row_value['category_name']."(".$row_value['cat_counter'].")</option>";
        }

        ?>
        </select></div>
    </form></div>

    <div id="txt">Sub Categories:<select disabled name="subcat_select"><option value=''>All Subcategories</option></select></div></br>
    <div id="map-canvas" style="width:500px;height:380px;">
</body>
</html> 

基本上在更改类别时,我正在尝试渲染地图,我从xml文件中获取数据。

但我收到错误&#34;未捕获的TypeError:无法读取属性&#39; offsetWidth&#39; of null&#34;而且我的地图没有加载。

我的示例与&#34; http://www.wolfpil.de/v3/toggle-cats.html&#34;

完全相同

我不知道我在这里做错了什么。

请帮帮我。

1 个答案:

答案 0 :(得分:18)

Uncaught TypeError: Cannot read property 'offsetWidth' of null

当地图容器的div id与地图构造函数中使用的id不匹配时,这是典型的错误。请参阅example at jsbin