دنبال کننده ها

۱۳۹۶ دی ۱۲, سه‌شنبه

html - Mapbox: Why isn't my for loop calling in the list of locations to the flyTo function? "...addEventListener is not a function"

[ad_1]



I am trying to create multiple flyTo buttons corresponding to different views, using a for loop to run through all views, rather than repeating the function for each view.



I am doing this by populating a list with the button names, so I can call this in to the for loop containing the flyTo function.



Problems occur in this loop, where I get the error "Uncaught TypeError: names[i].addEventListener is not a function".



I have tried calling elements[i].addEventListener... instead, but then get an error "Uncaught TypeError: Cannot read property 'center' of undefined at HTMLButtonElement."



This error is removed when "center: views[i].center" is replaced with "center: views[0].center", or any specific view - and all buttons fly to this one view.



I think I have everything there for it to work, but something is not right with the method and I'm struggling to solve it. I think there should be only one for loop, which creates a list of button names and links these to the views. Any help would be greatly appreciated - here is a link to my code:



http://jsfiddle.net/bsbdyvrv/2/



<div id='map' class="myMap"></div>

<!-- View buttons -->
<div id='console'>
<button class="location" name='loc 1' id='v1'>View 1</button>
<button class="location" name='loc 2' id='v2'>View 2</button>
<button class="location" name='loc 3' id='v3'>View 3</button>
</div>

<script>

// Mapboxgl demo app
'use strict';
var map;
mapboxgl.accessToken = 'pk.eyJ1IjoiYmVuamFtaW4td3lzcyIsImEiOiJVcm5FdEw4In0.S8HRIEq8NqdtFVz2-BwQog';

// init the map
map = new mapboxgl.Map(
container: 'map',
style: 'https://www.mapbox.com/mapbox-gl-styles/styles/outdoors-v7.json',
center: [-1.83, -78.183],
zoom: 5.5,
);

var views = [
name: "View 1",
zoom: 10,
pitch: 0,
bearing: 0,
center: [-0.33,-78.49],
,

name: "View 2",
zoom: 10,
pitch: 0,
bearing: 0,
center: [-1.04,-79.43],
,

name: "View 3",
zoom: 10,
pitch: 0,
bearing: 0,
center: [-2.19,-78.11],
,

];


// Populate list with button names
var elements = document.getElementsByClassName('location');
var names = '';
for(var i=0; i<elements.length; i++)
names += elements[i].name;

document.write(names);

// For each button, fly to corresponding view
for(var i=0; i<elements.length; i++)
names[i].addEventListener('click', function ()
map.flyTo(
center: views[i].center
// zoom: app.views[i].zoom,
// pitch: app.views[i].pitch,
// bearing: app.views[i].bearing
);
);
;
</script>



[ad_2]

لینک منبع