当我将其转换为类时,JavaScript代码不起作用

时间:2019-06-14 14:49:38

标签: javascript

我的代码的目标是显示包含一些标记的地图。

此代码运行正常:

loadMarkers() { // charger la liste des markers en s'appuyant sur la liste des stations
    let req = new XMLHttpRequest();
    req.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Lyon&apiKey=b79a52a433adef0fc100cd73fedf36710122f4ab');
    req.addEventListener('load', function() {
        if (req.status >= 200 && req.status < 400) {
            mapbikes.contentstation(req.responseText);
        } else {
            mapbikes.contentstation(req.status);
        }

    });

    req.addEventListener('error', function() { // affichage d'un message d'erreur si jcdecaux ne répond pas.
        console.log("erreur de connexion");
    });

    req.send();
},

contentstation(response) { // affichage pour chaque marker, des inforamtions d'une station de vélos
    response = JSON.parse(response);
    response.forEach(function (info) {
        L.marker([info.position.lat, info.position.lng], {
            "jcdecauxInfo": info
        })
        .on('click', mapbikes.onMarkerClick) // Clic sur un marker
        .addTo(mapbikes.mapbikes)
        .bindPopup(
            `<div class="text-success"><h5>Station de Vélo'v</h5></div><h6>` +  info.name + `</h6>` +
            info.address + `<br>` + `<i class="fas fa-bicycle"></i>&nbsp;&nbsp;<strong>` + info.available_bikes + `&nbsp;vélo(s) disponible(s)</strong>`
        );
    });
},

但是当我创建类时,当我转换为代码时,则它不起作用:


class Mapbikes { // propriétés de la carte
    constructor() {
        this.lat = 45.757192;
        this.lng = 4.840495;
        this.zoom =  15;
        this.mapContainer = 'mapid';
        this.mymap = '';
        this.displayMap = '';
        this.addTo = '';
        this.idMap = 'mapbox.streets';
        this.accessToken = 'pk.eyJ1IjoiNzZzZWJhc3RpZW4iLCJhIjoiY2p3czd4dWNmMGtzbjQ5cDVscmhienQ2YyJ9.4jK_HgpV9ObUTqYmBeVtdg';
        this.layer = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}';
        this.attribution = 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
            '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>';
    }

    init() { // affichage de la carte de Lyon, vide
        this.mapbikes = L.map(this.mapContainer, {
            center: [this.lat, this.lng],
            zoom: this.zoom,
        })
    }

    display() {  // affichage du Layer mapbox.com
        L.tileLayer(this.layer, {
            id: this.idMap,
            maxZoom: 18,
            attribution: this.attribution,
            accessToken: this.accessToken,
        }).addTo(this.mapbikes);

        this.loadMarkers();
    }

    loadMarkers() { // charger la liste des markers en s'appuyant sur la liste des stations
        let req = new XMLHttpRequest();
        req.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Lyon&apiKey=b79a52a433adef0fc100cd73fedf36710122f4ab');
        req.addEventListener('load', function() {
            if (req.status >= 200 && req.status < 400) {
                Mapbikes.contentstation(req.responseText);
            } else {
                Mapbikes.contentstation(req.status);
            }
        });

        req.addEventListener('error', () => { // affichage d'un message d'erreur si jcdecaux ne répond pas.
            console.log("erreur de connexion");
        });

        req.send();
    }

    contentstation(response) { // affichage pour chaque marker, des inforamtions d'une station de vélos
        response = JSON.parse(response);
        response.forEach(info => {
            L.marker([info.position.lat, info.position.lng], {
                "jcdecauxInfo": info
            })
            .on('click', Mapbikes.onMarkerClick) // Clic sur un marker
            .addTo(Mapbikes.mapbikes)
            .bindPopup(
                `<div class="text-success"><h5>Station de Vélo'v</h5></div><h6>` +  info.name + `</h6>` +
                info.address + `<br>` + `<i class="fas fa-bicycle"></i>&nbsp;&nbsp;<strong>` + info.available_bikes + `&nbsp;vélo(s) disponible(s)</strong>`
            );
        });
    }

我在控制台中遇到此错误:

TypeError:Mapbikes.contentstation不是函数

我已经尝试在Mapbikes.contentstation(req.responseText)上使用bind; 但这不起作用。

我该如何纠正?

谢谢

2 个答案:

答案 0 :(得分:2)

欢迎堆栈溢出,您可以尝试以下操作:

  loadMarkers() { // charger la liste des markers en s'appuyant sur la liste des stations
    const me = this;
    let req = new XMLHttpRequest();
    req.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Lyon&apiKey=b79a52a433adef0fc100cd73fedf36710122f4ab');
    req.addEventListener('load', function () {
      if (req.status >= 200 && req.status < 400) {
        me.contentstation(req.responseText);
      } else {
        me.contentstation(req.status);
      }
    }

您也可以尝试提供arrow function作为回调,因为这会自动绑定到当前实例,但是箭头功能是ES6和not supported in every browser

答案 1 :(得分:0)

loadMarkers方法中,而不是调用:

Mapbikes.contentstation(req.responseText);

您应该这样称呼它:

this.contentstation(req.responseText);