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

时间:2019-01-12 21:02:22

标签: 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>

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

现在,仅当我在代码中手动更改复选框的状态时,它才起作用。

我认为这与返回函数有关。

1 个答案:

答案 0 :(得分:2)

我收到发布代码Uncaught ReferenceError: myFunction is not defined的javascript错误。要在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
    };
  }
}
  1. 创建另一个函数(stylFeatures,该函数为GeoJson数据层中的所有对象设置样式,然后在复选框的onclick事件中调用它:
function styleFeatures() {
  map.data.setStyle(styleFunc);
}
  1. 在您的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>