openstreetmap изменить слой на гуманитарный

Я использую Angular 4 а также Ionic 3 в целях создания приложения содержит OpenStreetMap, Я хочу изменить слой или плитку из standard смотреть на Humanitarian смотреть. Я искал некоторые документы, но я ничего не нашел об изменении слоев для Angular,

Вот мой код TS для страницы содержит карту интеграции:

import 'rxjs/add/operator/filter';

import { Component, NgZone, OnInit, ViewChild, ViewChildren, QueryList } from '@angular/core';

import { NavController, NavParams, MenuController, Platform, Slides, PopoverController, LoadingController } from 'ionic-angular';

import { Geolocation, Geoposition } from '@ionic-native/geolocation';
import { Storage } from '@ionic/storage';

import { MapComponent } from 'angular2-openlayers';
import {  Feature, proj } from 'openlayers';

import { SearchPage } from '../../modules/search/search';
import { SearchService } from '../../modules/search/search.service';


import { Commerce } from './commerces/commerce';
import { CommercesService } from './commerces/commerces.service';

import { Type, Proposition } from './propositions/type';
import { PropositionsService } from './propositions/propositions.service';
import { PropositionsComponent } from './propositions/propositions.component';

import { Boost } from './boost/boost';

import { HOME_ANIMATIONS } from './home-animations';


declare let jQuery:any, ga:any;

@Component({
  selector: 'page-home',
  animations:HOME_ANIMATIONS,
  templateUrl: 'home.html',
  providers: [SearchService, CommercesService, PropositionsService, MapComponent, PropositionsComponent],
})

export class HomePage implements OnInit {


  lat: number = 48.8589;
  lng: number = 2.3469;
  zoom: number = 14;
  defaultPicture: string = 'app/src/assets/images/default.png';

  searchedPlace:Object; // search selected place

  loadedCommerces: Commerce[]=[]; // list of json places
  selectedCommerce:Commerce; // clicked marker

  markers: Commerce[]=[];
  markerDefaultIcon: string = '/app/src/assets/images/marker.png';
  markerActiveIcon: string = '/app/src/assets/images/marker-active.png';

  visibleSlide:boolean=false;
  visibleInfoBox:boolean=false;
  slideTimeout:number=600;

  activeMarkerIndex: number = 0;
  initSlides:boolean=false;

  startPropose:boolean=false;

  selectionType:string="";

  types:Type[]=[];

  selectedproposition:Proposition;

  startBoost:boolean=false;

  boostInformations:Boost;

  startShare:boolean=false;

  startSuggestion:boolean=false;

  loadedSuggestions:boolean=false;
  selectedSuggestion:any=false;

  @ViewChild(Slides) slides: Slides;
  @ViewChild(MapComponent) map: MapComponent;
  @ViewChildren('loadedProposes') proposeItems: QueryList<any>;


  /**
   * create a new instace
   */

  constructor(
    public navCtrl: NavController,
    public zone: NgZone,
    public loadingCtrl:LoadingController,
    public storage:Storage,
    private _navParams: NavParams,
    private _menuCtrl: MenuController,
    private _popoverCtrl: PopoverController,
    private _geolocation: Geolocation,
    private _platform: Platform,
    private _searchService: SearchService,
    private _commercesService:CommercesService,
    private _propositionsService: PropositionsService
    ) {

      this._menuCtrl.enable(true);
      this._menuCtrl.swipeEnable(false);
   }

 /**
  * get commerces
  * @return list of commerces
  */

  public ngOnInit(): any {

    ga('send', 'pageview','Home');

    this._commercesService.getCommerces().subscribe(
      data =>{
        for(let i=0; i<data.length; i++){
          this.loadedCommerces.push(new Commerce(
           data[i].id,
           data[i].agence,
           data[i].bailleur,
           data[i].arrondissement,
           data[i].adresse,
           data[i].surface_du_local,
           data[i].date_de_vacance,
           data[i].Type_de_vacance,
           data[i].photo,
           data[i].lat,
           data[i].lng,
           data[i].nb_view,
           this.markerDefaultIcon
           ));
        }
      },
      error => console.log(error)
    );
  }

  /**
   * create commerce by id
   * @return commerce
   */

