隐藏和显示所有标记
Posted
技术标签:
【中文标题】隐藏和显示所有标记【英文标题】:Hide and Show ALL markers 【发布时间】:2015-10-16 23:50:09 【问题描述】:我正在构建一个地图,它使用角度来调用并将数据设置到网页和谷歌地图上。
这是我第一个使用 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>tryTypekit.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: ''
);
【问题讨论】:
setAllMap()
定义在哪里?
对不起 - 在格式化过程中被错误地删除了。我把它加回来了——它在 clearMarkers 和 showMarkers 函数之上。
@MattHerbstritt:这个问题提到了错误和要添加的额外代码,所以它不适合代码审查。
太棒了。我已经在这里发布了所有代码。谁能看到导致问题的原因?我 99% 的问题是范围问题。但我不知道如何解决它。任何帮助表示赞赏。谢谢!
@MattHerbstritt 请阅读A guide to Code Review for Stack Overflow users,以免再次误导用户。谢谢。
【参考方案1】:
您的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);
【讨论】:
以上是关于隐藏和显示所有标记的主要内容,如果未能解决你的问题,请参考以下文章