向 Google 地图添加图层(为交通图层添加切换)

Adding layer to Google Map (Adding toggle for traffic layer)

我想切换 Google 地图交通图层。我发现这个 post:Adding Custom Control to Google Map (Adding toggle for traffic layer)

我曾尝试将 DOM 侦听器放入代码中的不同位置,但没有任何效果。使用 Firebug 我没有看到任何错误,但交通层没有切换。

我能够在流量层进行硬编码,所以我知道它可以工作。

这是我的代码:

<!DOCTYPE html>
<html>
  <head>
<!-- This tutorial came from: https://developers.google.com/maps/articles/phpsqlajax_v3 -->
<!--  -->
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Eyehike Hike Locator</title>
<!-- This code will allow you to develop a map without an api key -->
<!--    <script src="http://maps.google.com/maps/api/js?sensor=false" 
             type="text/javascript"></script> -->
<!-- This line for development brings in the libraries needed for layers without using an api key  -->           
<script src="https://maps.googleapis.com/maps/api/js?libraries=weather&sensor=false"></script>

     <script type="text/javascript"> 

    var m_icon;
    var m_shadow;
    var mrk_id;
    var thumnbnail;
    var trafficLayer;
    function toggleTraffic(){
        if(trafficLayer.getMap() == null){
            //traffic layer is disabled.. enable it
            trafficLayer.setMap(map);
        } else {
            //traffic layer is enabled.. disable it
            trafficLayer.setMap(null);             
        }
    }

    function load() {
        var map = new google.maps.Map(document.getElementById("map"), {
          center: new google.maps.LatLng(44.50, -115.00),
          zoom: 6,
          mapTypeId: 'hybrid'
        }); // The higher the zoom number, the more detailed the map.



 //       var trafficLayer = new google.maps.TrafficLayer();
 //       trafficLayer.setMap(map);

        var infoWindow = new google.maps.InfoWindow;

        // Change this depending on the name of your PHP file
        downloadUrl("marker_php_07_16.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 rank = markers[i].getAttribute("rank"); 
                var mileage = markers[i].getAttribute("mileage"); 
                var permalink = markers[i].getAttribute("permalink");
                var photolink = markers[i].getAttribute("photolink");
                var routelink = markers[i].getAttribute("routelink");
                var image_thumb = markers[i].getAttribute("thumbnail");


                if(rank > 0 && rank < 10) {
                    iconImageOverUrl = 'http://www.eyehike.com/modules/hikelocator/icons/' + type + rank + '.png';
                    iconImageOutUrl = 'http://www.eyehike.com/modules/hikelocator/icons/' + type + rank + '.png';         
                    m_icon = 'http://www.eyehike.com/modules/hikelocator/icons/' + type + rank + '.png';
                    m_shadow = 'http://www.google.com/mapfiles/shadow50.png';
                } 
                else {
                    iconImageOverUrl = 'http://www.eyehike.com/modules/hikelocator/icons/blue_.png';
                    iconImageOutUrl = 'http://www.eyehike.com/modules/hikelocator/icons/blue_.png';       
                    m_icon = 'http://www.eyehike.com/modules/hikelocator/icons/blue_.png';
                    m_shadow = 'http://www.google.com/mapfiles/shadow50.png';
                };

                var marker = new google.maps.Marker({
                map: map,
                position: point,
                icon: m_icon,
                shadow: m_shadow,
                title: name,
                zIndex: mrk_id,
                optimized: false,
                html: "<div style='font-size:12px';width: 400px; height: 200px'><b>" + name 
                    + "</b></br><a href=\"" + photolink +  "\" TARGET=blank><img src=\"" + image_thumb +  "\" height=108 width=144 vspace=2 border=4 align=left></a>"
                    + address
                    + '</br>Difficulty (1-5) : '
                    + rank
                    + '. Mileage: '
                    + mileage
                    + " miles.</br>Trail review at: "
                    + "<a href=\"" + permalink +   "\" TARGET=blank>www.eyehike.com</a> <br/>"
                    + "<a href=\"" + photolink +  "\" TARGET=blank>See pictures of the hike.</a><br/>"
                    + "<a href=\"" + routelink +  "\" TARGET=blank>Topograhic map.</a>" 
                    + "</div>"


                });
                bindInfoWindow(marker, map, infoWindow);

            }


        });

    }

    function bindInfoWindow(marker, map, infoWindow, html) {
        google.maps.event.addListener(marker, "click", function() {
            infoWindow.setContent(this.html);
            infoWindow.open(map, this);

//      google.maps.event.addDomListener(window, 'load', load);         

        });
        trafficLayer = new google.maps.TrafficLayer();
        google.maps.event.addDomListener(document.getElementById('trafficToggle'), 'click', toggleTraffic);  

    }

    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()">
        <button id="trafficToggle">Toggle Traffic Layer</button>
        <div id="map" style="width: 900px; height: 600px">
        </div>
    </body>
