0

从事谷歌地图项目并坚持似乎是一个小问题。当我调用 displayMarkers 函数时,萤火虫返回:

ReferenceError:未定义 displayMarkers [中断此错误]

显示标记(1);

<script type="text/javascript">
    function initialize() {
        var center = new google.maps.LatLng(25.7889689, -80.2264393);
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 10,
            center: center,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        //var data = [[25.924292, -80.124314], [26.140795, -80.3204049], [25.7662857, -80.194692]]     var data = {"crs": {"type": "link", "properties": {"href": "http://spatialreference.org/ref/epsg/4326/", "type": "proj4"}}, "type": "FeatureCollection", "features": [{"geometry": {"type": "Point", "coordinates": [25.924292, -80.124314]}, "type": "Feature", "properties": {"industry": [2], "description": "hosp", "title": "shaytac hosp2"}, "id": 35}, {"geometry": {"type": "Point", "coordinates": [26.140795, -80.3204049]}, "type": "Feature", "properties": {"industry": [1, 2], "description": "retail", "title": "shaytac retail"}, "id": 48}, {"geometry": {"type": "Point", "coordinates": [25.7662857, -80.194692]}, "type": "Feature", "properties": {"industry": [2], "description": "hosp2", "title": "shaytac hosp3"}, "id": 36}]}
        var markers = [];
        for (var i = 0; i < data.features.length; i++) {
            var latLng = new google.maps.LatLng(data.features[i].geometry.coordinates[0], data.features[i].geometry.coordinates[1]);
            var marker = new google.maps.Marker({
                position: latLng,
                title: console.log(data.features[i].properties.industry[0]),
                map: map
            });
            marker.category = data.features[i].properties.industry[0];
            marker.setVisible(true);
            markers.push(marker);
        }
        function displayMarkers(category) {
            var i;
            for (i = 0; i < markers.length; i++) {
                if (markers[i].category === category) {
                    markers[i].setVisible(true);
                } else {
                    markers[i].setVisible(false);
                }
            }
        }
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-container">
    <div id="map"></div>
</div>
<input type="button" value="Retail" onclick="displayMarkers(1);">
4

2 回答 2

3

函数displayMarkers必须在全局范围内才能被这样调用(从onclick属性中)。

这可能就是正在发生的事情。请正确格式化和缩进您的代码,这应该很容易发现(我认为它是在内部定义的initialize,而它应该在外部)。

于 2012-11-23T16:55:43.280 回答
2

displayMarkers在函数内部定义initialize

onclick="displayMarkers(1);"在全局命名空间中搜索该函数,显然它不存在。这是一种使displayMarkers函数成为全局但仍然能够引用内部定义的变量的解决方法initialize。改变:

function initialize() {
    // ...
    function displayMarkers(category) {
        // ...
    }
}

到:

function initialize() {
    // ...  
    window.displayMarkers = function (category) {
        // ...  
    }
}
于 2012-11-23T17:01:52.733 回答