  public ionViewDidLoad(): any {
    this._platform.ready().then(() => {

      let commerce_id = this._navParams.get('commerce_id');
      let sharerProposition = this._navParams.get('sharerProposition');
      let boostProposition = this._navParams.get('boostProposition');

      if(commerce_id || sharerProposition || boostProposition){
        if(commerce_id){
          var id = commerce_id;
        }else if(sharerProposition){
          var id = sharerProposition.commerce_id;
        }else if(boostProposition){
          var id = boostProposition.commerce_id;
        }
        this.getCommerceId(id,sharerProposition,boostProposition);
      } else{
        this.loadPosition();
      }
    });
  }

  /**
   * get commerce
   * @param commerce id
   * @return commerce by id
   */

  private getCommerceId(commerce_id:number, sharerProposition:Boost, boostProposition:Proposition) : any {
    setTimeout(()=>{
       const commerce = this.loadedCommerces.filter(commerce=>commerce.id==commerce_id);
       this.lat = Number(commerce[0].lat);
       this.lng = Number(commerce[0].lng);
       this.createMarkers(commerce);
       this.markers[0].src=this.markerActiveIcon;
       this.selectedCommerce = commerce[0];
       this.visibleInfoBox=false;
       this.visibleSlide=false;

       if(sharerProposition){
         this.boostInformations = sharerProposition;
         this.onSelectBoost(this.boostInformations);
       }else if(boostProposition){
         this.boostInformations = new Boost(null,null,null,null,null,null,null,null,null);
         this.selectedproposition=boostProposition;
         this.selectionType=this._navParams.get('selectionType');
         this.onstartBoost(this.selectedproposition);
       }

    },200)
  }


  /**
   * get user position
   * create markers
   * update map position
   * @return void
   */

  private loadPosition() : any{
    let options = {
      enableHighAccuracy: true,
      timeout: 600000,
      maximumAge: 10000,
    }
    this._geolocation.getCurrentPosition(options).then((position: Geoposition) => {
      // Run update inside of Angular's zone
      this.zone.run(() => {
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
        this.storage.set('Geocordination', {
          "lat": this.lat,
          "lng": this.lng
        });
        console.log("lat: ", this.lat, 'lng: ', this.lng);
        this._searchService.nearestCity(this.lat, this.lng, this.loadedCommerces).then(cities => this.createMarkers(cities));
      });
      },
      error => this._handleError(error)
    );
  }

  /**
   * create search layer
   * update map position on search
   * @return void
   */

  public presentPopover(myEvent) :any {
    let popover = this._popoverCtrl.create(SearchPage, {
      callbackMap: (_data) => {
        this.lat = Number(_data[0]);
        this.lng = Number(_data[1]);
        this.map.instance.getView().setZoom(this.zoom);
        setTimeout(()=>this.visibleInfoBox=false,3000);
      }
    }, {
      cssClass: "search-popover"
    });
    popover.present({
      ev: myEvent
    });

    popover.onDidDismiss((_data) => {
      if (_data) {

        this.selectedproposition=null;
        this.selectedCommerce=null;
        this.startPropose=false;

        this.searchedPlace=_data;
        this._searchService.nearestCity(_data.lat, _data.lng, this.loadedCommerces).then(cities => this.createMarkers(cities));
      }
    })
  }

  /**
   * listen for marker click
   * create instance of selected marker
   * @return void
   */

  public onPointerClick($event) : any {
    let pixel = this.map.instance.getEventPixel($event);
    let feature = this.map.instance.forEachFeatureAtPixel(pixel,(feature:Feature, layer) =>{
        return feature;
     });
    if(feature){
      let index = Number(feature.getId());
      this.markers.map(item=>item.src=this.markerDefaultIcon);
      this.markers[index].src=this.markerActiveIcon;
      this.visibleInfoBox=false;
      this.visibleSlide=true;
      ga('send', 'event', 'Commerce', 'click', this.markers[index].adresse);
      setTimeout(()=>{this.slides.slideTo(index);this.initSlides=true;this.slideTimeout=0},this.slideTimeout);
     }
  }

  public onMoveEnd($event){
    if(!this.selectedCommerce){
      this.visibleInfoBox=false;
      let centerpoint = this.map.instance.getView().getCenter();
      let referenceProjection: proj.Projection;
      referenceProjection = this.map.instance.getView().getProjection();
      let transformedCoordinates = proj.transform(centerpoint, 'EPSG:3857', 'EPSG:4326');
      this._searchService.nearestCity(transformedCoordinates[1], transformedCoordinates[0], this.loadedCommerces, 900).then(cities => this.createMarkers(cities,true));
    }
  }