</html>

您的代码存在两个潜在问题:

  1. map 变量是 load 函数的局部变量。
  2. 配置trafficLayer的代码在bindInfoWindow函数里面

代码片段:

var map;
var trafficLayer;

function toggleTraffic() {
  if (trafficLayer.getMap() == null) {
    //traffic layer is disabled.. enable it
    trafficLayer.setMap(map);
  } else {
    //traffic layer is enabled.. disable it
    trafficLayer.setMap(null);
  }
}

function load() {
  // initialize the global map variable
  map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(44.50, -115.00),
    zoom: 6,
    mapTypeId: 'hybrid'
  }); // The higher the zoom number, the more detailed the map.

  trafficLayer = new google.maps.TrafficLayer();
  google.maps.event.addDomListener(document.getElementById('trafficToggle'), 'click', toggleTraffic);

}
google.maps.event.addDomListener(window, "load", load);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<button id="trafficToggle">Toggle Traffic Layer</button>
<div id="map"></div>

Here is my finished html code with the traffic layer working:
<!DOCTYPE html>
<html>
  <head>
<!-- This tutorial came from: 
     https://developers.google.com/maps/articles/phpsqlajax_v3 
Copyright 2016 Steven Jones
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Google Maps API key manager site: https://console.developers.google.com/apis/credentials?project=divine-course-137822
Key name as of 8/6/2016 - browser_key_hikelocator: AIzaSyCLxFu4qJHu_ytCjXeWVMUd67hyOS_kT6I
     -->
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Eyehike Hike Locator</title>
<!-- This line of code will allow you to develop a map without an api key -->

<script src="https://maps.googleapis.com/maps/api/js?libraries=weather&sensor=false"></script>


<!-- This code is for the api key   -->
<!-- <script src="https://maps.googleapis.com/maps/api/js?key=your_key_here&callback=load" 
        async defer></script>  -->
