隐藏和显示所有标记

时间:2015-07-26 21:28:52

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

我正在构建一个使用angular来调用并将数据设置到网页和谷歌地图上的地图。

这是我的第一个使用角度的大项目,我几乎按照我的设想工作。我想为网站添加其他功能,使其更加用户友好。

View the working code.

View code on github.

我设置了两个按钮来隐藏或显示所有标记,但我得到的错误是clearMarkers,showMarkers和allSetMap未定义。 Onclick,我需要这些按钮才能:

在信息窗口打开的情况下隐藏除标记之外的所有标记 显示所有标记 我还想添加代码以删除折线,并在用户单击“清除方向”按钮,顶部图像栏中的一个选项或隐藏/显示标记按钮时将所有标记恢复为原始状态。

非常感谢您提供的任何帮助或指导!更简单的代码,建议,方向越好,因为我显然仍然是一个初学者。福克斯鼓励。我真的想学习这个并正确编码。任何指导都非常感谢。

这是数据和地图的html代码:

<!doctype html>
<html ng-app="mapApp" lang="en">
<head>
<meta content="width=device-width, initial-scale=1" name="viewport">
<meta charset="utf-8">
<title>Map || Portland Streetcar Bars</title>
<meta name="description" content="Map of Portland's Eastside Streetcar Bars">
<meta name="viewport" content="width=device-width">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory    -->
<!-- build:css(.) styles/vendor.css -->
<!-- bower:css -->

<!-- endbower -->
<!-- endbuild -->
<!-- build:css(.tmp) styles/main.css -->

<link rel="stylesheet" href="../../../styles/map-styles.css"> 
<link rel="stylesheet" href="../../styles/mapAppStyles.css">
<link type="text/css" rel="stylesheet" href="../../styles/waitMe.css"><!--  
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> -->  
<script src="../../scripts/lib/modernizr-2.5.3.js"></script>
<script src="../../scripts/modernizr.custom.js"></script>

<script src="//use.typekit.net/kgp0loa.js"></script>
<script>try{Typekit.load();}catch(e){}</script>
<link rel="icon" 
  type="image/png" 
  href="http://portlandstreetcarbars.com/favicons/favicon.ico">

<!-- endbuild -->
</head>
<body>
<!--[if lt IE 7]>
  <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->

<!-- Add your site or application content here -->
     <!--  Menu Header  -->
<section class="module parallax parallax-1-inner">
<div class="container">
<header>
  <nav id="dl-menu" class="dl-menuwrapper">
      <button class="dl-trigger">Open Menu</button>
      <ul class="navMenu dl-menu">
        <li><a class="hvr-shutter-out-horizontal" href="/">HOME</a>  </li>
        <li><a class="hvr-shutter-out-horizontal" href="/streetcar-bars-list/">BAR LIST</a></li>
        <li><a class="hvr-shutter-out-horizontal" id="current" href="#">MAP</a></li>
        <li><a class="hvr-shutter-out-horizontal" href="/streetcar-bars-crawls/">CRAWLS</a></li>
        <li><a class="hvr-shutter-out-horizontal" href="/streetcar-bars-join/">CONTACT</a></li>
      </ul>
   </nav>
   <div class="clear"></div>
   <div class="header-inner">Portland<span> Streetcar Bars</span></div>
  <div class="inner-eastside-font-effect"><em>Eastside</em></div>
</header> 
</div>
</section>
<div class="clear"></div>
  <section class="module parallax parallax-2">
    <div class="container">
     <h2>Get Directions to Your Next Stop</h2>
     </div>
</section>  
<div ng-view=""></div> 

<div class="clear"></div>
<section class="module parallax parallax-2">
    <div class="container">
      <h2>Featured Stops on the Portland Streetcar</h2>
     </div>
</section>  


 <!-- build:js(.) scripts/oldieshim.js -->
 <!--[if lt IE 9]>
 <script src="bower_components/es5-shim/es5-shim.js"></script>
 <script src="bower_components/json3/lib/json3.js"></script>
 <![endif]-->
 <!-- endbuild -->
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCdOS0Bctn6co9d2ZaecN-LNrU5yi3eoXQ&sensor=true&libraries=places,drawing,geometry"></script>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <!-- build:js(.) scripts/vendor.js -->
 <!-- bower:js -->
 <script src="bower_components/jquery/dist/jquery.js"></script>
 <script src="bower_components/angular/angular.js"></script>
 <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
 <script src="bower_components/angular-animate/angular-animate.js"></script>
 <script src="bower_components/angular-cookies/angular-cookies.js"></script>
 <script src="bower_components/angular-resource/angular-resource.js"></script>
 <script src="bower_components/angular-route/angular-route.js"></script>
 <script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
 <script src="bower_components/angular-touch/angular-touch.js"></script>
 <script src="bower_components/angular-ui-map/ui-map.js"></script>
 <script src="bower_components/angular-ui-utils/ui-utils.js"></script>

 <!-- endbower -->
 <!-- endbuild -->

    <!-- build:js({.tmp,app}) scripts/scripts.js -->

