Я хочу, чтобы bindPopup получал информацию из класса в файле component.ts - PullRequest
0 голосов
/ 15 апреля 2020

Я работаю с Angular 8 и Leaflet. У меня есть маркеры с индивидуальным значком для отображения ресторанов, которым я звоню с помощью Yelp API. Я пытаюсь навести курсор на значки и отобразить название ресторана и рейтинги. Я попытался заполнить options привязкой данных, но это не сработало. Я не знаю, как показать информацию о ресторане. Я пытался даже в моем leafMap.component.ts файле передать параметры в bindPopup в моей CityMap функции или InitMap, но это тоже не сработало. Это мой leafMap.component.ts файл

    import { Component, OnInit, AfterViewInit, Input, OnChanges } from '@angular/core';
import * as L from 'leaflet';

import { YelpService } from '../yelp.service';
import { Business } from '../businessModel';
import { Router, Routes } from '@angular/router';

import { restMarker } from '../marker';
import { CityClickService } from '../city-click.service';

import { InfoPanelService } from '../info-panel.service';

@Component({
  selector: 'app-leaf-map',
  templateUrl: './leaf-map.component.html',
  styleUrls: ['./leaf-map.component.scss']
})

export class LeafMapComponent implements OnInit {


  //create object for business
  business: Business[] = [];
  private map: L.Map;
  markers: L.Marker[];
  city:String;
  coordinates: object;

  Icon = L.icon({
    iconUrl: '../assets/img/Minilogo.png',

    iconSize: [35,35]
  });

  LocationMarker = L.Marker.extend({

    options: {
      icon: this.Icon,
      title: String,
    },

    setLocation: function(business: Business) {
      this.business = business;
    },

    getLocation: function(): Business{
      return this.business;
    },

    bindPopup: function ( options) {
      this.LocationMarker.bindPopup( options);
      return this;
    },

    setPopupContent: function (content) {
      this.LocationMarker.setPopupContent(content);
      return this;
    },

    unbindPopup: function () {
      this.LocationMarker.unbindPopup();
      return this;
    }

  });


  constructor(public infoPanelService: InfoPanelService, public yelpService : YelpService, public CityClickService : CityClickService) {
    this.city = 'denver';
    // this.coordinates = {'lat' :40.014984, 'long':-105.270546};

  }

  getSearchBusiness(city): void {
    this.yelpService.getSearchBusiness(city)
    .subscribe(data => {
      this.business = data;
      console.log(this.business);
    },
    error => {
      console.log(error);
    });
  }

  setCity(city): void{
    this.CityClickService.setCity(city)
    console.log('this city is set ', city);
  }

  getCity() {
    this.city = this.CityClickService.getCity();
    console.log('Get city: ', this.city)
    return this.city;
  }

  getCoordinate(city){

    this.coordinates = this.CityClickService.getCity_Coordinates(city);
    console.log("coordinate", this.coordinates['lat']);
    return this.coordinates;

  }


  // console.log("This city is clicked " + this.getCity());
  private initMap(): void {
    // Setting location to Boulder
    this.markers = [];
    this.map = L.map('map').locate({setView: true, maxZoom:8});

    var latLon = L.latLng(40.016984,-105.270546);
    var bounds = latLon.toBounds(10000); // 10000 = metres
    this.map.panTo(latLon).fitBounds(bounds);

    var Esri_WorldTopoMap = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), and the GIS User Community'
    }).addTo(this.map)


    // this.city = city
    this.yelpService.getSearchBusiness('boulder')
    .subscribe(business => {
      business.forEach(function(a) {

        // console.log(a.coordinates['latitude']);

        var am = new this.LocationMarker([a.coordinates['latitude'], a.coordinates['longitude']], {});

        if(a.coordinates['latitude'] != null && a.coordinates['longitude'] != null){

          am.setLocation(a);

          am.on('click', function() {
             this.infoPanelService.add(am.getLocation());
            this.infoPanelService.showPanel();
          }, this);

          this.markers.push(am);
        }
      }, this);

      L.featureGroup(this.markers).addTo(this.map);
    });
  }

  CityMap(city): void {
    // Setting location to Boulder
    // this.city = city;
    this.setCity(city);
    this.getCoordinate(this.getCity());

    this.markers = [];
    if(this.map) {
      this.map.remove();
    }

    this.map = L.map('map').locate({setView: true, maxZoom:8});
    console.log(this.getCity + ' latitude ', this.coordinates['lat']);
    console.log(this.getCity + ' long ', this.coordinates['long']);
    var latLon = L.latLng(this.coordinates['lat'], this.coordinates['long']);
    var bounds = latLon.toBounds(10000); // 10000 = metres
    this.map.panTo(latLon).fitBounds(bounds);


    var Esri_WorldTopoMap = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), and the GIS User Community'
    }).addTo(this.map)


    this.yelpService.getSearchBusiness(this.getCity())
    .subscribe(business => {
      business.forEach(function(a) {

        var am = new this.LocationMarker([a.coordinates['latitude'], a.coordinates['longitude']], {});

        if(a.coordinates['latitude'] != null && a.coordinates['longitude'] != null){

          am.setLocation(a);

          am.on('click', function() {
            this.infoPanelService.add(am.getLocation());
            this.infoPanelService.showPanel();
          }, this);


          this.markers.push(am);
        }
      }, this);

      L.featureGroup(this.markers).addTo(this.map);
    });
  }

  ngOnInit() {
    this.initMap();
    this.getSearchBusiness(this.city);
  }
}

и это мой BusinesModel.ts, где я пытаюсь получить информацию от

    export class Business {
    id: String;
    alias: String;
    name: String;
    image_url: String;
    is_closed: Boolean;
    url: String;
    review_count: Number;
    categories: {
        alias: String;
        title: String;
    };
    rating : Number;
    coordinates: {
        latitude: Number;
        longitude:Number;
    };
    transactions: Object;
    price: String;
    location:{
        address1: String;
        address2: String;
        address3: String;
        city: String;
        zip_code: String;
        country: String;
        state: String;
        display_address: Object;

    };
    phone: String;
    display_phone: String;
    distance: Number;
}

, и это мой yelpservice.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class YelpService {

  constructor(private http: HttpClient) { }

  //get all business in the city you pass
  getSearchBusiness(city: any): Observable<any> {
    var test = this.http.get('http://localhost:3000/business/' + city);
    console.log(test);
    return test;
  }

  //get all business delail of each business by passing id of that business
  getBusinessDetail(id: any): Observable<any> {
    return this.http.get('http://localhost:3000/business/' + id);
  }

  //get all review detail of the business by the id
  getReviewDetail(id: any): Observable<any> {
    return this.http.get('http://localhost:3000/reviews/' + id);
  }
}
...