<!-- End of code for api      -->            

     <script type="text/javascript"> 
    // this variable will collect the html which will eventually be placed in the side_bar 
    var side_bar_html = "";  
    var side_bar = ""; 
    var marker = "";
    var sb_markers = []; 
    var mcolor = "";
    var rank = "";
    var mileage = "";
    var m_icon;
    var m_shadow;
    var mrk_id;
    var thumnbnail;
    var map;
    var trafficLayer;
    function toggleTraffic(){
        if(trafficLayer.getMap() == null){
            //traffic layer is disabled.. enable it
            trafficLayer.setMap(map);
        } 
        else {
            //traffic layer is enabled.. disable it
            trafficLayer.setMap(null);             
        }
    }


    function load() {
        //Initialize the global map variable
        map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(44.50, -117.00),
            zoom: 6,   // The higher the zoom number, the more detailed the map.
            mapTypeId: 'hybrid',
            zoomControl: true,
            zoomControlOptions: {
                style: google.maps.ZoomControlStyle.LARGE
            }
        }); 


        trafficLayer = new google.maps.TrafficLayer();
        google.maps.event.addDomListener(document.getElementById('trafficToggle'), 'click', toggleTraffic); 


        var infoWindow = new google.maps.InfoWindow;

        // Change this depending on the name of your PHP file
        downloadUrl("marker_sqli_data.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("mrk_id");
                var name = markers[i].getAttribute("name");
                var mcolor = markers[i].getAttribute("mcolor");
                var point = new google.maps.LatLng(
                      parseFloat(markers[i].getAttribute("lat")),
                      parseFloat(markers[i].getAttribute("lng")));

                var rank = markers[i].getAttribute("rank"); 
                var mileage = markers[i].getAttribute("mileage"); 
                var permalink = markers[i].getAttribute("permalink");
                var photolink = markers[i].getAttribute("photolink");
                var routelink = markers[i].getAttribute("routelink");
                var image_thumb = markers[i].getAttribute("thumbnail");


                if(rank > 0 && rank < 10) {
                    iconImageOverUrl = 'http://www.eyehike.com/modules/hikelocator/icons/' + mcolor + rank + '.png';
                    iconImageOutUrl = 'http://www.eyehike.com/modules/hikelocator/icons/' + mcolor + rank + '.png';       
                    m_icon = 'http://www.eyehike.com/modules/hikelocator/icons/' + mcolor + rank + '.png';
                    m_shadow = 'http://www.google.com/mapfiles/shadow50.png';
                } 
                else {
                    iconImageOverUrl = 'http://www.eyehike.com/modules/hikelocator/icons/blue_.png';
                    iconImageOutUrl = 'http://www.eyehike.com/modules/hikelocator/icons/blue_.png';       
                    m_icon = 'http://www.eyehike.com/modules/hikelocator/icons/blue_.png';
                    m_shadow = 'http://www.google.com/mapfiles/shadow50.png';
                };


                var marker = new google.maps.Marker({
                    map: map,
                    position: point,
                    icon: m_icon,
                    shadow: m_shadow,
                    title: name,
                    zIndex: mrk_id,
                    optimized: false,

                    html: "<div style='font-size:14px; line-height: 18px; width: 375px; height: 130px'><b>" + name 
                        + "</b></br><a href=\"" + photolink +  "\" TARGET=blank><img src=\"" + image_thumb +  "\" height=108 width=144 vspace=2 border=4 align=left></a>"
                        + '</br>Difficulty (1-5) : '
                        + rank
                        + '. Mileage: '
                        + mileage
                        + " miles.</br>Trail review at: "
                        + "<a href=\"" + permalink +   "\" TARGET=blank>www.eyehike.com</a> <br/>"
                        + "<a href=\"" + photolink +  "\" TARGET=blank>See pictures of the hike.</a><br/>"
                        + "<a href=\"" + routelink +  "\" TARGET=blank>Topograhic map.</a>" 
                        + "</div>"

                });


                // add a line to the side_bar html
                side_bar_html += '<a href="javascript:myclick(' + (sb_markers.length) + ')">' + rank + " " + name + '<\/a><br>';

                //save the info to use later for the side_bar
                sb_markers.push(marker);

//              var side_bar = createSidebarEntry(rank, name);
//                   sidebar.appendChild(sidebarEntry);

                bindInfoWindow(marker, map, infoWindow);

                //When I put this in the marker click handler then the side_bar
                //info appears when the first time I click on a marker.
                // put the assembled side_bar_html contents into the side_bar div
                document.getElementById("side_bar").innerHTML = side_bar_html;  

            }
        }
        );
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
        google.maps.event.addListener(marker, "click", function() {
            infoWindow.setContent(this.html);
            infoWindow.open(map, this);
        });
    }

    // This function picks up the click and opens the corresponding info window
    function myclick(i) {
      google.maps.event.trigger(sb_markers[i], "click");
    }   

    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>
<style type="text/css">