<script src="scripts/app.js"></script>
<script src="scripts/controllers/controllers.js"></script>      
<script src="scripts/directives/directives.js"></script> 

    <!-- endbuild -->

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="../../scripts/waitMe.js"></script> 
<script src="../../scripts/jquery.dlmenu.js"></script>

<script>
  $(function(){
      var url = window.location.href; 
      $(".navMenu a").each(function() {
          if(url == (this.href)) { 
              $(this).closest("a").addClass("current");
          }
      });
  });
  (function(){
      var parallax = document.querySelectorAll(".parallax"),
        speed = 0.35;
    window.onscroll = function(){
        [].slice.call(parallax).forEach(function(el,i){
          var windowYOffset = window.pageYOffset,
            elBackgrounPos = "0 " + (windowYOffset * speed) + "px";  
          el.style.backgroundPosition = elBackgrounPos;
      });
    };
  })();
  $(function(){
    // none, bounce, rotateplane, stretch, orbit, 
    // roundBounce, win8, win8_linear or ios
    var current_effect = 'bounce'; // 
    function run_waitMe(effect){
    $('#spinHere').waitMe({
      //none, rotateplane, stretch, orbit, roundBounce, win8, 
      //win8_linear, ios, facebook, rotation, timer, pulse, 
      //progressBar, bouncePulse or img
      effect: 'bounce',

      //place text under the effect (string).
      text: 'Getting Directions',

      //background for container (string).
      bg: 'rgba(255,255,255,0.7)',

      //color for background animation and text (string).
      color: '#000',

      //change width for elem animation (string).
      sizeW: '',

      //change height for elem animation (string).
      sizeH: '',

      // url to image
      source: ''

      });
    }  
  });

  $(function() {
    $( '#dl-menu' ).dlmenu({
      animationClasses : { classin : 'dl-animate-in-3', classout : 'dl-animate-out-3' }
    });
  });
</script>

这是我的控制器代码。这是一个烂摊子,但除了我上面提到的问题外,它大部分都有效。

