Как я могу отобразить расстояние между двумя маркерами в милях и километрах на собственных Картах Google? (Кордова, Ионная 3) - PullRequest
0 голосов
/ 27 апреля 2018

Как я могу отобразить расстояние между двумя маркерами в милях и км на родных картах Google Ionic? Я хочу отобразить числа в правой верхней части карты, используя теги h3.

и есть ли способ отобразить примерное время в пути? Мне нужно оценить время для прогулок и вождения.

Любой пример кода будет оценен.

Спасибо

1 Ответ

0 голосов
/ 27 апреля 2018

Я использовал Google Maps Служба маршрутов API для отображения расстояния между двумя местами.

Сначала установите библиотеку Карт Google, используя эту команду:

npm install @types/googlemaps --save-dev

Теперь перейдите к node_modules, а затем к @types и в эту папку карт Google и добавьте строку ниже:

declare module 'googlemaps';

Теперь мы будем использовать библиотеку JavaScript Карт Google для получения информации о местах. Поэтому включите js-файл Google Maps в файл index.html:

<script src="http://maps.google.com/maps/api/js?key=XXXXX=places"></script>
  • Приведенному выше сценарию требуется ключ API Карт Google. Следуй этим шагам:
    • Перейти к https://console.developers.google.com
    • Создайте новый проект Google и присвойте подходящее имя вашему проекту
    • Как только вы создадите новый проект, он перенаправит вас в раздел API и щелкнет Google Maps JavaScript API
    • Нажмите включить API. Затем нажмите «Создать учетные данные» и нажмите «Какие учетные данные мне нужны?»
    • Вот и все. Это даст вам ключ API Карт Google

Затем установите плагин геолокации, чтобы получить доступ к местоположению пользователя:

ionic cordova plugin add cordova-plugin-geolocation
npm install --save @ionic-native/geolocation

Теперь для импорта плагина геолокации в app.module.ts file:

import { Geolocation } from '@ionic-native/geolocation';      
@NgModule({    
     ...   
     providers: [  Geolocation   ]  
     ... })

Затем импортируйте класс карт Google и плагин геолокации в файл home.ts :

import { Geolocation ,GeolocationOptions } from '@ionic-native/geolocation';

import { googlemaps } from 'googlemaps';

Теперь добавьте следующий код в ваш home.ts файл:

import { Component, ElementRef, ViewChild } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Geolocation ,GeolocationOptions ,Geoposition ,PositionError } from '@ionic-native/geolocation';
import { googlemaps } from 'googlemaps';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})


export class HomePage {

  @ViewChild('map') mapElement: ElementRef;
  @ViewChild('directionsPanel') directionsPanel: ElementRef;

  map:any;
  latLng:any;
  markers:any;
  mapOptions:any;

  startService:any;
  autocompleteStart:any;

  endService:any;
  autocompleteEnd:any;

  directionsService = new google.maps.DirectionsService;
  directionsDisplay = new google.maps.DirectionsRenderer;
  start:any;
  end:any;
  travelType:any = 'DRIVING';

  //distance and duration
  distance:any='';
  duration:any='';

  constructor(private geolocation : Geolocation) { }

  ionViewDidLoad() {
    this.loadMap();
    this.startService = new google.maps.places.AutocompleteService();        
    this.autocompleteStart = [];
    this.endService = new google.maps.places.AutocompleteService();        
    this.autocompleteEnd = [];      
    this.start = '';
    this.end = '';
  }

  loadMap(){

    this.geolocation.getCurrentPosition().then((position) => {

      this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      console.log('latLng',this.latLng);

      this.mapOptions = {
        center: this.latLng,
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }   

      this.map = new google.maps.Map(this.mapElement.nativeElement, this.mapOptions);

    }, (err) => {
      alert('err '+err);
    });

  }

/*-----------------------Search Direction--------------------*/

