javascript - 从多个 JSON 文件中切换复选框选择标记

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

我无法切换复选框选择上的标记。我试图在 stackoverflow 上找到答案,但找不到任何合适的答案。

我有 4 个带有坐标的 JSON 文件,并且我为不同的 json 文件制作了 4 个复选框,当我单击两个或多个复选框时,标记会出现,但当我取消选中标记时,标记不会消失。

我尝试使用 setMap(null) 函数,但收到错误“setMap 未定义”。

$(document).ready(function() {
    var map;
    var mapMarker;
    function initMap() {
    	map = new google.maps.Map(document.getElementById('map'), {
    		center: {lat: 22.844700, lng: 78.939206},
        	zoom: 12,
        	mapTypeId : google.maps.MapTypeId.ROADMAP,
        	disableDefaultUI: true,
        	styles: [{"featureType":"all","elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#000000"},{"lightness":40}]},{"featureType":"all","elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#000000"},{"lightness":16}]},{"featureType":"all","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#000000"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#000000"},{"lightness":17},{"weight":1.2}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":20}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":21}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#000000"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#000000"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":16}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":19}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":17}]}]
      	});
    	
    	function interio() {
    		$.getJSON('json1', function(data) {
    		   	for (var i = 0; i < data.feed.entry.length; i++) {
    		    	var merker = new google.maps.Marker({
    					position: new google.maps.LatLng(data.feed.entry[i].gsx$lat.$t,data.feed.entry[i].gsx$longitude.$t),
    		   			map: map,
    		   			icon: "images/interio-marker.png"
    		   		});
    			}
    		});
    	}
    	function lock() {
    		$.getJSON('json2', function(data) {
    	   		for (var i = 0; i < data.feed.entry.length; i++) {
    	    		var merker = new google.maps.Marker({
    					position: new google.maps.LatLng(data.feed.entry[i].gsx$lat.$t,data.feed.entry[i].gsx$longitude.$t),
    		   			map: map,
    	   				icon: "images/lock-marker-png.png"
    	   			});
    			}
    	   	});
    	}

    	function mhe() {
    		$.getJSON('json3', function(data) {
    		   	for (var i = 0; i < data.feed.entry.length; i++) {
    		    	var merker = new google.maps.Marker({
    					position: new google.maps.LatLng(data.feed.entry[i].gsx$lat.$t,data.feed.entry[i].gsx$longitude.$t),
    		   			map: map,
    		   			icon: "images/mhe-png.png"
    		   		});
    			}
    		});
    	}

    	function appliance() {
    		$.getJSON('json4', function(data) {
    		   	for (var i = 0; i < data.feed.entry.length; i++) {
    		    	var merker = new google.maps.Marker({
    					position: new google.maps.LatLng(data.feed.entry[i].gsx$latitude.$t,data.feed.entry[i].gsx$longitude.$t),
    		   			map: map,
    		   			icon: "images/appliance-marker.png"
    		   		});
    			}
    		});
    	}

        	//current location
    	if (navigator.geolocation) {
       		navigator.geolocation.getCurrentPosition(function(position) {
       			var pos = {
           		lat: position.coords.latitude,
           		lng: position.coords.longitude
       			};
       			var marker = new google.maps.Marker({
       				position: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
       				map: map,
       				icon: 'images/blue.png'
       			});
       			map.setCenter(pos);
       		}, function() {
       			handleLocationError(true, infoWindow, map.getCenter());
       		});


       		$("input[name = 'mapButton']").on('click', function() {
       			if(($("#interio").is(':checked') === true) && ($("#lock").is(':checked') === true)) {
       				interio();
       				lock();
       			} else if (($("#interio").is(':checked') === true) && ($("#mhe").is(':checked') === true)) {
       				interio();
       				mhe();
       			} else if (($("#interio").is(':checked') === true) && ($("#appliance").is(':checked') === true)) {
       				interio();
       				appliance();
       			} else if (($("#interio").is(':checked') === true) && ($("#lock").is(':checked') === true) && ($("#mhe").is(':checked') === true)) {
       				interio();
       				lock();
       				mhe();
       			} else if (($("#interio").is(':checked') === true) && ($("#lock").is(':checked') === true) && ($("#appliance").is(':checked') === true)) {
       				interio();
       				lock();
       				appliance();
       			} else if(($("#interio").is(':checked') === true) && ($("#mhe").is(':checked') === true) && ($("#appliance").is(':checked') === true)) {
       				interio();
       				mhe();
       				appliance();
       			} else if (($("#interio").is(':checked') === true) && ($("#lock").is(':checked') === true) && ($("#mhe").is(':checked') === true) && ($("#appliance").is(':checked') === true)) {
       				interio();
       				lock();
       				mhe();
       				appliance();
       			}
       			
       		});

    	} else {
       		// Browser doesn't support Geolocation
       		handleLocationError(false, infoWindow, map.getCenter());
    	}

      	function handleLocationError(browserHasGeolocation, infoWindow, pos) {
     		infoWindow.setPosition(pos);
      		infoWindow.setContent(browserHasGeolocation ?
                            'Error: The Geolocation service failed.' :
                            'Error: Your browser doesn\'t support geolocation.');
    	}
    };

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

});
html, body {
	margin: 0px;
	padding: 0px;
  background-color: black;
}

.row {
  max-width: 100% !important;
  margin-left: auto;
  margin-right: auto;
  max-width: initial;
}

.leftSidebar {
  margin-top: 30px;
  margin-left: 10px;
  padding: 0px;
  background-color: black;
}