'use strict';

 var markers = [];
 var mapApp = angular.module('mapControllers', []);
 mapApp.controller('ListController', function ($scope, $http) {
 $http.get('scripts/bars.json').
 success(function(data, status, headers, config) {
    //this happens if everything works
    $scope.bars = data;
    $scope.markers = [];
    var bounds = new google.maps.LatLngBounds();
    var myLatlng100 = new google.maps.LatLng(45.523007, -122.657890);
    var mapOptions = {
            center: myLatlng100,
            styles: [{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#e0efef"}]},{"featureType":"poi","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"hue":"#1900ff"},{"color":"#c0e8e8"}]},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":100},{"visibility":"simplified"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"transit.line","elementType":"geometry","stylers":[{"visibility":"on"},{"lightness":700}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#7dcdcd"}]}],
            zoom: 15,
            draggable: false,
            scrollwheel: false,
            disableDoubleClickZoom: true,
            zoomControl: false             
    };
    var infoWindow = new google.maps.InfoWindow();
     // Create a renderer for directions and bind it to the map.
    var rendererOptions = {
            map: $scope.map
    };
    var directionsDisplay;
    var directionsService;
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    $scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
    directionsDisplay.setMap($scope.map);

    $scope.openInfoWindow = function(e, selectedMarker){
        e.preventDefault();
        google.maps.event.trigger(selectedMarker, 'click');
    }; 
    var createMarker = function(bar){
        var marker = new google.maps.Marker({
            map: $scope.map,
            position: new google.maps.LatLng(bar.lat, bar.lng),
            title: bar.name
        });

        marker.content = '<div class="contentString"><img src="' + 
        bar.image +
        '"><br/>'+ 
        bar.address +
        ' ' +  
        '<br /><button id="spinner" class="button" onclick="getDir('+bar.lat+', '+bar.lng+')">Get Directions</button>' +
        '</div>';
        marker.image = bar.image;

        google.maps.event.addListener(bar, 'click', function(){
            infoWindow.setContent('<a class="info-window" href="' + bar.url + '">' +'<h3 class="info-window" >' + bar.name + '</h3>' + '</a>' +  marker.content);
            infoWindow.open($scope.map, marker);
        });
          google.maps.event.addListener(marker, 'click', function(){
            infoWindow.setContent('<a class="info-window" href="' + bar.url + '">' +'<h3 class="info-window" >' + bar.name + '</h3>' + '</a>' +  marker.content);
            infoWindow.open($scope.map, marker);
        });
        google.maps.event.addListener(marker, 'dragstart', function() {
            disableMovement(true);
        });

        google.maps.event.addListener(marker, 'dragend', function() {
            disableMovement(false);
        });         

        $scope.markers.push(marker);
     };  

    $scope.setAllMap = function(map) {
        for (var i = 0; i < $scope.bars.length; i++){
          createMarker($scope.bars[i]);
        }  
    }
    $scope.setAllMap(map); 

    $scope.clearMarkers = function(map) {
        setAllMap(null);
     }
    $(".hideit").on("click", function(map){
           $scope.clearMarkers(); 
       });

    $("#clearPanel").on("click", function(map){
            document.getElementById("panel").innerHTML = " ";
            $('h3.map').show();
            $('#clearPanel').hide();
      });

console.log($scope.bars);
}).
error(function(data, status, headers, config) {
  console.log("Did not compute");
});
});   

function disableMovement(disable) {
var mapOptions;
if (disable) {
    mapOptions = {
        draggable: false,
        scrollwheel: false,
        disableDoubleClickZoom: true,
        zoomControl: false
    };
} else {
    mapOptions = {
        draggable: true,
        scrollwheel: true,
        disableDoubleClickZoom: false,
        zoomControl: true
    };
}
map.setOptions(mapOptions);
}
function getDir(lat,lng,markers,map) {
 run_waitMe();
 document.getElementById("panel").innerHTML = " ";
// If the browser supports the Geolocation API
    if (typeof navigator.geolocation == "undefined") {
      $("#error").text("Your browser doesn't support the Geolocation API");
      return;
    }
     // Save the positions' history
     var path = [];
     navigator.geolocation.getCurrentPosition(function (position) {       //This gets the
        // Create the map
         var myOptions = {
            styles: [{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#e0efef"}]},{"featureType":"poi","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"hue":"#1900ff"},{"color":"#c0e8e8"}]},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":100},{"visibility":"simplified"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"transit.line","elementType":"geometry","stylers":[{"visibility":"on"},{"lightness":700}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#7dcdcd"}]}],
            zoom: 15,
            draggable: false,
            scrollwheel: false,
            disableDoubleClickZoom: false,
            zoomControl: true,
            center : path[0],
            mapTypeId : google.maps.MapTypeId.TRANSIT
          };
        var map = new google.maps.Map(document.getElementById("map"), myOptions);

        var latitude = position.coords.latitude;                       //users current
        var longitude = position.coords.longitude;                    
        var start = new google.maps.LatLng(latitude, longitude);     //Creates variable for map coordinates
           //location
           path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
             // Creates the polyline object
           var polyline = new google.maps.Polyline({
            map: map,
            path: path,
            strokeColor: '#0000FF',
            strokeOpacity: 0.7,
            strokeWeight: 1
           });

        var directionsService = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('panel'));

        var request = {
          origin: start,
          destination: new google.maps.LatLng(lat, lng),
          travelMode: google.maps.DirectionsTravelMode.TRANSIT
        };
        // Removes the overlays from the map, but keeps them in the array
        function clearOverlays() {
          if (markersArray) {
            for (i in markersArray) {
              markersArray[i].setMap(null);
            }
          }
        }             
        directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
               directionsDisplay.setDirections(response);
                $('.waitMe').hide();
                $('h3.map').hide();
                $('#clearPanel').show();
                }
        });
  });
}

// none, bounce, rotateplane, stretch, orbit, 
// roundBounce, win8, win8_linear or ios
var current_effect = 'bounce'; // 

function run_waitMe(effect){
$('#spinHere').waitMe({
    //none, rotateplane, stretch, orbit, roundBounce, win8, 
    //win8_linear, ios, facebook, rotation, timer, pulse, 
    //progressBar, bouncePulse or img
    effect: 'bounce',

    //place text under the effect (string).
    text: 'Getting Directions',

    //background for container (string).
    bg: 'rgba(255,255,255,0.7)',

    //color for background animation and text (string).
    color: '#000',

    //change width for elem animation (string).
    sizeW: '',

    //change height for elem animation (string).
    sizeH: '',

    // url to image
    source: ''

    });
}

1 个答案:

答案 0 :(得分:0)

您的setAllMap()函数仅存在于$scope对象上,但您尝试将其称为全局函数。这可能是您收到错误的一个原因。

// the `map` argument is unused and is thus redundant
$scope.setAllMap = function(map) {
    for (var i = 0; i < $scope.bars.length; i++){
          createMarker($scope.bars[i]);
    }  
}

// passing map does nothing
$scope.setAllMap(map); 

$scope.clearMarkers = function(map) {
    // this only exists on the $scope object
    // so this is why you will get 'setAllMap is undefined'

    // try changing it to $scope.setAllMap()

    // Also, null does nothing
    setAllMap(null);


}