body {
    font: 1em/150% Arial, Helvetica, sans-serif;
}
a {
    color: #669;
    text-decoration: none;
}
a:hover {
    text-decoration: underline;
}
h1 {
    font: bold 36px/100% Arial, Helvetica, sans-serif;
}

/************************************************************************************
STRUCTURE
*************************************************************************************/
#pagewrap {
    padding: 0px;
    border:1px solid black; 
    overflow:auto;
}

#button {
    height: 21px;
    width: 956px;
    float: right;
    vertical-align:top; 
    margin-bottom: -9px; //Note added line here 

}

#side_bar {
    width: 250px;
    height: 500px; 
    overflow:auto; 
    text-decoration: underline; 
    color:#393; 
    fontSize: 10px; 
    line-height: 18px;
    float: left;
    vertical-align:top;
}

#map {
    width: 956px;
    height: 650px; 
    float: right;
}

#legend {
    padding-top: 4px;
    width: 250px;
    float: left;
    vertical-align:bottom;  
    overflow:hidden;  
    z-index:99;
    text-align: center;
    background-color:#ebe3de; 
    border:#393 1px solid"
}

#legendicon {
    /* padding top, right, bottom, left */
    padding: 0px 0px 0px 10px;
}

/*This will detect firefox*/
@-moz-document url-prefix() {
    #button {
        height: 21px;
        width: 1075px;
        float: right;
        vertical-align:top; 
        margin-bottom: -9px; //Note added line here 
    }
    #map {
        width: 1075px;
        height: 650px; 
        float: right;
    }
}
/************************************************************************************
MEDIA QUERIES
*************************************************************************************/
/* for 980px or less */
@media screen and (max-width: 980px) {

    #pagewrap {
        width: 95%;
    }
    #button {
        width: 74%;
    }
    #side_bar {
        width: 25%;
    }
    #map {
        width: 74%;
    }
    #legend {
        width: 25%;
    }

}

/* for iphone 5 samsung s4 375px or less */
@media screen and (max-width: 375px) {

    #side_bar {
        width: auto;
        float: none;
    }
    #button {
        width: auto;
        float: none;
        vertical-align: top;
    }

    #map {
        width: auto;
        float: none;
    }
}

/* for 280px or less */
@media screen and (max-width: 280px) {

    #button {
        height: auto;
    }
    h1 {
        font-size: 24px;
    }
    #side_bar {
        display: none;
    }
}

/* border & guideline (you can ignore these) */
/* #side_bar { */
/*  background: #f0efef; */
/*} */
/*#map { */
/*  background: #f8f8f8; */
/*  width: 600px; height: 600px; overflow:hidden" */
/*} */

#button, #map, #sidebar {
    margin-bottom: 0px;
}
#pagewrap, #button, #map, #side_bar, #legend {
    border: solid 1px #ccc;
}

</style>
</head>
    <body onload="load()">
<h3><a href="../../2016/">Return to Eyehike</a></h3>
<div id="pagewrap">

    <div id="button"><button id="trafficToggle">Toggle Traffic Layer</button></div>

    <div id="side_bar">
        <h4>Loading...</h4>
    </div>

    <div id="map">
    </div>

    <div id='legend'>
        <h4 style="color:#393; line-height: 10px; margin: 0; padding: 1">Map Legend</h4>
            <div id="legendicon">
                <img src="http://www.eyehike.com/modules/hikelocator/icons/green_.png" WIDTH=15 HEIGHT=25 ALIGN=left>- Loop Hike<p class="big">
                <img src="http://www.eyehike.com/modules/hikelocator/icons/blue_.png" WIDTH=15 HEIGHT=25 ALIGN=left>- Out and Back Hike<p class="big">
                <img src="http://www.eyehike.com/modules/hikelocator/icons/orange_.png" WIDTH=15 HEIGHT=25 ALIGN=left>- Backpack
                </p>
            </div>
        <sup>
        Difficulty Level: 1 thru 5
        </sup>
    </div>

</div>

</body>
</html>