首页 > 解决方案 > 如何在我的所有课程中使用 API 结果?

问题描述

我用一种方法创建了一个JSMapController,该方法调用API JC Decaux. 在成功的情况下,此方法initJcDecaux()在谷歌地图上创建不同的标记。但我会将结果分配$ajax()给我的公共财产this.data。我尝试了这段代码,但它并不好......如果有人可以帮助我?谢谢你。

class MapController {
  constructor(mapIdPosition) {
    this.mapIdPosition = mapIdPosition;
    this.position = {lat: 43.6009272, lng: 1.4452841};
    this.zoom = 14;
    this.markers = [];
    this.data = [];
  }

  initMap() {
    this.map = new google.maps.Map(document.getElementById(this.mapIdPosition), {
      center: this.position,
      zoom: 5,
    })
    this.map.setZoom(this.zoom);
  }

  initJcDecaux() {
    $.ajax({
      url: 'https://api.jcdecaux.com/vls/v1/stations?contract=Toulouse&apiKey=6d8e030000000000000000000000000000',
      type: 'GET',
      datatype: 'json',
      success: function(data) {
        this.data = data;
        data.forEach(this.addMarkerOnMap.bind(this));
        var markerCluster = new MarkerClusterer(this.map, this.markers,
            {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
      }.bind(this)

    })
  }

  addMarkerOnMap(data) {
    this.marker = new google.maps.Marker({
      position: data.position,
      map: this.map,
      title: '',
    })
    this.markers.push(this.marker);
  }
};

const map1 = new MapController('map');
map1.initMap();
map1.initJcDecaux();
console.log(map1.data);

标签: javascriptapiclass

解决方案


推荐阅读