javascript - Google Maps API - 基于复选框状态的 loadGeoJson

标签 javascript html google-maps-api-3

我有这个 Google map 叠加文件。

叠加 - https://api.myjson.com/bins/ge7q4

function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 5,
          center: {lat: 49.656963, lng: -112.506664},
		  gestureHandling: 'greedy',
  mapTypeControl: false
        });
		  
		  
	  
		  
		  // Load GeoJson Data Plus Choose Polygon Color


		  		  		  map.data.loadGeoJson(
            'https://api.myjson.com/bins/ge7q4');
		  
		  
			map.data.setStyle(function myFunction(feature) {
		  var checkBox = document.getElementById("overlayid");
		  if (checkBox.checked == true){
			  			return {
			      fillColor: feature.getProperty('COLOR'),
			       strokeWeight: 1,
			       strokeColor: 'white',
			       fillOpacity: 0.4,
			       strokeOpacity: 0.7,
			       zIndex: 0
			};
		  } else {
			return {
			      fillColor: feature.getProperty('COLOR'),
			       strokeWeight: 1,
			       strokeColor: 'black',
			       fillOpacity: 0.4,
			       strokeOpacity: 0.7,
			       zIndex: 0
			};
		  }
		});		  
		  
	  
		  

		  
 		// Infowindow
		var infoWindow = new google.maps.InfoWindow({
					zIndex: 2
			});
		    map.data.addListener('click', function(event) {
				 
			map.data.revertStyle();
			map.data.overrideStyle(event.feature, {strokeWeight: 2, strokeColor: 'black', zIndex: 1});
			
			var CDNAME	= event.feature.getProperty('CDNAME');
			var COLOR	= event.feature.getProperty('COLOR');
			
			infoWindow.setPosition( event.latLng );
			infoWindow.setOptions( {
				pixelOffset: {width: 0, height: -3}
			});
		
			infoWindow.setContent(
					"CDNAME: <b>" + CDNAME + "</b><br />" + 
					"COLOR: <b>" + COLOR + "</b>"
			);	
			infoWindow.open(map);	
			
		 });
		 
		 map.data.addListener('clickout', function(event) {
		 		 
		 	map.data.revertStyle();
		 	infoWindow.close();
		 });
		  
		 map.data.addListener('mouseover', function(event) {
			 
			map.data.revertStyle();
			map.data.overrideStyle(event.feature, {strokeWeight: 2, strokeColor: 'black', zIndex: 1});		 		 
		 });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function() {
          var places = searchBox.getPlaces();

          // For each place, get the icon, name and location.
          var bounds = new google.maps.LatLngBounds();
          places.forEach(function(place) {
            if (!place.geometry) {
              console.log("Returned place contains no geometry");
              return;
            }
			  
            if (place.geometry.viewport) {
              // Only geocodes have viewport.
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
          });
          map.fitBounds(bounds);
        });
      }
      /* 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;
      }

#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}	
	
<div id="floating-panel">
<input type="checkbox" id="overlayid" name="overlayname" value="overlayvalue" onclick="myFunction()" checked="checked">Border Color<br>
</div>
    <div id="map"></div>
        <script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete"
         async defer></script>

我希望能够通过选中/取消选中复选框将边框颜色从白色切换为黑色。

现在,只有当我在代码中手动更改复选框的状态时,它才有效。

我假设它与返回函数有关。

最佳答案

我在发布的代码中遇到了 JavaScript 错误Uncaught ReferenceError: myFunction is not Defined。要在 HTML 元素(您的复选框)的点击监听器中使用该函数,需要在全局范围内定义它。它也不能接受任何争论。我建议:

  1. 将该函数重命名为 styleFunc,并将其移出 initAutocomplete 函数:
function styleFunc(feature) {
  var checkBox = document.getElementById("overlayid");
  if (checkBox.checked == true) {
    return {
      fillColor: feature.getProperty('COLOR'),
      strokeWeight: 1,
      strokeColor: 'white',
      fillOpacity: 0.4,
      strokeOpacity: 0.7,
      zIndex: 0
    };
  } else {
    return {
      fillColor: feature.getProperty('COLOR'),
      strokeWeight: 1,
      strokeColor: 'black',
      fillOpacity: 0.4,
      strokeOpacity: 0.7,
      zIndex: 0
    };
  }
}
  • 创建另一个函数(stylFeatures),它为 GeoJson 数据层中的所有对象设置样式,在复选框的 onclick 事件中调用它:
  • function styleFeatures() {
      map.data.setStyle(styleFunc);
    }
    
  • 在 HTML 中调用它:
  • proof of concept fiddle

    screenshot of resulting map

    代码片段:

    var map;
    
    function initAutocomplete() {
      map = new google.maps.Map(document.getElementById('map'), {
        zoom: 5,
        center: {
          lat: 49.656963,
          lng: -112.506664
        },
        gestureHandling: 'greedy',
        mapTypeControl: false
      });
    
      // Load GeoJson Data Plus Choose Polygon Color
      map.data.loadGeoJson(
        'https://api.myjson.com/bins/ge7q4');
    
      map.data.setStyle(styleFunc);
    
      // Infowindow
      var infoWindow = new google.maps.InfoWindow({
        zIndex: 2
      });
      map.data.addListener('click', function(event) {
        map.data.revertStyle();
        map.data.overrideStyle(event.feature, {
          strokeWeight: 2,
          strokeColor: 'black',
          zIndex: 1
        });
    
        var CDNAME = event.feature.getProperty('CDNAME');
        var COLOR = event.feature.getProperty('COLOR');
    
        infoWindow.setPosition(event.latLng);
        infoWindow.setOptions({
          pixelOffset: {
            width: 0,
            height: -3
          }
        });
    
        infoWindow.setContent(
          "CDNAME: <b>" + CDNAME + "</b><br />" +
          "COLOR: <b>" + COLOR + "</b>"
        );
        infoWindow.open(map);
      });
    
      map.data.addListener('clickout', function(event) {
        map.data.revertStyle();
        infoWindow.close();
      });
      map.data.addListener('mouseover', function(event) {
        map.data.revertStyle();
        map.data.overrideStyle(event.feature, {
          strokeWeight: 2,
          strokeColor: 'black',
          zIndex: 1
        });
      });
    }
    
    function styleFunc(feature) {
      var checkBox = document.getElementById("overlayid");
      if (checkBox.checked == true) {
        return {
          fillColor: feature.getProperty('COLOR'),
          strokeWeight: 1,
          strokeColor: 'white',
          fillOpacity: 0.4,
          strokeOpacity: 0.7,
          zIndex: 0
        };
      } else {
        return {
          fillColor: feature.getProperty('COLOR'),
          strokeWeight: 1,
          strokeColor: 'black',
          fillOpacity: 0.4,
          strokeOpacity: 0.7,
          zIndex: 0
        };
      }
    }
    
    function styleFeatures() {
      map.data.setStyle(styleFunc);
    }
    html,
    body,
    #map {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    #floating-panel {
      position: absolute;
      top: 10px;
      left: 25%;
      z-index: 5;
      background-color: #fff;
      padding: 5px;
      border: 1px solid #999;
      text-align: center;
      font-family: 'Roboto', 'sans-serif';
      line-height: 30px;
      padding-left: 10px;
    }
    <div id="map"></div>
    <!-- Replace the value of the key parameter with your own API key. -->
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initAutocomplete"></script>
    <div id="floating-panel">
      <input type="checkbox" id="overlayid" name="overlayname" value="overlayvalue" onclick="styleFeatures()" checked="checked">Border Color<br>
    </div>

    <input type="checkbox" id="overlayid" name="overlayname" value="overlayvalue" onclick="styleFeatures()" checked="checked">Border Color<br>
    

    关于javascript - Google Maps API - 基于复选框状态的 loadGeoJson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54163841/

    相关文章:

    javascript - 谷歌地图不显示

    java - JSF 页面中删除按钮中的错误

    javascript - 点击后 Knockout.js 输入焦点

    javascript - 构建所有选择框的 id 数组

    html - 多个名称和值使用 css 和 html 通过一个复选框或按钮

    html - 在 Canvas 的裁剪区域外放置阴影

    html - 在一个页面中使用大量表格,这是一个问题吗?

    javascript - jQuery Mobile 和 Google map 不可见

    javascript - IF 条件下的 Google map

    javascript - 如何使用 mocha、chai 和 sinon 模拟和测试闭包