.leftSidebar img {
  width: 250px;
  height: 120px;
}

.textLogo {
	margin-top: 80px;
  color: #EF3753;
  font-weight: 400;
  font-style: normal;
  font-size: 40px;
  font-family: 'PT Serif', serif;
  line-height: 36px;
  text-shadow: 1px 1px 0px #D21F02;
}

.compLogo {
  color: #C4C4C4;
  margin-top: 80px;
  font-weight: 400;
  font-style: normal;
  font-size: 40px;
  font-family: 'PT Serif', serif;
  line-height: 36px;
  text-shadow: 1px 1px 0px #cccccc;
}

.custom-button {
  background-color: #EF3753;
}

.custom-button:hover, .custom-button:focus {
  background-color: rgb(158, 34, 54);
}

#map {
    display:block;
    width:100%;
    height:700px;
  }

div label input {
   margin-right:100px;
}
body {
    font-family:sans-serif;
}

#ck-button {
    margin:4px;
    background-color:#EF3753;
    overflow:auto;
    float:left;
}

#ck-button label {
    float:left;
    width:6.0em;
}

#ck-button label span {
    text-align: center;
    padding: 12px 0px;
    display: block;
}

#ck-button label input {
    position:absolute;
    left:-100px;
}

#ck-button input:hover + span {
    background-color:#9E2236;
}

#ck-button input:checked + span {
    background-color:#9E2236;
    color:#fff;
}

#ck-button input:checked:hover + span {
    background-color:#EF3753;
    color:#fff;
}
<div id="ck-button">
	<label>
	<input type="checkbox" name="mapButton" value="1" title="Godrej Interio" id="interio"><span><img src="images/interior.png" alt="Interio" checked></span>
	</label>
</div>
<div id="ck-button">
	<label>
	<input type="checkbox" name="mapButton" value="2" title="Godrej Lock" id="lock"><span><img src="images/lock.png"></span>
	</label>
</div>
<div id="ck-button">
	<label>
	<input type="checkbox" name="mapButton" value="3" title="Godrej Material Handling" id="mhe"><span><img src="images/Material-handling.png"></span>
	</label>
</div>
<div id="ck-button">
	<label>
	<input type="checkbox" name="mapButton" value="4" title="Godrej Appliances" id="appliance"><span><img src="images/appliance.png"></span>
	</label>
</div>

最佳答案

切换不应加载带有标记的文件,它应该只执行 setMap(map) 或 setMap(null)。

这是您正在寻找的效果的示例(我想)

所以,我测试了2个数据文件; 4. 看第 15 行,看第 32 行(开关),由你决定

我的数据文件:

json1.txt

[{"lat": 50.0, "lng": 4.0},{"lat": 50.1, "lng": 4.0},{"lat": 50.2, "lng": 4.0},{"lat": 50.3, "lng": 4.0}]

json2.txt

[{"lat": 50.0, "lng": 4.2},{"lat": 50.1, "lng": 4.2},{"lat": 50.2, "lng": 4.2},{"lat": 50.3, "lng": 4.2}]

脚本,index.php:

<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var map;
var markerSets = [];  // this will be an array of arrays of markers
function initMap() {
  // create map
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: new google.maps.LatLng(50.5, 4.5),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // load the markers
  loadMarkers('json1.txt', createMarkers);
  loadMarkers('json2.txt',  createMarkers);
  //loadMarkers('json3.txt',  createMarkers);
  //loadMarkers('json4.txt',  createMarkers);
}

function loadMarkers(url, successCallback) {
  // make the ajax call
  $.ajax({
    url: url,
    dataType: 'json',
    success: successCallback // so, this will be function createMarkers
  });

}
function createMarkers(locations) {
  // now, we look at the request url to get the class / icon / ...
  switch(this.url) {
    case 'json1.txt': 
      var icon = 'interio-marker.png'; 
      var className = 'json1';
      var index = 0;
      break;
    case 'json2.txt': 
      var icon = 'lock-marker-png.png'; 
      var className = 'json2';
      var index = 1;
      break;
  }
  markerSets[index] = [] ;  
  for(var i in locations) {
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
      icon: 'images/' + icon,
      title: 'Set: ' + index + ' - Class: ' + className + ' - item: ' + i,
      map: map
    });
    markerSets[index].push(marker);
  }
  // create checkbox
  $('#checkboxes').append('<input checked="checked" onclick="toggle(this, ' + index + ')" type="checkbox"> ' + className + '<br>');
}
function toggle(checkbox, index) {
  for(var i in markerSets[index]) {
    if(checkbox.checked) {
      markerSets[index][i].setMap(map);
    }
    else {
      markerSets[index][i].setMap(null);
    }
  }
}

google.maps.event.addDomListener(window, 'load', initMap);
</script>
<style>
#map {
  height: 400px;
}
</style>
<div id="map"></div>
<div id="checkboxes"></div>

关于javascript - 从多个 JSON 文件中切换复选框选择标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33840310/

相关文章:

javascript - 将数据从 Android 代码传递到从外部 URL 加载的 Javascript 方法?

javascript - 当列表中存在重复值时显示警报消息

javascript - HTML 追加 jQuery

php - 数组作为 Laravel 表单中的输入(提交功能不起作用)

json - 从http请求解码json时出现EOF错误

Django 中的 Javascript 模块管理(已关闭)

javascript - Chrome 扩展上的旧 CSS 闪烁

javascript - IE 使用 Jquery UI 显示 .dialog 模式框时出现问题

javascript - JSON.stringify() 无法工作

php - 将 JSON 输出保存到 json 文件