我正在开始开发,为了进行练习,我必须使用面向对象编程进行编程。但是我不知道如何调用函数,以及添加函数callback
和onMarkerClick
经过许多教程后,我仍然不明白。谢谢您的帮助。
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stationscontract=xxxxxxxxxx&apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
xhr.addEventListener('load', function() {
if (xhr.status >= 200 && xhr.status < 400) {
callback(xhr.responseText);
} else {
callback(xhr.status);
}
});
xhr.addEventListener('error', function() {
console.log("erreur de connexion");
});
xhr.send(null);
//This part of the code is on another js file
"use strict";
let carte = {
lat: 43.6044,
lng: 1.4442,
zoom: 13,
mapContainer: 'mapid',
displayMap: '',
addTo: '',
idMap: 'mapbox.streets',
accessToken: 'pk.eyJ1IjoidGhyb3VkIiwiYSI6ImNqczRndjIweDA0axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
layer: 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}',
attribution: 'Map data © <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: function() {
this.mymap = L.map(this.mapContainer, {
center: [this.lat, this.lng],
zoom: this.zoom,
})
},
display: function() {
L.tileLayer(this.layer, {
id: this.idMap,
maxZoom: 18,
attribution: this.attribution,
accessToken: this.accessToken,
}).addTo(this.mymap);
},
callback: function(response) {
response = JSON.parse(response);
response.forEach(function(info) {
L.marker(
[info.position.lat, info.position.lng], {
"jcdecauxInfo": info
}
)
.on('click', onMarkerClick)
.addTo(this.mymap)
.bindPopup(info.name);
});
}
onMarkerClick: function(arg) {
let marker = arg.target;
let info = marker.options.jcdecauxInfo;
let address = info.address;
let bikeStands = info.bike_stands;
let availableBikes = info.available_bikes;
let statusStation = info.status;
document.getElementById("info-station").style.display = "block";
document.getElementById("adresse-station").innerText = address;
document.getElementById("place-libre").innerText = bikeStands;
document.getElementById("velo-dispo").innerText = availableBikes;
document.getElementById("etat-station").innerText = statusStation;
};
答案 0 :(得分:1)
如果您将函数另存为道具carte
,则可以像这样调用函数:
carte.init()
顺便说一句,您的代码中存在以下错误:
,
的函数后没有callback
:carte
对象。let carte = {
callback : function(response) {
// ...
}
// ↑ you need a , here!!!
onMarkerClick : function(arg) {
// ...
}
// no ; here!!!
};
// ↑ you need to close `carte` here