  /**
   * listen markers navigation
   * @param direction
   * @return void
   */

  public goToSlide(direction: string) :any {
    if(!this.markers[this.activeMarkerIndex]) return;
    if(direction=="next"){
      this.activeMarkerIndex = this.slides.isEnd()?0:this.slides.getActiveIndex()+1;
    }else if(direction=="prev"){
      this.activeMarkerIndex = this.slides.isBeginning()?this.slides.length() - 1:this.slides.getActiveIndex() - 1;
    }
    this.markers.map(item=>item.src=this.markerDefaultIcon);
    this.markers[this.activeMarkerIndex].src=this.markerActiveIcon;
    this.slides.slideTo(this.activeMarkerIndex)
  }

  /**
   * set active marker icon
   * @return void
   */

  public onDidChange() :any {
    if(this.markers[this.slides.getActiveIndex()]){
      this.markers.map(item=>item.src=this.markerDefaultIcon);
      this.markers[this.slides.getActiveIndex()].src=this.markerActiveIcon;
      this.activeMarkerIndex=this.slides.getActiveIndex();
      // this.lat = this.markers[this.slides.getActiveIndex()].lat;
      // this.lng = this.markers[this.slides.getActiveIndex()].lng;
      //this._searchService.nearestCity(this.lat, this.lng, this.loadedCommerces).then(cities => this.createMarkers(cities));

    }
  }

/**
 * set default active marker
 * @return void
 */

 public onReachStart() :any {
   if(this.markers.length==1){
     this.markers[0].src=this.markerActiveIcon;
   }
 }

  /**
   * get propositions
   * create propositions layer
   * @return void
   */

  public loadPropositions() : any{
    let loading = this.loadingCtrl.create({
      spinner:'crescent',
      content: '',
      cssClass:'custom-loading white-spinner',
    });
    loading.present();
    this._propositionsService.getTypes().subscribe(
      data => {
        this.selectionType="envie";
        for(let i=0; i<data.length; i++){
          let type = new Type(data[i].id,data[i].name,data[i].icon,data[i].choices);
          this.types.push(type);
        }
        loading.dismiss();
        loading.onDidDismiss(() => {
          this.startPropose=true;
        });
      },
      error => console.log(error)
    );
  }

  /**
   * create new proposition instance
   * @param $event
   * @return selectedproposition
  */

  public onProposition(event:Proposition) : any{
    const proposition = new Proposition(
      event.commerce_id,
      event.type_id,
      event.soustype_id,
      event.user_id,
      event.number_propositions
    );
    this.selectedproposition = proposition;

    if(this.types.length){
      let selectedType, selectedSubType;

      for(let i=0; i<this.types.length;i++){
        if(this.types[i].id==this.selectedproposition.type_id){
          selectedType = this.types[i];
          break;
        }
      }

      for(let i=0; i<selectedType.choices.length;i++){
        if(selectedType.choices[i].id==this.selectedproposition.soustype_id){
          selectedSubType = selectedType.choices[i];
          break;
        }
      }
      ga('send', 'event', 'Proposer une envie', 'Click', 'Suivant: '+selectedType.name+': '+selectedSubType.name);

    }

  }


public onBackProposition($event:Commerce){
  this.selectedproposition=null;
  this.selectedCommerce=null;
  this.startPropose=false;
  this.types=[];
  this._searchService.nearestCity($event.lat, $event.lng, this.loadedCommerces).then(cities => this.createMarkers(cities));
}

  /**
   * watch creation of proposeItems
   * @return void
  */

  public ngAfterViewInit() : any{
    this.proposeItems.changes.subscribe(t => {
      //console.log(t._results)
    })
  }

  /**
   * create boost layer
   * @param $event
   * @return void
  */

  public onstartBoost($event) : any{
    this.startBoost=$event;
  }

  /**
   * create new boost instance
   * @param $event
   * @return boostInformations
  */

  public onSelectBoost($event:Boost){
    this.startShare=true;
    this.boostInformations=new Boost(
      $event.proposition_id,
      $event.commerce_id,
      $event.type_id,
      $event.soustype_id,
      $event.user_id,
      $event.number_propositions,
      $event.frequentation,
      $event.budget,
      $event.periode,
    );
  }

