如何使用angularjs过滤google-map-markers?

时间:2015-09-09 09:39:45

标签: javascript angularjs google-maps google-maps-api-3 google-maps-markers



.controller('MapCtrl', [
        '$scope', '$http', '$location', '$window', '$filter', '$ionicLoading', '$compile','$timeout','$ionicPopup',
        function($scope, $http, $location, $window, $filter, $ionicLoading, $compile, $timeout,$ionicPopup) {
	$scope.favoriteStore = '';
    $scope.Storetype = [{
        name: "Nokia"
    }, {
        name: "Samsung"
    }];
	$scope.submit =function()
	{
        if($scope.favoriteStore == 'Nokia') {
            alert($('#nokia').val());
        } else {
            alert($('#samsung').val());
        }
	
	
	}  
            $http.get('*****').success(function(data, dealers, response) {
                function initialize() {
                    var serverData = data;
                    $scope.locations = [];
                    for (var i = 0; i < serverData.length; i++) {
                var modal = [
                data[i].Store_Name, data[i].S_Location.Latitude, data[i].S_Location.Longitude, i, 'images/arrow.svg', data[i]._id,data[i].Store_Type,data[i].Services];
                $scope.locations.push(modal); 
            }
					var locations = [
                ['Sakthi Nokia Store', '12.901599', '77.594563', '1', 'images/arrow.svg.svg', '55a78953815356700bee698f','Nokia','Interior Services,Exterior Services,Regular Services & Maintenance'],
                ['Google Mobile Center', '12.9165534', '77.5474802', '2', 'images/arrow.svg.svg', '55a786d1815356700bee6982','Nokia,Samsung','Software problem & updates,Interior Services'],
				['Zig zag mobiles', '12.9033434', '77.5574802', '3', 'images/arrow.svg.svg', '55a786d1815356700bee6982','Samsung','Hardware Problem,Interior Services,Exterior Services,Other Services'],
				['Guptha mobile Corner', '12.9165534', '77.5456742', '4', 'images/arrow.svg.svg', '55a786d1815356700bee6982','Nokia,Samsung','Regular Services & Maintenance'],
				];

                    var map = new google.maps.Map(document.getElementById('map'), {
                        zoom: 13,
                        center: new google.maps.LatLng(12.9667, 77.5667),
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    });



                    var marker, i;

                    for (i = 0; i < $scope.locations.length; i++) {

                        marker = new google.maps.Marker({
                            position: new google.maps.LatLng($scope.locations[i][1], $scope.locations[i][2]),
                            map: map,
                            icon: $scope.locations[i][4],
                            animation: google.maps.Animation.DROP,

                        });


                        google.maps.event.addListener(marker, 'click', (function(marker, i) {
                            return function() {


                                var compiled = $compile('<div><div>' + $scope.locations[i][0] + ' </div><div>' + $scope.locations[i][1] + ' </div><div>' + $scope.locations[i][2] + ' </div><div><button ng-click="getid(locations[' + i + '][5])">Get</button></div></div>')($scope);

                                var infowindow = new google.maps.InfoWindow({
                                    content: compiled[0]
                                });


                                infowindow.open(map, marker);
                                $scope.$apply();

                            }

                        })(marker, i));
                    }
                    
                    $scope.getid = function(id) {
					console.log(id)
                        
                    }

                    
                    $scope.map = map;
                }

                
            });
			}
		
    ])
&#13;
<script type='text/javascript' src='https://fiddle.jshell.net/js/lib/dummy.js'></script>
<script type='text/javascript' src="https://code.jquery.com/jquery-2.0.2.js"></script>
<script type='text/javascript' src="https://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" type="text/css" href="https://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css">
<link rel="stylesheet" type="text/css" href="https://davidstutz.github.io/bootstrap-multiselect/docs/css/bootstrap-3.3.2.min.css">
<script type='text/javascript' src="https://davidstutz.github.io/bootstrap-multiselect/docs/js/bootstrap-3.3.2.min.js"></script>
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.1/angular.js"></script>
<ion-content ng-controller="MapCtrl">
 <form data-ng-submit="submit()">
    <ul>
        <li ng-repeat="store in Storetype">
            <label>{{store.name}}
                <input type="radio" name="storetype" ng-model="$parent.favoriteStore" value="{{store.name}}" />
            </label>
        </li>
    </ul>
 <div ng-show="favoriteStore == 'Nokia'" style="padding:20px">
    <select id="nokia" multiple="multiple">
      <option value="Interior Services">Interior Services</option>
      <option value="Exterior Services">Exterior Services</option>
      <option value="Regular Services & Maintenance">Regular Services & Maintenance</option>
      <option value="Software problem & updates">Software problem & updates</option>
      <option value="Hardware Problem">Hardware Problem</option>
    </select>
     <br /><br />
    <input type="submit" id="btnget" value="submit" />
</div>
<div ng-show="favoriteStore == 'Samsung'" style="padding:20px">
   <select id="samsung" multiple="multiple">
     <option value="Interior Services">Interior Services</option>
     <option value="Exterior Services">Exterior Services</option>
     <option value="Regular Services & Maintenance">Regular Services & Maintenance</option>
     <option value="Software problem & updates">Software problem & updates</option>
     <option value="Hardware Problem">Hardware Problem</option>
     <option value="Other Services">Other Services</option>
    </select>
    <br /><br />
   <input type="submit" id="btnget" value="Submit" />
</div>
</form>
  <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  <div id="map" data-tap-disabled="true"></div>
  </ion-content>
<script type='text/javascript'>//<![CDATA[