  startSearch() {

    if (this.start == '') {
      this.autocompleteStart = [];
      return;
    }

    let self = this; 

    let config = { 
      input: this.start, 
      componentRestrictions: {  } 
    }

    this.startService.getPlacePredictions(config, function (predictions, status) {
      console.log('modal > getPlacePredictions > status > ', status);
      self.autocompleteStart = [];            
      predictions.forEach(function (prediction) {              
      self.autocompleteStart.push(prediction);
      });
    });

  }

  endSearch() {

    if (this.end == '') {
      this.autocompleteEnd = [];
      return;
    }

    let self = this; 

    let config = { 
      input: this.end, 
      componentRestrictions: {  } 
    }

    this.endService.getPlacePredictions(config, function (predictions, status) {
      console.log('modal > getPlacePredictions > status > ', status);
      self.autocompleteEnd = [];            
      predictions.forEach(function (prediction) {              
        self.autocompleteEnd.push(prediction);
      });
    });
  }

  chooseStart(item){
    console.log('item',item);
    this.start = item.description; 
    this.autocompleteStart = [];
  }

  chooseEnd(item){
    console.log('item',item);
    this.end = item.description;
    this.autocompleteEnd = [];
  }

/*--------------------Get Direction beteen to places-----------------------*/

  getDirections(){

    this.directionsDisplay.setMap(this.map);
    this.directionsDisplay.setPanel(this.directionsPanel.nativeElement);

    this.directionsService.route({
      origin : this.start,
      destination : this.end,
      waypoints: this.wayPoints,
      optimizeWaypoints: true,
      travelMode : this.travelType,
      provideRouteAlternatives: true,
    }, (response, status) => {
        if (status == google.maps.DirectionsStatus.OK) {
         this.directionsDisplay.setDirections(response);
          // Create a new DirectionsRenderer for each route
        for (var i = 0; i < response.routes.length; i++) {
            var dr = new google.maps.DirectionsRenderer();
            dr.setDirections(response);
            // Tell the DirectionsRenderer which route to display
            dr.setRouteIndex(i);
            dr.setMap(this.map);

            // Code ommited to display distance and duration
           let x = i+1;
            // Display the distance:
             this.distance += x +') '+ response.routes[i].legs[0].distance.text +', ' ;
             console.log('distance',this.distance);
            // Display the duration:
            this.duration += x +') '+ response.routes[i].legs[0].duration.text +', ' ;
            console.log('duration',this.duration);
        }

       // this.directionsDisplay.setDirections(response);
        console.log('response:-',response);
      } else {
        alert('Directions request failed due to ' + status);
      }
    });
  }

}

Теперь добавьте следующий код в ваш home.html файл:

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Map
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

<!--====================== For Get Direction ==========================-->

<form align="center">

    <ion-searchbar 
    [(ngModel)]="start" 
    name="start"
    [showCancelButton]="shouldShowCancel" 
    (ionInput)="startSearch()" 
    (ionCancel)="dismiss()"
    placeholder="Starting Places">
    </ion-searchbar>
    <ion-list>
        <ion-item *ngFor="let item of autocompleteStart" (click)="chooseStart(item)">
            {{ item.description }}
        </ion-item>
    </ion-list>


    <ion-searchbar 
    [(ngModel)]="end" 
    name="end"
    [showCancelButton]="shouldShowCancel" 
    (ionInput)="endSearch()" 
    (ionCancel)="dismiss()"
    placeholder="Ending Places">
    </ion-searchbar>
    <ion-list>
        <ion-item *ngFor="let item of autocompleteEnd" (click)="chooseEnd(item)">
            {{ item.description }}
        </ion-item>
    </ion-list>

    <button ion-button round (click)="getDirections()">GO</button>

</form>

<br>
  <div *ngIf="distance && duration">
    <b>Distance :- {{distance}}</b><br>
    <b>Duration :- {{duration}}</b>
  </div>

<br>
    <div #map id="map"></div>

    <ion-card>
        <ion-card-content>
            <div #directionsPanel></div>
        </ion-card-content>
    </ion-card>

</ion-content>
...