  /**
   * create suggestion layer
   * @param $event
   * @return loadedSuggestions
  */

  public onLoadedSuggestions($event) : any {
    if($event===null){
      this.startSuggestion=false;
      this.selectedSuggestion=false;
      this.loadPropositions();
      return;
    }
     this.loadedSuggestions=$event;
  }

  /**
   * listen suggestion type
   * @return boolean
  */

  public loadSuggestion() : any{
    this.selectionType="suggestion";
    this.startSuggestion=true;
  }

  /**
   * start recommend layer
   * save the selected commerce
   * @return selected commerce
  */

  public startRecommend() :any {

    this.selectedCommerce = this.markers[this.activeMarkerIndex];
    this.markers=[this.selectedCommerce];
    this.visibleSlide=false;
    this.lat = this.markers[0].lat;
    this.lng = this.markers[0].lng;
    ga('send', 'event', 'Recommander un besoin', 'Click', this.selectedCommerce.adresse);
    this._commercesService.setView(this.selectedCommerce.id).subscribe(
      result=>{
        this.selectedCommerce.nb_view=result.data.nb_view;
       },
      error=>console.log(error)
    )
  }

  /**
   * create markers list
   * show markers length informations
   * save the selected commerce
   * @return void
  */

  private createMarkers(items: Commerce[], onRefilterMap=false): any {
    this.markers = [];
    for (let i = 0; i < items.sort(this._compare).length; i++) {
      this.markers.push(new Commerce(
        items[i].id,
        items[i].agence,
        items[i].bailleur,
        items[i].arrondissement,
        items[i].adresse,
        items[i].surface_du_local,
        items[i].date_de_vacance,
        items[i].type_de_vacance,
        items[i].photo,
        Number(items[i].lat),
        Number(items[i].lng),
        items[i].nb_view,
        this.markerDefaultIcon
      ));
    }
    this.visibleSlide=false;
    this.initSlides=false;
    this.slideTimeout = 600;

    if(!onRefilterMap){
      this.visibleInfoBox=true;
    }
    this.map.instance.updateSize();
  }

  /**
   * http://www.java2s.com/Tutorials/Javascript/Javascript_Tutorial/Array/Reorder_an_array_in_Javascript.htm
   * reorder commerces Array based on distance between each commerce
   * @param lat, lng
   * @return position
  */

  private _compare(value1, value2) : number{
     if (value1.lng < value2.lng) {
         return -1;
     } else if (value1.lng > value2.lng) {
         return 1;
     } else {
         return 0;
     }
   }

   /**
    * handle geolocation error
    * get stored user position
    * @return void
   */

  private _handleError(err) :any {
    console.log(err);
    this.storage.get('Geocordination').then(coordinations=>{
      if(coordinations){
        this.lat = Number(coordinations.lat);
        this.lng = Number(coordinations.lng);
      }
      this.presentPopover({});
    })
  }

  /**
   * filter nearest commerces
   * @param lat, lng
   * @return list of commerces
  */

  // private NearestCity(latitude: number, longitude: number): Promise < any > {
  //   return new Promise < any > ((resolve, reject) => {
  //     let max = 1000;
  //     let closest;
  //     let selected = [];
  //     for (let index = 0; index < this.loadedCommerces.length; ++index) {
  //       let dif = this._searchService.getDistance(latitude, longitude, this.loadedCommerces[index].lat, this.loadedCommerces[index].lng);
  //       if (dif <= max) {
  //         closest = index;
  //         max = dif;
  //         selected.push(this.loadedCommerces[closest])
  //       }
  //     }
  //     resolve(selected);
  //   });
  // }

  // private geobackup() {
  //   let geolocation = new ol.Geolocation({
  //     // take the projection to use from the map's view
  //     projection: this.map.instance.getView().getProjection(),
  //     trackingOptions: {
  //       maximumAge: 10000,
  //       enableHighAccuracy: true,
  //       timeout: 600000
  //     }
  //   });
  //   console.log(this.map.instance.getView().getProjection())
  //   geolocation.setTracking(true);
  //   // listen to changes in position
  //   geolocation.on('change', (evt) => {
  //     this.lat = geolocation.getPosition()[1];
  //     this.lng = geolocation.getPosition()[0];
  //     //this.map.instance.getView().setCenter(geolocation.getPosition());
  //   });
  // }


}

0 ответов

Другие вопросы по тегам