$(function() {
  $('#nokia').multiselect({
    includeSelectAllOption: true
  });
  
  $('#samsung').multiselect({
    includeSelectAllOption: true
  });
});

</script>
&#13;
&#13;
&#13;

我附上了我的代码。我有四个商店,它在谷歌地图中正确显示,但我想根据选择过滤谷歌地图标记。我有商店类型和他们的服务,我需要根据这两个过滤。我有两个单选按钮,分别是诺基亚和三星。依赖于单选按钮选择服务后,提交我需要的按钮来过滤地图标记。例如:

案例1:在单选按钮用户选择的诺基亚和该服务列表用户已检查内部服务并提交。诺基亚我需要检查数据[i] .Store_Type和内部服务我需要检查数据[i] 。服务

对于这种情况的答案它应该只显示两个标记1.Sakthi Nokia Store,2.Google Mobile Center

案例2:在单选按钮用户选择的诺基亚和该服务列表用户已检查内部服务,常规服务&amp;维护和提交。诺基亚我需要检查数据[i] .Store_Type和内部服务,常规服务&amp;维护我需要检查数据[i]。服务

回答这个案例它应该只显示两个标记1.Sakthi Nokia Store,2.Google Mobile Center3.Guptha mobile Corner

案例3:在单选按钮用户选择三星和该服务列表用户已检查内部服务并提交。所以三星我需要检查数据[i] .Store_Type和内部服务我需要检查数据[i] 。服务

对于这种情况的答案它应该只显示两个标记1.Google Mobile Center 2.Zig zag mobiles请一些人帮我解决这个谷歌地图api和angularjs的新手。

1 个答案:

答案 0 :(得分:0)

我有一个答案,但这是纯js,您可以通过单选按钮过滤标记。

我在俄语门户网站here中回答了这个问题。

Google翻译:

在myMarkers对象中将标记分为几组,每个键是组的名称,每个值是其中键是标记头的组对象,而值是标记坐标。

每个组中都有选项,在选项中,您可以设置将应用于每个组标记的任何参数,在此示例中,选项中包含图标和动画。

googleMarkers对象的结构类似于myMarkers,但是它包含Google标记对象,而不包含它们的描述,该对象填充在setMarkers函数中。

单选按钮通过data- *属性绑定到组,这使您可以为元素使用任意id。最初,显示与选中的单选按钮相关的那些标记。带有data-marker =“ showall”的单选按钮将显示所有元素。

其余的内容应该可以理解,代码中包含注释,并使用ES2015。

let map, googleMarkers = {} // карта и объект содержащий объекты гугл маркеров
const radios = document.querySelectorAll('input[type=radio][data-marker]')
const myMarkers = { // описание маркеров
  first: {
    'Title 1': [52.4357808, 4.991315699999973],
  },
  second: { // имя группы
    options: { // опции для маркеров этой группы
      icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png' 
    }, 
    'Title 2': [52.4357808, 4.981315699999973],
    'Title 3': [52.4555687, 5.039231599999994],
  },
  third: {
    options: { 
      icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
      animation: google.maps.Animation.BOUNCE
    },
    'Title 4': [52.4755687, 5.019261599999994],
    'Title 5': [52.4555687, 5.049231599999994],
    'Title 6': [52.4055687, 5.039236599999994]
  }
}

initMap()
// для каждой радио-кнопки добавляет слушатель события клика
radios.forEach(i => i.addEventListener('click', radioClick))


function initMap() {
  const center = new google.maps.LatLng(52.4527808, 4.991315699999973)
  const mapOptions = {
    zoom: 11,
    center,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  }

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions)
  setMarkers(map)
}

function setMarkers (map) {
  let isFirst = true
  for (let group in myMarkers) {
    for (let title in myMarkers[group]) {
      if (title === 'options') // не берет во внимание опции
        continue
   
      const myMarker = myMarkers[group][title]
      const visible = document.querySelector(`input[type=radio][data-marker=${group}]`).checked
      const marker = new google.maps.Marker({
        title,
        position: {lat: myMarker[0], lng: myMarker[1]},
        map,
        visible,
        ...myMarkers[group].options // берет опции группы
      })
      
      googleMarkers[group] = googleMarkers[group] || [] // создает массив если его нет
      googleMarkers[group].push(marker)
    }
  }
}

function radioClick ({ target }) { // берет target события
  const group = target.dataset.marker // id группы к которой принадлежит радио-кнопка
  const arrOfEveryGroup = Object.values(googleMarkers) // массив массивов групп маркеров
  const everyMarker = [].concat.apply([], arrOfEveryGroup) // массив всех маркеров
  
  if (group === 'showall') {
    // показывает всех
    everyMarker.forEach(i => i.setVisible(true))
    return
  }
  // те кто был видимым становиться не видемым
  everyMarker.forEach(i => i.visible && i.setVisible(false))
  
  // показывает группу к которой принадлежит радио-кнопка
  for (let marker of googleMarkers[group])
    marker.setVisible(!marker.visible)
}
#map-canvas { 
  height: 160px;
  width: 100%;
}
#map-canvas img {
  max-width: none;
}
    
#map-canvas div {
  -webkit-transform: translate3d(0, 0, 0);
}
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>


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


<input data-marker="first" id="first" type="radio" name="myMarkers">
<label for="first">First</label>

<input data-marker="second" id="second" type="radio" name="myMarkers" checked>
<label for="second">second</label>

<input data-marker="third" id="third" type="radio" name="myMarkers">
<label for="third">third</label>

<input data-marker="showall" id="showall" type="radio" name="myMarkers">
<label for="showall">Show all</label>